Part 1
Python Basics
Variables, Operators, Control Flow & I/O
1. Introduction
Python is a high-level, interpreted, general-purpose programming language known for its readable
syntax and huge ecosystem of libraries. Created by Guido van Rossum and first released in 1991, it
has become one of the most popular languages in the world. It is widely used in web development,
data science, automation, artificial intelligence, scientific computing, and scripting.
Why Python is popular:
• Simple, readable syntax close to plain English
• Huge standard library and third-party package ecosystem (PyPI)
• Cross-platform — runs on Windows, macOS, and Linux
• Strong community support and documentation
• Used by companies like Google, Netflix, Instagram, and NASA
Installing Python
Download the latest version from [Link], or use a package manager. You can verify your
installation from the terminal:
python --version
python3 --version
Running Your First Program
print("Hello, World!")
Save this in a file named [Link] and run it with python [Link].
2. Variables & Data Types
Variables in Python don't need explicit type declarations — the type is inferred automatically at
runtime based on the assigned value. This is called dynamic typing.
name = "Alice" # str
age = 25 # int
height = 5.6 # float
is_student = True # bool
skills = ["Python", "SQL"] # list
Core built-in types:
• int — whole numbers, e.g. 10, -3
• float — decimal numbers, e.g. 3.14
• str — text, e.g. "hello"
• bool — True / False
• list, tuple, dict, set — collections
• NoneType — represents the absence of a value (None)
Naming Rules for Variables
• Must start with a letter or underscore, not a digit
• Can contain letters, digits, and underscores
• Case-sensitive: age and Age are different
• Cannot use reserved keywords like if, class, for
Type Conversion
You can convert between types explicitly using built-in functions:
x = int("42") # 42
y = float("3.14") # 3.14
z = str(100) # "100"
b = bool(0) # False
print(type(x), type(y), type(z))
Checking Types
value = 3.14
print(type(value)) # <class 'float'>
print(isinstance(value, float)) # True
3. Operators
Python supports arithmetic, comparison, logical, assignment, membership, and identity operators.
Arithmetic Operators
a, b = 7, 2
print(a + b, a - b, a * b, a / b) # 9 5 14 3.5
print(a // b, a % b, a ** b) # 3 1 49
Comparison Operators
print(a == b, a != b, a > b, a < b, a >= b, a <= b)
Logical Operators
print(a > b and b > 0) # True
print(a > b or b < 0) # True
print(not (a > b)) # False
Assignment Operators
x = 10
x += 5 # x = x + 5 -> 15
x -= 2 # 13
x *= 2 # 26
x //= 4 # 6
Membership & Identity Operators
nums = [1, 2, 3]
print(2 in nums) # True
print(5 not in nums) # True
a = [1, 2]
b = a
c = [1, 2]
print(a is b) # True (same object)
print(a is c) # False (equal value, different object)
4. Strings
Strings are immutable sequences of characters. Python provides many built-in methods for working
with text.
s = "Hello, Python!"
print([Link]()) # HELLO, PYTHON!
print([Link]()) # hello, python!
print([Link]("Python", "World"))
print([Link](",")) # ['Hello', ' Python!']
print(len(s)) # 17
print(s[0:5]) # Hello (slicing)
print([Link]()) # remove leading/trailing whitespace
String Formatting
f-strings (formatted string literals) are the modern, preferred way to embed expressions inside
strings:
name = "Rafi"
age = 21
print(f"{name} is {age} years old")
print(f"Next year, {name} will be {age + 1}")
print(f"{3.14159:.2f}") # 3.14 (2 decimal places)
5. Control Flow
if/elif/else statements control branching logic based on conditions:
score = 82
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
print(grade) # B
Nested Conditions
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Too young")
Ternary (Conditional) Expressions
status = "adult" if age >= 18 else "minor"
print(status)
6. Loops
Loops let you repeat a block of code multiple times.
The for Loop
for i in range(5):
print(i) # 0 1 2 3 4
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
The while Loop
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff!")
Loop Control Statements
for i in range(10):
if i == 3:
continue # skip this iteration
if i == 7:
break # exit the loop
print(i)
The else Clause on Loops
A loop's else block runs only if the loop completes without hitting a break:
for i in range(5):
print(i)
else:
print("Loop finished normally")
7. Input & Output
Use print() for output and input() to read user input. Input is always returned as a string, so
convert it if you need a number.
name = input("What is your name? ")
print(f"Hello, {name}!")
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
Common print() Options
print("A", "B", "C", sep="-") # A-B-C
print("No newline", end=" ")
print("continues here")
8. Common Pitfalls
• Mixing tabs and spaces for indentation causes errors — Python is whitespace-sensitive.
• Forgetting that input() always returns a string.
• Comparing floats directly for equality can fail due to precision (use rounding instead).
• Using == when you mean is, or vice versa.
• Modifying a list while iterating over it can cause unexpected behavior.
Practice Exercises
• Write a program to check if a number is even or odd.
• Write a program that prints the multiplication table of a given number.
• Take two numbers as input and print their sum, difference, and product.
• Write a program to check whether a string is a palindrome.
• Write a program to find the largest of three numbers using if/elif/else.
• Print all prime numbers between 1 and 50 using a for loop.
• Build a simple calculator that takes two numbers and an operator as input.