-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_mastery.py
More file actions
1358 lines (1076 loc) · 35.6 KB
/
Copy pathpython_mastery.py
File metadata and controls
1358 lines (1076 loc) · 35.6 KB
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PYTHON MASTERY: Complete Beginner-Friendly Reference
====================================================
This file contains a comprehensive guide to Python programming, covering all major
concepts from basic syntax to advanced topics. Each section includes:
- Clear explanations
- Runnable examples
- Expected outputs
- Best practices
Run this file to see all examples in action!
"""
# =============================================================================
# 1. BASIC SYNTAX, VARIABLES, AND DATA TYPES
# =============================================================================
print("=" * 60)
print("1. BASIC SYNTAX, VARIABLES, AND DATA TYPES")
print("=" * 60)
# Variables in Python are dynamically typed - no need to declare types
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
nothing = None # None type
print(f"Name: {name}, Type: {type(name)}")
print(f"Age: {age}, Type: {type(age)}")
print(f"Height: {height}, Type: {type(height)}")
print(f"Is Student: {is_student}, Type: {type(is_student)}")
print(f"Nothing: {nothing}, Type: {type(nothing)}")
# Multiple assignment
x, y, z = 1, 2, 3
print(f"x={x}, y={y}, z={z}")
# Type conversion
num_str = "42"
num_int = int(num_str) # Convert string to integer
num_float = float(num_str) # Convert string to float
print(f"String '{num_str}' -> int: {num_int}, float: {num_float}")
# =============================================================================
# 2. STRINGS
# =============================================================================
print("\n" + "=" * 60)
print("2. STRINGS")
print("=" * 60)
# String creation and basic operations
text = "Hello, World!"
print(f"Original: {text}")
print(f"Length: {len(text)}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}")
print(f"Replace: {text.replace('World', 'Python')}")
# String formatting (multiple ways)
name = "Bob"
age = 30
# f-strings (Python 3.6+, recommended)
message1 = f"Hello, {name}! You are {age} years old."
print(f"f-string: {message1}")
# .format() method
message2 = "Hello, {}! You are {} years old.".format(name, age)
print(f".format(): {message2}")
# % formatting (older style)
message3 = "Hello, %s! You are %d years old." % (name, age)
print(f"% formatting: {message3}")
# String slicing and indexing
text = "Python Programming"
print(f"First character: {text[0]}")
print(f"Last character: {text[-1]}")
print(f"First 6 characters: {text[:6]}")
print(f"Characters 7-11: {text[7:12]}")
print(f"Every 2nd character: {text[::2]}")
# String methods
text = " hello world "
print(f"Strip whitespace: '{text.strip()}'")
print(f"Split into words: {text.strip().split()}")
print(f"Join with dashes: {'-'.join(['hello', 'world'])}")
# =============================================================================
# 3. LISTS
# =============================================================================
print("\n" + "=" * 60)
print("3. LISTS")
print("=" * 60)
# Creating lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
print(f"Numbers: {numbers}")
print(f"Fruits: {fruits}")
print(f"Mixed: {mixed}")
# List operations
numbers.append(6) # Add to end
numbers.insert(0, 0) # Insert at index
print(f"After append and insert: {numbers}")
# List slicing (same as strings)
print(f"First 3: {numbers[:3]}")
print(f"Last 3: {numbers[-3:]}")
print(f"Every 2nd: {numbers[::2]}")
# List methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"Original: {numbers}")
print(f"Sorted: {sorted(numbers)}")
print(f"Count of 1: {numbers.count(1)}")
print(f"Index of 5: {numbers.index(5)}")
# List comprehensions (powerful way to create lists)
squares = [x**2 for x in range(5)]
print(f"Squares: {squares}")
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(f"Even squares: {even_squares}")
# =============================================================================
# 4. TUPLES
# =============================================================================
print("\n" + "=" * 60)
print("4. TUPLES")
print("=" * 60)
# Tuples are immutable (cannot be changed after creation)
coordinates = (3, 4)
person = ("Alice", 25, "Engineer")
print(f"Coordinates: {coordinates}")
print(f"Person: {person}")
print(f"X coordinate: {coordinates[0]}")
print(f"Name: {person[0]}")
# Tuple unpacking
x, y = coordinates
name, age, job = person
print(f"Unpacked: x={x}, y={y}")
print(f"Unpacked: name={name}, age={age}, job={job}")
# Tuples are often used for multiple return values
def get_name_and_age():
return "Bob", 30
name, age = get_name_and_age()
print(f"Function returned: name={name}, age={age}")
# =============================================================================
# 5. SETS
# =============================================================================
print("\n" + "=" * 60)
print("5. SETS")
print("=" * 60)
# Sets store unique elements (no duplicates)
fruits = {"apple", "banana", "cherry", "apple"} # Duplicate removed
print(f"Fruits set: {fruits}")
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(f"Set 1: {set1}")
print(f"Set 2: {set2}")
print(f"Union: {set1 | set2}")
print(f"Intersection: {set1 & set2}")
print(f"Difference: {set1 - set2}")
print(f"Symmetric difference: {set1 ^ set2}")
# Set methods
numbers = {1, 2, 3}
numbers.add(4)
numbers.remove(2) # Raises error if not found
numbers.discard(5) # Doesn't raise error if not found
print(f"After operations: {numbers}")
# =============================================================================
# 6. DICTIONARIES
# =============================================================================
print("\n" + "=" * 60)
print("6. DICTIONARIES")
print("=" * 60)
# Dictionaries store key-value pairs
person = {
"name": "Alice",
"age": 25,
"city": "New York",
"hobbies": ["reading", "swimming"]
}
print(f"Person: {person}")
print(f"Name: {person['name']}")
print(f"Age: {person.get('age', 'Unknown')}")
# Dictionary operations
person["email"] = "alice@example.com" # Add new key
person["age"] = 26 # Update existing key
print(f"After updates: {person}")
# Dictionary methods
print(f"Keys: {list(person.keys())}")
print(f"Values: {list(person.values())}")
print(f"Items: {list(person.items())}")
# Dictionary comprehensions
squares_dict = {x: x**2 for x in range(5)}
print(f"Squares dict: {squares_dict}")
# =============================================================================
# 7. CONDITIONALS
# =============================================================================
print("\n" + "=" * 60)
print("7. CONDITIONALS")
print("=" * 60)
# Basic if-elif-else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score {score} gets grade: {grade}")
# Comparison operators
a, b = 10, 20
print(f"a = {a}, b = {b}")
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
print(f"a < b: {a < b}")
print(f"a <= b: {a <= b}")
print(f"a > b: {a > b}")
print(f"a >= b: {a >= b}")
# Logical operators
x, y = True, False
print(f"x = {x}, y = {y}")
print(f"x and y: {x and y}")
print(f"x or y: {x or y}")
print(f"not x: {not x}")
# Ternary operator (conditional expression)
age = 17
status = "adult" if age >= 18 else "minor"
print(f"Age {age} is {status}")
# =============================================================================
# 8. LOOPS
# =============================================================================
print("\n" + "=" * 60)
print("8. LOOPS")
print("=" * 60)
# For loop with range
print("For loop with range:")
for i in range(5):
print(f" i = {i}")
# For loop with list
print("\nFor loop with list:")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f" {fruit}")
# For loop with enumerate (get both index and value)
print("\nFor loop with enumerate:")
for i, fruit in enumerate(fruits):
print(f" {i}: {fruit}")
# For loop with dictionary
print("\nFor loop with dictionary:")
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key, value in person.items():
print(f" {key}: {value}")
# While loop
print("\nWhile loop:")
count = 0
while count < 3:
print(f" Count: {count}")
count += 1
# Loop control: break and continue
print("\nLoop with break and continue:")
for i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit loop
print(f" i = {i}")
# Else clause with loops (runs when loop completes normally)
print("\nLoop with else clause:")
for i in range(3):
print(f" i = {i}")
else:
print(" Loop completed normally!")
# =============================================================================
# 9. FUNCTIONS
# =============================================================================
print("\n" + "=" * 60)
print("9. FUNCTIONS")
print("=" * 60)
# Basic function
def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
print(greet("Alice"))
# Function with default parameters
def greet_with_title(name, title="Mr./Ms."):
return f"Hello, {title} {name}!"
print(greet_with_title("Smith"))
print(greet_with_title("Smith", "Dr."))
# Function with multiple parameters
def calculate_area(length, width):
return length * width
print(f"Area: {calculate_area(5, 3)}")
# Function with *args (variable number of positional arguments)
def sum_all(*args):
return sum(args)
print(f"Sum of 1,2,3,4: {sum_all(1, 2, 3, 4)}")
print(f"Sum of 10,20: {sum_all(10, 20)}")
# Function with **kwargs (variable number of keyword arguments)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f" {key}: {value}")
print("Info with kwargs:")
print_info(name="Alice", age=25, city="NYC")
# Function with both *args and **kwargs
def flexible_function(*args, **kwargs):
print(f"Positional args: {args}")
print(f"Keyword args: {kwargs}")
flexible_function(1, 2, 3, name="Alice", age=25)
# Lambda functions (anonymous functions)
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")
# Lambda with multiple parameters
add = lambda x, y: x + y
print(f"Add 3 and 4: {add(3, 4)}")
# =============================================================================
# 10. CLASSES AND OBJECT-ORIENTED PROGRAMMING
# =============================================================================
print("\n" + "=" * 60)
print("10. CLASSES AND OBJECT-ORIENTED PROGRAMMING")
print("=" * 60)
# Basic class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name} and I'm {self.age} years old."
def have_birthday(self):
self.age += 1
return f"Happy birthday! Now I'm {self.age} years old."
# Create an instance
person = Person("Alice", 25)
print(person.greet())
print(person.have_birthday())
# Class with class variables and methods
class BankAccount:
# Class variable (shared by all instances)
bank_name = "Python Bank"
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
return f"Deposited ${amount}. New balance: ${self.balance}"
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return f"Withdrew ${amount}. New balance: ${self.balance}"
else:
return "Insufficient funds!"
@classmethod
def get_bank_name(cls):
return cls.bank_name
@staticmethod
def calculate_interest(principal, rate, time):
return principal * rate * time
# Using the class
account = BankAccount("Bob", 1000)
print(account.deposit(500))
print(account.withdraw(200))
print(f"Bank name: {BankAccount.get_bank_name()}")
print(f"Interest: ${BankAccount.calculate_interest(1000, 0.05, 2)}")
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call parent constructor
self.student_id = student_id
self.courses = []
def enroll(self, course):
self.courses.append(course)
return f"Enrolled in {course}"
def greet(self): # Override parent method
return f"Hi, I'm {self.name}, student ID: {self.student_id}"
student = Student("Charlie", 20, "S12345")
print(student.greet())
print(student.enroll("Python Programming"))
# =============================================================================
# 11. DECORATORS
# =============================================================================
print("\n" + "=" * 60)
print("11. DECORATORS")
print("=" * 60)
# Simple decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
# Decorator with parameters
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
print("\nRepeated greeting:")
greet("Bob")
# Built-in decorators
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
circle = Circle(5)
print(f"Circle radius: {circle.radius}")
print(f"Circle area: {circle.area:.2f}")
# =============================================================================
# 12. FILE HANDLING
# =============================================================================
print("\n" + "=" * 60)
print("12. FILE HANDLING")
print("=" * 60)
# Writing to a file
filename = "example.txt"
with open(filename, "w") as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.write("Python is awesome!\n")
print(f"Created file: {filename}")
# Reading from a file
with open(filename, "r") as file:
content = file.read()
print(f"File content:\n{content}")
# Reading line by line
with open(filename, "r") as file:
lines = file.readlines()
print("Lines:")
for i, line in enumerate(lines, 1):
print(f" {i}: {line.strip()}")
# Appending to a file
with open(filename, "a") as file:
file.write("This line was appended.\n")
print("Appended to file")
# JSON handling
import json
# Create a dictionary
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "swimming"],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
# Write to JSON file
with open("data.json", "w") as file:
json.dump(data, file, indent=2)
print("Created JSON file: data.json")
# Read from JSON file
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(f"Loaded data: {loaded_data}")
# CSV handling
import csv
# Write CSV file
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "New York"])
writer.writerow(["Bob", 30, "Boston"])
writer.writerow(["Charlie", 35, "Chicago"])
print("Created CSV file: data.csv")
# Read CSV file
with open("data.csv", "r") as file:
reader = csv.reader(file)
print("CSV content:")
for row in reader:
print(f" {row}")
# =============================================================================
# 13. MODULES AND PACKAGES
# =============================================================================
print("\n" + "=" * 60)
print("13. MODULES AND PACKAGES")
print("=" * 60)
# Importing modules
import math
import random
from datetime import datetime, timedelta
# Using math module
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Pi: {math.pi}")
print(f"Ceiling of 4.3: {math.ceil(4.3)}")
# Using random module
print(f"Random integer (1-10): {random.randint(1, 10)}")
print(f"Random float (0-1): {random.random()}")
print(f"Random choice from list: {random.choice(['apple', 'banana', 'cherry'])}")
# Using datetime module
now = datetime.now()
print(f"Current time: {now}")
print(f"Formatted time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")
# Creating a simple module (simulated)
def add_numbers(a, b):
return a + b
def multiply_numbers(a, b):
return a * b
# This would normally be in a separate file called mymath.py
print(f"Using local functions: {add_numbers(3, 4)}")
# =============================================================================
# 14. ERROR HANDLING AND EXCEPTIONS
# =============================================================================
print("\n" + "=" * 60)
print("14. ERROR HANDLING AND EXCEPTIONS")
print("=" * 60)
# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
# Multiple exception types
try:
value = int("not_a_number")
except ValueError as e:
print(f"ValueError: {e}")
except Exception as e:
print(f"Other error: {e}")
# Try-except-else-finally
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
except TypeError:
print("Invalid input types!")
return None
else:
print("Division successful!")
return result
finally:
print("This always runs!")
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return True
try:
validate_age(-5)
except ValueError as e:
print(f"Validation error: {e}")
# Custom exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def check_positive(number):
if number < 0:
raise CustomError("Number must be positive")
return number
try:
check_positive(-1)
except CustomError as e:
print(f"Custom error: {e}")
# =============================================================================
# 15. COMPREHENSIONS
# =============================================================================
print("\n" + "=" * 60)
print("15. COMPREHENSIONS")
print("=" * 60)
# List comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square all numbers
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")
# Even numbers only
evens = [x for x in numbers if x % 2 == 0]
print(f"Even numbers: {evens}")
# Square only even numbers
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"Even squares: {even_squares}")
# Dictionary comprehensions
word_lengths = {word: len(word) for word in ["apple", "banana", "cherry"]}
print(f"Word lengths: {word_lengths}")
# Set comprehensions
unique_lengths = {len(word) for word in ["apple", "banana", "cherry", "date"]}
print(f"Unique lengths: {unique_lengths}")
# Nested comprehensions
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(f"Flattened matrix: {flattened}")
# =============================================================================
# 16. GENERATORS AND ITERATORS
# =============================================================================
print("\n" + "=" * 60)
print("16. GENERATORS AND ITERATORS")
print("=" * 60)
# Generator function
def count_up_to(max_count):
count = 1
while count <= max_count:
yield count
count += 1
# Using the generator
counter = count_up_to(5)
print("Generator values:")
for value in counter:
print(f" {value}")
# Generator expression
squares_gen = (x**2 for x in range(5))
print(f"Generator expression: {list(squares_gen)}")
# Iterator protocol
class CountDown:
def __init__(self, start):
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.start <= 0:
raise StopIteration
self.start -= 1
return self.start + 1
print("Countdown iterator:")
for i in CountDown(3):
print(f" {i}")
# =============================================================================
# 17. LAMBDA, MAP, FILTER, REDUCE
# =============================================================================
print("\n" + "=" * 60)
print("17. LAMBDA, MAP, FILTER, REDUCE")
print("=" * 60)
# Lambda functions
square = lambda x: x ** 2
add = lambda x, y: x + y
print(f"Square of 5: {square(5)}")
print(f"Add 3 and 4: {add(3, 4)}")
# Map function
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(f"Original: {numbers}")
print(f"Squared: {squared}")
# Filter function
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {evens}")
# Reduce function (need to import)
from functools import reduce
sum_all = reduce(lambda x, y: x + y, numbers)
print(f"Sum of all numbers: {sum_all}")
# Combining map, filter, and reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = reduce(lambda x, y: x + y,
map(lambda x: x**2,
filter(lambda x: x % 2 == 0, numbers)))
print(f"Sum of squares of even numbers: {result}")
# =============================================================================
# 18. REGULAR EXPRESSIONS
# =============================================================================
print("\n" + "=" * 60)
print("18. REGULAR EXPRESSIONS")
print("=" * 60)
import re
# Basic pattern matching
text = "The quick brown fox jumps over the lazy dog"
pattern = r"fox"
match = re.search(pattern, text)
if match:
print(f"Found '{match.group()}' at position {match.start()}")
# Find all matches
pattern = r"\b\w{4}\b" # 4-letter words
matches = re.findall(pattern, text)
print(f"4-letter words: {matches}")
# Substitution
pattern = r"fox"
replacement = "cat"
new_text = re.sub(pattern, replacement, text)
print(f"After replacement: {new_text}")
# Email validation
email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
emails = ["user@example.com", "invalid-email", "test@domain.org"]
for email in emails:
if re.match(email_pattern, email):
print(f"'{email}' is valid")
else:
print(f"'{email}' is invalid")
# =============================================================================
# 19. DATE AND TIME
# =============================================================================
print("\n" + "=" * 60)
print("19. DATE AND TIME")
print("=" * 60)
from datetime import datetime, date, time, timedelta
import time as time_module
# Current date and time
now = datetime.now()
print(f"Current datetime: {now}")
print(f"Current date: {now.date()}")
print(f"Current time: {now.time()}")
# Formatting dates
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted}")
# Parsing dates
date_string = "2024-01-15 14:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date: {parsed_date}")
# Date arithmetic
today = date.today()
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
print(f"Today: {today}")
print(f"Tomorrow: {tomorrow}")
print(f"Next week: {next_week}")
# Time differences
start = datetime(2024, 1, 1, 10, 0, 0)
end = datetime(2024, 1, 1, 15, 30, 0)
difference = end - start
print(f"Time difference: {difference}")
print(f"Hours: {difference.total_seconds() / 3600}")
# Unix timestamp
timestamp = time_module.time()
print(f"Unix timestamp: {timestamp}")
converted = datetime.fromtimestamp(timestamp)
print(f"Converted back: {converted}")
# =============================================================================
# 20. VIRTUAL ENVIRONMENTS AND PIP
# =============================================================================
print("\n" + "=" * 60)
print("20. VIRTUAL ENVIRONMENTS AND PIP")
print("=" * 60)
print("""
Virtual Environments and Pip Commands:
# Create virtual environment
python -m venv myenv
# Activate virtual environment
# On Windows:
myenv\\Scripts\\activate
# On macOS/Linux:
source myenv/bin/activate
# Install packages
pip install package_name
pip install package_name==1.2.3 # Specific version
pip install -r requirements.txt # From file
# List installed packages
pip list
pip freeze > requirements.txt # Save to file
# Deactivate virtual environment
deactivate
# Remove virtual environment
# Just delete the folder
""")
# =============================================================================
# 21. USEFUL BUILT-IN MODULES
# =============================================================================
print("\n" + "=" * 60)
print("21. USEFUL BUILT-IN MODULES")
print("=" * 60)
# os module
import os
print(f"Current working directory: {os.getcwd()}")
print(f"Environment variable HOME: {os.environ.get('HOME', 'Not set')}")
# sys module
import sys
print(f"Python version: {sys.version}")
print(f"Command line arguments: {sys.argv}")
# math module
import math
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Factorial of 5: {math.factorial(5)}")
print(f"Sine of π/2: {math.sin(math.pi/2)}")
# random module
import random
print(f"Random integer (1-100): {random.randint(1, 100)}")
print(f"Random choice: {random.choice(['apple', 'banana', 'cherry'])}")
# pathlib module (modern way to handle paths)
from pathlib import Path
current_path = Path.cwd()
print(f"Current path: {current_path}")
print(f"Path exists: {current_path.exists()}")
# itertools module
import itertools
print("Permutations of [1,2,3]:")
for perm in itertools.permutations([1, 2, 3]):
print(f" {perm}")
print("Combinations of [1,2,3,4] taken 2 at a time:")
for comb in itertools.combinations([1, 2, 3, 4], 2):
print(f" {comb}")
# =============================================================================
# 22. DATA SCIENCE BASICS (NumPy and Pandas)
# =============================================================================