Python Reviewer
# Python Reviewer
## Introduction to Python
- Python is a general-purpose, open-source programming language with a focus on readability.
- Created by Guido Van Rossum in 1989.
- Features:
- Simplicity - easy-to-read syntax
- Portability - runs on Windows, Mac, Linux, etc.
- Huge Libraries - extensive built-in and third-party modules
- Object-Oriented - supports classes and objects
## Python Basics
### 1. Variables & Data Types
- Variables store values and do not need explicit declaration.
- Built-in Data Types:
- Numbers: int, float, complex
- String (str) - Sequence of characters, immutable.
- List - Ordered, mutable collection ([ ]).
- Tuple - Ordered, immutable collection (( )).
- Dictionary - Key-value pairs ({ }).
- Set - Unordered, unique values.
### Type Checking
x=5
print(type(x)) # <class 'int'>
### String Manipulation
s = "Hello"
print(s[0]) # First character
print(s[1:4]) # Slicing
print(s * 2) # Repetition
print(s + " World!") # Concatenation
### List Example
my_list = [10, "hello", 3.14]
print(my_list[1]) # hello
my_list.append(100) # Add element
## 2. Decision-Making Statements
### If Statement
if x > 10:
print("Greater than 10")
### If-Else
if x > 10:
print("Greater than 10")
else:
print("Less than or equal to 10")
### If-Elif-Else
if x > 10:
print("Greater")
elif x == 10:
print("Equal")
else:
print("Smaller")
### Nested If
if x > 10:
if x % 2 == 0:
print("Even and Greater than 10")
### Ternary Operator
result = "Even" if x % 2 == 0 else "Odd"
### Switch Alternative (Using Dictionary)
def switch_case(option):
cases = {1: "One", 2: "Two", 3: "Three"}
return cases.get(option, "Invalid")
print(switch_case(2)) # Output: Two
## 3. Loops in Python
### For Loop
for i in range(5): # 0 to 4
print(i)
### While Loop
x=0
while x < 5:
print(x)
x += 1
### Break & Continue
for i in range(10):
if i == 5:
break # Stops loop
print(i)
for i in range(10):
if i == 5:
continue # Skips iteration
print(i)
## 4. Random Numbers
import random
x = random.randint(1, 10)
print(x) # Random integer between 1 and 10
y = round(random.uniform(1.5, 10.5), 2)
print(y) # Random float
## Summary
| Concept | Syntax Example |
|----------------------|---------------|
| Variable Assignment | x = 5 |
| Data Types | int, float, list, tuple, dict, set |
| If-Else | if x > 10: |
| Loop (For) | for i in range(5): |
| Loop (While) | while x < 5: |
| List | my_list = [1,2,3] |
| Dictionary | my_dict = {"name": "John"} |
| Random | random.randint(1, 10) |