15_python_basics.py

Download
python 513 lines 12.0 KB
  1"""
  2Python Basics
  3
  4Demonstrates:
  5- Variables and data types
  6- Operators
  7- Control flow (if, for, while)
  8- Functions
  9- String formatting
 10- Lists, tuples, sets, dictionaries
 11- List/dict/set comprehensions
 12- File I/O
 13- Exception handling
 14"""
 15
 16
 17def section(title: str) -> None:
 18    """Print a section header."""
 19    print("\n" + "=" * 60)
 20    print(f"  {title}")
 21    print("=" * 60)
 22
 23
 24# =============================================================================
 25# Variables and Data Types
 26# =============================================================================
 27
 28section("Variables and Data Types")
 29
 30# Numbers
 31integer_num = 42
 32float_num = 3.14
 33complex_num = 3 + 4j
 34
 35print(f"Integer: {integer_num} (type: {type(integer_num).__name__})")
 36print(f"Float: {float_num} (type: {type(float_num).__name__})")
 37print(f"Complex: {complex_num} (type: {type(complex_num).__name__})")
 38
 39# Strings
 40single_quote = 'Hello'
 41double_quote = "World"
 42triple_quote = """Multi-line
 43string"""
 44
 45print(f"\nStrings:")
 46print(f"  Single: {single_quote}")
 47print(f"  Double: {double_quote}")
 48print(f"  Triple: {triple_quote}")
 49
 50# Booleans
 51is_active = True
 52is_deleted = False
 53print(f"\nBooleans: {is_active}, {is_deleted}")
 54
 55# None
 56nothing = None
 57print(f"None: {nothing}")
 58
 59
 60# =============================================================================
 61# Operators
 62# =============================================================================
 63
 64section("Operators")
 65
 66# Arithmetic
 67a, b = 10, 3
 68print(f"a = {a}, b = {b}")
 69print(f"  Addition: {a} + {b} = {a + b}")
 70print(f"  Subtraction: {a} - {b} = {a - b}")
 71print(f"  Multiplication: {a} * {b} = {a * b}")
 72print(f"  Division: {a} / {b} = {a / b}")
 73print(f"  Floor division: {a} // {b} = {a // b}")
 74print(f"  Modulus: {a} % {b} = {a % b}")
 75print(f"  Exponentiation: {a} ** {b} = {a ** b}")
 76
 77# Comparison
 78print(f"\nComparison:")
 79print(f"  {a} > {b}: {a > b}")
 80print(f"  {a} < {b}: {a < b}")
 81print(f"  {a} == {b}: {a == b}")
 82print(f"  {a} != {b}: {a != b}")
 83
 84# Logical
 85x, y = True, False
 86print(f"\nLogical (x={x}, y={y}):")
 87print(f"  x and y: {x and y}")
 88print(f"  x or y: {x or y}")
 89print(f"  not x: {not x}")
 90
 91
 92# =============================================================================
 93# Control Flow - if/elif/else
 94# =============================================================================
 95
 96section("Control Flow - if/elif/else")
 97
 98age = 25
 99
100if age < 18:
101    status = "minor"
102elif age < 65:
103    status = "adult"
104else:
105    status = "senior"
106
107print(f"Age {age}: {status}")
108
109# Ternary operator
110message = "even" if age % 2 == 0 else "odd"
111print(f"Age is {message}")
112
113
114# =============================================================================
115# Control Flow - for loop
116# =============================================================================
117
118section("Control Flow - for loop")
119
120# Iterate over range
121print("Range(5):")
122for i in range(5):
123    print(f"  {i}", end=" ")
124print()
125
126# Iterate over list
127fruits = ["apple", "banana", "cherry"]
128print("\nFruits:")
129for fruit in fruits:
130    print(f"  {fruit}")
131
132# Enumerate
133print("\nEnumerated:")
134for index, fruit in enumerate(fruits):
135    print(f"  {index}: {fruit}")
136
137# Iterate over dictionary
138person = {"name": "Alice", "age": 30, "city": "NYC"}
139print("\nDictionary:")
140for key, value in person.items():
141    print(f"  {key}: {value}")
142
143
144# =============================================================================
145# Control Flow - while loop
146# =============================================================================
147
148section("Control Flow - while loop")
149
150count = 0
151print("Counting to 5:")
152while count < 5:
153    print(f"  Count: {count}")
154    count += 1
155
156# break and continue
157print("\nWith break and continue:")
158for i in range(10):
159    if i == 3:
160        continue  # Skip 3
161    if i == 7:
162        break  # Stop at 7
163    print(f"  {i}", end=" ")
164print()
165
166
167# =============================================================================
168# Functions
169# =============================================================================
170
171section("Functions")
172
173
174def greet(name: str) -> str:
175    """Simple function with return value."""
176    return f"Hello, {name}!"
177
178
179def calculate_area(width: float, height: float = 10.0) -> float:
180    """Function with default argument."""
181    return width * height
182
183
184def sum_all(*numbers: int) -> int:
185    """Variable arguments (*args)."""
186    return sum(numbers)
187
188
189def describe_person(**kwargs: str) -> str:
190    """Keyword arguments (**kwargs)."""
191    parts = [f"{k}={v}" for k, v in kwargs.items()]
192    return ", ".join(parts)
193
194
195print(greet("Alice"))
196print(f"Area: {calculate_area(5)}")
197print(f"Area: {calculate_area(5, 20)}")
198print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")
199print(f"Person: {describe_person(name='Bob', age='30', city='NYC')}")
200
201
202# Lambda functions
203square = lambda x: x ** 2
204print(f"\nLambda: square(5) = {square(5)}")
205
206
207# =============================================================================
208# String Formatting
209# =============================================================================
210
211section("String Formatting")
212
213name = "Alice"
214age = 30
215pi = 3.14159
216
217# f-strings (Python 3.6+)
218print(f"f-string: {name} is {age} years old")
219print(f"Expression: 2 + 2 = {2 + 2}")
220print(f"Formatted: pi = {pi:.2f}")
221
222# format() method
223print("format(): {} is {} years old".format(name, age))
224print("format(): {1} is {0} years old".format(age, name))
225print("format(): {name} is {age}".format(name=name, age=age))
226
227# %-formatting (old style)
228print("%%: %s is %d years old" % (name, age))
229
230
231# =============================================================================
232# Lists
233# =============================================================================
234
235section("Lists")
236
237numbers = [1, 2, 3, 4, 5]
238print(f"List: {numbers}")
239
240# Indexing
241print(f"First: {numbers[0]}")
242print(f"Last: {numbers[-1]}")
243
244# Slicing
245print(f"First 3: {numbers[:3]}")
246print(f"Last 2: {numbers[-2:]}")
247print(f"Every 2nd: {numbers[::2]}")
248
249# Methods
250numbers.append(6)
251print(f"After append(6): {numbers}")
252
253numbers.insert(0, 0)
254print(f"After insert(0, 0): {numbers}")
255
256numbers.pop()
257print(f"After pop(): {numbers}")
258
259# List operations
260list1 = [1, 2, 3]
261list2 = [4, 5, 6]
262combined = list1 + list2
263print(f"Combined: {combined}")
264
265
266# =============================================================================
267# List Comprehensions
268# =============================================================================
269
270section("List Comprehensions")
271
272# Basic comprehension
273squares = [x**2 for x in range(10)]
274print(f"Squares: {squares}")
275
276# With condition
277evens = [x for x in range(20) if x % 2 == 0]
278print(f"Evens: {evens}")
279
280# Nested comprehension
281matrix = [[i * j for j in range(3)] for i in range(3)]
282print(f"Matrix: {matrix}")
283
284
285# =============================================================================
286# Tuples
287# =============================================================================
288
289section("Tuples")
290
291point = (10, 20)
292print(f"Tuple: {point}")
293print(f"  x={point[0]}, y={point[1]}")
294
295# Tuple unpacking
296x, y = point
297print(f"Unpacked: x={x}, y={y}")
298
299# Tuples are immutable
300try:
301    point[0] = 100
302except TypeError as e:
303    print(f"Cannot modify tuple: {e}")
304
305
306# =============================================================================
307# Sets
308# =============================================================================
309
310section("Sets")
311
312set1 = {1, 2, 3, 4, 5}
313set2 = {4, 5, 6, 7, 8}
314
315print(f"Set1: {set1}")
316print(f"Set2: {set2}")
317
318# Set operations
319print(f"Union: {set1 | set2}")
320print(f"Intersection: {set1 & set2}")
321print(f"Difference: {set1 - set2}")
322print(f"Symmetric difference: {set1 ^ set2}")
323
324# Set comprehension
325squares_set = {x**2 for x in range(10)}
326print(f"Squares set: {squares_set}")
327
328
329# =============================================================================
330# Dictionaries
331# =============================================================================
332
333section("Dictionaries")
334
335person = {
336    "name": "Alice",
337    "age": 30,
338    "city": "NYC"
339}
340
341print(f"Dict: {person}")
342print(f"Name: {person['name']}")
343print(f"Age: {person.get('age')}")
344print(f"Country (default): {person.get('country', 'USA')}")
345
346# Add/modify
347person["email"] = "alice@example.com"
348person["age"] = 31
349
350print(f"Updated: {person}")
351
352# Dict methods
353print(f"Keys: {list(person.keys())}")
354print(f"Values: {list(person.values())}")
355print(f"Items: {list(person.items())}")
356
357# Dict comprehension
358squares_dict = {x: x**2 for x in range(5)}
359print(f"Squares dict: {squares_dict}")
360
361
362# =============================================================================
363# File I/O
364# =============================================================================
365
366section("File I/O")
367
368import tempfile
369import os
370
371# Create temp file
372temp_file = os.path.join(tempfile.gettempdir(), "python_basics_demo.txt")
373
374# Writing
375with open(temp_file, 'w') as f:
376    f.write("Hello, File I/O!\n")
377    f.write("Python is awesome.\n")
378    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
379    f.writelines(lines)
380
381print(f"Wrote to: {temp_file}")
382
383# Reading
384with open(temp_file, 'r') as f:
385    content = f.read()
386    print(f"Read content:\n{content}")
387
388# Reading lines
389with open(temp_file, 'r') as f:
390    lines = f.readlines()
391    print(f"Lines: {len(lines)}")
392
393# Cleanup
394os.remove(temp_file)
395
396
397# =============================================================================
398# Exception Handling
399# =============================================================================
400
401section("Exception Handling")
402
403
404def divide(a: float, b: float) -> float:
405    """Divide with exception handling."""
406    try:
407        result = a / b
408        print(f"  {a} / {b} = {result}")
409        return result
410    except ZeroDivisionError:
411        print(f"  Error: Cannot divide by zero")
412        return None
413    except TypeError:
414        print(f"  Error: Invalid types")
415        return None
416    finally:
417        print(f"  Finally block executed")
418
419
420divide(10, 2)
421divide(10, 0)
422
423
424# Raising exceptions
425def validate_age(age: int):
426    """Validate age."""
427    if age < 0:
428        raise ValueError("Age cannot be negative")
429    if age > 150:
430        raise ValueError("Age too high")
431    return True
432
433
434try:
435    validate_age(25)
436    print("Age 25: valid")
437    validate_age(-5)
438except ValueError as e:
439    print(f"Invalid age: {e}")
440
441
442# =============================================================================
443# Common Built-in Functions
444# =============================================================================
445
446section("Common Built-in Functions")
447
448numbers = [3, 1, 4, 1, 5, 9, 2, 6]
449
450print(f"List: {numbers}")
451print(f"len(): {len(numbers)}")
452print(f"min(): {min(numbers)}")
453print(f"max(): {max(numbers)}")
454print(f"sum(): {sum(numbers)}")
455print(f"sorted(): {sorted(numbers)}")
456print(f"reversed(): {list(reversed(numbers))}")
457
458# map, filter
459doubled = list(map(lambda x: x * 2, numbers))
460print(f"map(x*2): {doubled}")
461
462evens = list(filter(lambda x: x % 2 == 0, numbers))
463print(f"filter(even): {evens}")
464
465# zip
466names = ["Alice", "Bob", "Charlie"]
467ages = [25, 30, 35]
468combined = list(zip(names, ages))
469print(f"zip: {combined}")
470
471# any, all
472values = [True, True, False]
473print(f"any({values}): {any(values)}")
474print(f"all({values}): {all(values)}")
475
476
477# =============================================================================
478# Summary
479# =============================================================================
480
481section("Summary")
482
483print("""
484Python basics covered:
4851. Variables and types - int, float, str, bool, None
4862. Operators - arithmetic, comparison, logical
4873. Control flow - if/elif/else, for, while
4884. Functions - def, return, *args, **kwargs
4895. String formatting - f-strings, format(), %
4906. Lists - indexing, slicing, methods
4917. Comprehensions - list, dict, set
4928. Tuples - immutable sequences
4939. Sets - unique elements, set operations
49410. Dictionaries - key-value pairs
49511. File I/O - open, read, write
49612. Exception handling - try/except/finally
497
498Key concepts:
499- Python is dynamically typed
500- Indentation matters (4 spaces)
501- Everything is an object
502- Duck typing: "If it walks like a duck..."
503- Batteries included philosophy
504
505Next steps:
506- Object-oriented programming (classes)
507- Modules and packages
508- Decorators and generators
509- Context managers
510- Type hints
511- Advanced data structures
512""")