Phyton Basic Handout
Phyton Basic Handout
Introduction to Python
Python is a high-level, interpreted programming language known for:
✔ Simple & readable syntax
✔ Versatility (Web, Data Science, AI, Automation)
✔ Large standard library
2. Python Setup
Install Python
bash
Copy
Download
python
>>> print("Hello World!")
Download
print("Hello World!")
Run with:
bash
Copy
Download
python hello.py
3. Basic Syntax
Variables & Data Types
python
Copy
Download
name = "Alice" # String
age = 25 # Integer
price = 9.99 # Float
is_student = True # Boolean
Printing Output
python
Copy
Download
print("Hello,", name) # Hello, Alice
print(f"Age: {age}") # f-strings (Python 3.6+)
Comments
python
Copy
Download
# Single-line comment
"""
Multi-line
comment
"""
4. Operators
Arithmetic Operators
python
Copy
Download
x = 10
y = 3
print(x + y) # 13 (Addition)
print(x - y) # 7 (Subtraction)
print(x * y) # 30 (Multiplication)
print(x / y) # 3.333... (Division)
print(x // y) # 3 (Floor Division)
print(x % y) # 1 (Modulus)
print(x ** y) # 1000 (Exponent)
Comparison Operators
python
Copy
Download
print(x == y) # False (Equal)
print(x != y) # True (Not Equal)
print(x > y) # True (Greater Than)
Logical Operators
python
Copy
Download
print((x > 5) and (y < 10)) # True (AND)
print((x < 5) or (y < 2)) # False (OR)
print(not is_student) # False (NOT)
5. Control Flow
If-Else Statements
python
Copy
Download
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
Loops
1. for Loop
python
Copy
Download
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
2. while Loop
python
Copy
Download
count = 0
while count < 5:
print(count)
count += 1
6. Data Structures
Lists (Mutable Arrays)
python
Copy
Download
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.pop() # [1, 2, 3]
Copy
Download
point = (10, 20)
x, y = point # Unpacking
Copy
Download
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
Copy
Download
unique_numbers = {1, 2, 2, 3} # {1, 2, 3}
7. Functions
Basic Function
python
Copy
Download
def greet(name):
return f"Hello, {name}!"
Default Arguments
python
Copy
Download
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
8. File Handling
Reading a File
python
Copy
Download
with open("file.txt", "r") as file:
content = file.read()
print(content)
Writing to a File
python
Copy
Download
with open("file.txt", "w") as file:
file.write("Hello, Python!")
9. Error Handling (Try-Except)
python
Copy
Download
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
o Calculator
o To-Do List App
o Web Scraper