-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syntax_cheatsheet(atomic).py
636 lines (512 loc) · 17.5 KB
/
syntax_cheatsheet(atomic).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
class MainMenu:
def __init__(self):
self.topics = {
'1': ("\033[94mFormats", FormatMenu()),
'2': ("\033[93mClasses", ClassMenu()),
'3': ("\033[92mControl Flow", ControlFlowMenu()),
'4': ("\033[95mIterators", IteratorMenu()),
'5': ("\033[96mDecorators", DecoratorMenu()),
'6': ("\033[93mFunctions", FunctionMenu()),
'7': ("\033[94mList and Tuples", ListandTuplesMenu()),
'8': ("\033[95mDictionaries\033[0m", DictionaryMenu()),
}
def display(self):
print("\033[96m=== Main Menu ===\033[0m")
for key, topic in self.topics.items():
print(f"{key}. {topic[0]}")
print("0. Exit")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '0':
print("Goodbye!")
break
if choice in self.topics:
sub_menu = self.topics[choice][1]
sub_menu.run()
class SubMenu:
def __init__(self, examples):
self.examples = examples
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. {example}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
print("Running example:", self.examples[int(choice) - 1])
input("Press Enter to continue...")
else:
print("Invalid choice!")
class FormatMenu(SubMenu):
def __init__(self):
examples = [
'''name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message) # Output: "My name is Alice and I am 25 years old."''',
'''pi = 3.14159
message = "The value of pi is approximately {:.2f}".format(pi)
print(message) # Output: "The value of pi is approximately 3.14"''',
'''from string import Template
name = "Bob"
age = 30
template = Template("$name is $age years old.")
message = template.substitute(name=name, age=age)
print(message) # Output: "Bob is 30 years old."'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class ClassMenu(SubMenu):
def __init__(self):
examples = [
'''class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
def __str__(self):
return f"Rectangle: length={self.length}, width={self.width}"''',
'''class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
self.grades = []
def add_grade(self, grade):
self.grades.append(grade)
def average_grade(self):
if len(self.grades) == 0:
return 0
return sum(self.grades) / len(self.grades)
def __str__(self):
return f"Student: name={self.name}, age={self.age}, major={self.major}"''',
'''class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
else:
self.balance -= amount
def __str__(self):
return f"Account: number={self.account_number}, balance={self.balance}"'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class ControlFlowMenu(SubMenu):
def __init__(self):
examples = [
'''# Dynamic Formatting and If-Else Example
favorite_color = input("What is your favorite color? ")
if favorite_color.lower() == "blue":
print(f"Oh, {favorite_color} is a calming and serene color!")
elif favorite_color.lower() == "red":
print(f"{favorite_color} is a bold and energetic color!")
elif favorite_color.lower() == "green":
print(f"{favorite_color} represents nature and growth!")
else:
print(f"{favorite_color} is a great choice!")
''',
'''# While Loop with User Input Example
total = 0
while True:
number = int(input("Enter a number (enter 0 to stop): "))
if number == 0:
break # Exit the loop if the user enters 0
total += number
print(f"The sum of all numbers entered is: {total}")
''',
'''# For Loop with Range and If-Else Example
for num in range(1, 11):
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class IteratorMenu(SubMenu):
def __init__(self):
examples = [
'''# Using an Iterator with a List
fruits = ["apple", "banana", "orange"]
# Create an iterator from the list
fruit_iterator = iter(fruits)
# Iterate through the elements using a loop
for fruit in fruit_iterator:
print(fruit)
''',
'''# Creating a Custom Iterator
class SquaresIterator:
def __init__(self, max_value):
self.current = 0
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
if self.current > self.max_value:
raise StopIteration
square = self.current ** 2
self.current += 1
return square
# Create a custom iterator that generates squares up to 9
squares_iterator = SquaresIterator(3)
# Iterate through the squares
for square in squares_iterator:
print(square)
''',
'''# Using the built-in enumerate() function
fruits = ["apple", "banana", "orange"]
# Iterate through the list and get both index and value
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class DecoratorMenu(SubMenu):
def __init__(self):
examples = [
'''# Simple Function Decorator
def greet():
return "Hello!"
# Define a decorator function
def uppercase_decorator(func):
def wrapper():
original_result = func()
modified_result = original_result.upper()
return modified_result
return wrapper
# Apply the decorator to the greet() function
greet = uppercase_decorator(greet)
# Call the decorated function
print(greet()) # Output: "HELLO!"
''',
'''# Decorator with Arguments
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
# Apply the decorator with argument to the greet() function
@repeat(num_times=3)
def greet(name):
return f"Hello, {name}!"
# Call the decorated function
print(greet("Alice"))
''',
'''# Chaining Multiple Decorators
def uppercase_decorator(func):
def wrapper():
original_result = func()
modified_result = original_result.upper()
return modified_result
return wrapper
def exclamation_decorator(func):
def wrapper():
original_result = func()
modified_result = original_result + "!"
return modified_result
return wrapper
# Apply multiple decorators to the greet() function
@exclamation_decorator
@uppercase_decorator
def greet():
return "hello"
# Call the decorated function
print(greet()) # Output: "HELLO!"
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class FunctionMenu(SubMenu):
def __init__(self):
examples = [
'''# Function with Default Parameters
def greet(name="Guest"):
return f"Hello, {name}!"
# Call the function without arguments
print(greet()) # Output: "Hello, Guest!"
# Call the function with an argument
print(greet("Alice")) # Output: "Hello, Alice!"
''',
'''# Recursive Function
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Calculate factorial of 5
result = factorial(5)
print("Factorial of 5:", result) # Output: 120
''',
'''# Lambda Functions
# Define a lambda function to square a number
square = lambda x: x**2
# Use the lambda function
print(square(5)) # Output: 25
# Lambda function as an argument in a higher-order function
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
''',
'''# Example 4: Closure
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
# Create closures with different values of x
closure1 = outer_function(10)
closure2 = outer_function(20)
print(closure1(5)) # Output: 15
print(closure2(5)) # Output: 25
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class ListandTuplesMenu(SubMenu):
def __init__(self):
examples = [
'''# List Comprehension
# Generate a list of even numbers from 1 to 10
even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]''',
'''# Tuple Unpacking
# Define a tuple
person = ('John', 30, 'Engineer')
# Unpack the tuple into variables
name, age, profession = person
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Profession: {profession}")
''',
'''# List Concatenation and Slicing
# Create two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenate the two lists
concatenated_list = list1 + list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
# Get a sublist using slicing
sublist = concatenated_list[2:5]
print(sublist) # Output: [3, 4, 5]
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
class DictionaryMenu(SubMenu):
def __init__(self):
examples = [
'''# Example 1: Creating a Dictionary
# Using curly braces and key-value pairs
person = {
'name': 'John',
'age': 30,
'occupation': 'Engineer'
}
# Using dict() constructor with keyword arguments
person = dict(name='John', age=30, occupation='Engineer')
print(person) # Output: {'name': 'John', 'age': 30, 'occupation': 'Engineer'}
''',
'''# Example 2: Dictionary Comprehension
# Create a dictionary of squares from 1 to 5
squares = {num: num**2 for num in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
''',
'''# Example 3: Merging Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Using the update() method
merged_dict = dict1.copy()
merged_dict.update(dict2)
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Using dictionary unpacking in Python 3.9+
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
''',
'''# Example 4: Iterating Over a Dictionary
person = {
'name': 'John',
'age': 30,
'occupation': 'Engineer'
}
# Iterate over keys
print("Keys:")
for key in person:
print(key)
# Iterate over values
print("\nValues:")
for value in person.values():
print(value)
# Iterate over key-value pairs
print("\nKey-Value Pairs:")
for key, value in person.items():
print(key, ":", value)
'''
]
super().__init__(examples)
def display(self):
print("=== Sub Menu ===")
for i, example in enumerate(self.examples, 1):
print(f"{i}. Example {i}")
print("-1. Back")
def run(self):
while True:
self.display()
choice = input("Enter your choice: ")
if choice == '-1':
break
if choice.isdigit() and int(choice) <= len(self.examples):
example_code = self.examples[int(choice) - 1]
print(f"Running Example {int(choice)}:")
print(example_code)
exec(example_code)
input("Press Enter to continue...")
else:
print("Invalid choice!")
if __name__ == '__main__':
main_menu = MainMenu()
main_menu.run()