print("Hello, World!")print(5 + 9)name = "Majid"print(type(name))if 10 > 3: print("Python is easy!")print("Learning Python!")age = 20; print(age)print("A" * 5)print(10 == 10)for i in range(3): print(i)print "Hi" to print("Hi"). Python 3 supports emojis, modern math operations, and improved security. Always use Python 3 for new projects.print("Python 3!")print(8/3) (float division)print(8//3) (integer division)print("Emoji 😊")input("Enter your name: ")sudo apt install python3. After installing, run a simple program to verify everything works.python3 --versionpython3 hello.pymkdir MyPythoncd MyPythonpython3print("VS Code!") and run.x = 52 + 2 → Shift + Enter.py and execute it later. Running scripts allows you to create longer programs such as games, calculators, and automation tasks. Using an IDE like VS Code, PyCharm, or Jupyter makes running programs easier because they have Run buttons and tools to show errors. Running Python programs helps beginners understand how instructions are processed by the computer and builds confidence in writing longer applications.python3 myscript.pypython3./myscript.py (after chmod +x).py file. You write all the code first and then run it to see outputs. Interactive mode is fast and simple, while script mode is professional and helps build real applications. Beginners often use both: interactive mode for quick learning, script mode for projects.python3 → 3 + 4test.py → python3 test.pyprint("Hi")name = "Majid"; print(name)type("Hello")calc.pyprint("Hello World") shows you how Python handles text and gives you your first successful code experience. This tiny program is important because it teaches you about quotation marks, parentheses, and how code produces results. Once you understand printing, you can show names, results from math, and more. Every programmer starts with this step because it builds confidence and marks the beginning of your coding journey.print("Hello World")print("Welcome to Python!")print("Majid is learning Python")print(5 + 5)print("Age:", 25)print("😊 Happy Coding!")print("Python Syntax")# This is a commentname = "Majid"print(name)x = 10; y = 20; print(x + y)print("Syntax is easy!")if 5 > 3:
print("Yes")for i in range(3):
print(i)def hello():
print("Hello!")x = 10
if x == 10:
print("x is 10")while True:
breakif True:
# inside block# and ends at the end of that line. These are great for quick explanations. "Multi-line comments" use triple quotes ''' ... ''' or """ ... """ and can span multiple lines. They help you describe larger parts of a program, such as instructions or block explanations. Using comments is a good habit because it improves communication between programmers and helps beginners remember why they wrote certain code. Clean code always contains helpful comments.# This is a single-line commentprint("Hello") # Comment after code''' Multi
Line
Comment '''"""Explain program here"""# TODO: Add more features# Python ignores comments completelyx = 10 # variable storing a numbername = "Majid" # variable storing textprice = 9.99 # variable storing decimal valueis_learning = True # variable storing a Booleanprint(x) # prints value of xprint(type(name)) # shows data typeage = 25 # integerheight = 5.8 # float valuemessage = "Hello" # string textis_adult = True # boolean valueprint(type(height)) # shows floatprint(10 + age) # integer mathName and name are different variables. The recommended style is "snake_case" (words separated by underscores), like first_name. Following naming rules makes your code look professional and easier to maintain.first_name = "Majid" # clear name_count = 10 # valid name starting with underscoreuser_age = 20 # snake_case formattotal_price = 99.99 # descriptive# Wrong: 1name = "Error" # cannot start with number# Wrong: user-name = "error" # hyphen not allowedint() to change a number or text into an integer, float() to convert into decimals, str() to convert values into text, and bool() to convert into True/False. Type casting is important when taking input from users since it is always treated as text. If you want to perform math with user input, you must convert it to a number first. Type casting helps prevent errors and allows your program to work correctly with different kinds of data.x = "5"; y = int(x) # convert string to integernum = 10; txt = str(num) # number to textvalue = float("3.14") # string to floatprint(bool(1)) # Trueprint(int(3.99)) # becomes 3print(type(txt)) # shows string type
Input and output are two of the most important features in Python, because they allow
interaction between the user and the program. Output means showing information on the screen using
print(). It can display text, numbers, variables, or even math results. Without output, users would never
see what the program is doing.
Input uses the input() function, which pauses the program and waits for the user to type something.
The typed text is always stored as a string, so we often convert it using int() or float() when we need
numbers for math operations. Input makes programs customizable instead of fixed.
Python also lets us combine text and variables in a clean and friendly way using formatted strings — also
called f-strings. With f-strings, we write f"Hello {name}" which keeps code short and readable.
They work with calculations and expressions inside the braces { }. Input, output, and f-strings are
essential to build real-world applications such as calculators, signup forms, and games.
print("Welcome to Python!") # Simple output to screen
name = input("Enter your name: ") # Input waits for user typing
print("Hello,", name) # Output shows the typed name
age = input("How old are you? : ") # User enters age as text (string)
age = int(age) # Convert to integer for math
print(age + 1) # Shows age next year
city = input("Where do you live? : ")
print(f"You live in {city}.") # Using f-string formatting
price = float(input("Enter a product price: "))
print(f"Price with tax: {price * 1.15}") # Calculate inside f-string
a = 5
b = 10
print(f"{a} + {b} = {a + b}") # Output formatted like real math
Arithmetic operators are used to perform mathematical operations in Python. They include addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulus (%), and exponent (**). These operators let you build calculators, shopping totals, scores in games, and many more real-world features. Division always returns a decimal result, while floor division removes decimals and gives a whole number. Modulus (%) returns the remainder after division, which is useful in checking if a number is odd, even, or divisible by something. Exponent (**) is used for powers like 2² or 3³. Arithmetic operators work with numbers stored in variables, and Python follows standard math rules (PEMDAS). Understanding these operators is the first step in learning programming logic because everything from finance apps to scientific tools uses math operations. When beginners master arithmetic, they can easily move into more advanced topics like algorithms, data processing, and AI calculations.
a = 10; b = 3; print(a + b) # Addition: 13
a = 10; b = 3; print(a - b) # Subtraction: 7
a = 10; b = 3; print(a * b) # Multiplication: 30
a = 10; b = 3; print(a / b) # Division: 3.3333
a = 10; b = 3; print(a % b) # Remainder: 1
a = 2; print(a ** 3) # Power: 8
Comparison operators check the relationship between two values. They include equal to (==), not equal (!=), greater than (>), less than (<), greater or equal (>=), and less or equal (<=). These operators always return True or False, which makes them very important in decision-making. Whenever we want a program to choose between two actions — like whether you passed an exam, whether a login password is correct, or whether stock prices increased — we use comparison operators. They are also widely used in loops to repeat actions until a condition becomes False. By comparing variables, programs become interactive and responsive to user data. Without comparison operators, a program would not be able to judge or react, making logic-based applications impossible. These operators help computers understand situations similar to humans — such as checking if something is bigger, different, or the same — which is essential for automation, AI, and gaming.
print(5 == 5) # True
print(10 != 3) # True
print(8 > 6) # True
print(4 < 2) # False
print(7 >= 7) # True
print(5 <= 3) # False
Logical operators combine conditions to make more complex decisions. Python has three logical operators: and, or, and not. The and operator returns True only if both conditions are True. The or operator returns True if at least one condition is True. The not operator flips the result — True becomes False and False becomes True. Logical operators are used everywhere: checking if a user meets multiple requirements (age and password), verifying login while not banned, or filtering large data sets. Programs become smarter because they can think about multiple rules at once. Logical operators are also key in loops, search systems, AI, and scientific computing. They help a computer evaluate situations and make branching decisions just like humans do.
print(5 > 3 and 8 > 6) # True
print(5 > 8 and 8 > 6) # False
print(5 > 8 or 8 > 6) # True
print(not True) # False
age = 20; print(age >= 18 and age <= 30) # True
logged_in = False; print(not logged_in) # True
Assignment operators store values in variables. The most common is equal (=), which assigns a value to a variable. Python also has combined assignment operators to save typing effort. For example, += adds a number to the existing value, -= subtracts, *= multiplies, /= divides, and %= applies modulus. These operators update a variable without rewriting the entire expression. Assignment operators are used heavily in loops, where values continuously change — such as scores, counters, and totals. They help make code cleaner and faster to write, which reduces mistakes. Understanding assignment operators improves coding efficiency and is required for all advanced areas of software development.
x = 10 # Normal assignment
x += 5 # Equivalent to x = x + 5
x -= 3 # Equivalent to x = x - 3
x *= 2 # Multiply and store new value
x /= 4 # Divide and update
x %= 3 # Store remainder
Bitwise operators work with numbers at the binary level (0s and 1s). Computers store all numbers as binary signals — so bitwise operators allow powerful, low-level control. Common operators include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). These operators are mainly used in networking, cybersecurity, encryption, game programming, hardware control, and performance-critical applications. Although beginners rarely use them early, knowing they exist helps you understand how computers work inside. For example, shifting bits left multiplies numbers by 2, and shifting right divides by 2. XOR checks for differences — great for security. Bitwise operators help programmers write faster, memory-efficient code.
print(5 & 3) # AND → 1
print(5 | 3) # OR → 7
print(5 ^ 3) # XOR → 6
print(~5) # NOT → -6
print(5 << 1) # Left shift → 10
print(5 >> 1) # Right shift → 2
A string in Python is a sequence of characters such as letters, numbers, or symbols placed inside quotes. You can use single quotes ('Hello'), double quotes ("Hello"), or even triple quotes for multi-line text. Strings are used everywhere — names, messages, addresses, passwords, and more. Strings are not numbers, so they cannot be used directly for math, but they can be combined using the plus sign (+), which joins two strings together. This is called concatenation. Strings are ordered, meaning every character has a position number called an index. They are also immutable, which means once created, you cannot change characters inside them — but you can make new strings using old ones. Understanding strings is very important because most applications rely on user text. Whether you build a chatbot, form input, search engine, game dialog, or social media app — strings make communication possible between the user and the computer.
text = "Hello" # String with double quotes
name = 'Alice' # String with single quotes
msg = """Multi-line string"""
print("Hi " + "there") # Join strings
print(len("Python")) # Find length of string
print(type("Hello")) # Shows it is a string
Since strings are sequences, every character has a position (index). Indexing starts from 0 on the left. Example: "Python" → P(0), y(1), t(2), h(3), o(4), n(5). Negative indexing starts from the right: n(-1), o(-2)… Indexing helps us pick one character: text[2]. Slicing means selecting a part of a string using the format text[start:end]. The slice includes the start but stops before the end. Slicing allows us to extract words, initials, dates, file names, or edit messages. We can also skip characters using a third value called step text[start:end:step]. Slicing is frequently used in data cleaning, reversing text, usernames, and formatting dashboards. It is one of the most powerful features because it lets programs understand and manipulate human language. Mastering indexing and slicing makes your string handling skills strong and prepares you for dynamic apps like chat systems, AI text processing, and file management.
text = "Python"; print(text[0]) # P
print(text[-1]) # Last character: n
print(text[0:3]) # Slice first 3 letters: Pyt
print(text[:4]) # From start to index 3
print(text[2:]) # From index 2 to end: thon
print(text[::-1]) # Reverse: nohtyP
String methods are built-in functions that help us clean and transform text easily. Some common ones are: upper() → converts text to uppercase, lower() → lowercase, strip() → removes extra spaces, split() → breaks a sentence into words, replace() → swaps text, find() → searches and returns index of a word. These methods do not change the original string because strings are immutable — they return a new modified string. String methods help us format names correctly, remove mistakes in user input, search for important terms, and organize data before saving it to a database. They are essential for AI chat apps, signup forms, messaging, translation tools, and cleaning messy text. With string methods, we turn raw input into clean, useful information easily and professionally.
print("hello".upper()) # HELLO
print("HELLO".lower()) # hello
print(" Hi ".strip()) # Remove spaces
print("A,B,C".split(",")) # ['A','B','C']
print("cat".replace("c","b")) # bat
print("Python".find("h")) # index 3
String formatting helps us mix text and variables in a clean and readable way. Instead of writing many print statements or using +, Python gives us smarter options like f-strings, .format(), and the older % formatting. F-strings are the most modern and popular: we place variables inside curly braces {} inside a string that starts with f. Example: f"Hello {name}". This makes programs easy to customize with user details such as names, ages, scores, and prices. String formatting is used for receipts, dashboards, emails, forms, and data reports — anywhere we need neat and clear display. It also supports calculations inside the braces, making it very powerful for real-world apps.
name = "Alex"; print(f"Hello {name}")
age = 25; print(f"You are {age} years old")
print("Hi {}".format("Sam")) # .format()
score = 98; print(f"Score: {score}/100")
print(f"2 + 3 = {2+3}") # Math inside f-string
price = 10.5; print("Price: %.2f" % price) # old style
Mini projects are the best way to practice Python after learning the basics. These projects cover input/output, arithmetic, conditions, loops, and strings. Each project is beginner-friendly, fully commented, and includes step-by-step instructions for running. You can run them in VS Code, PyCharm, Jupyter Notebook, or any Python environment. The goal is to combine learned concepts into real, working programs. Follow the steps for each project to understand how Python programs work.
# Step 1: Ask user for two numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
# Step 2: Print original numbers
print("Before swap: a =", a, "b =", b)
# Step 3: Swap numbers using a temporary variable
temp = a
a = b
b = temp
# Step 4: Print swapped numbers
print("After swap: a =", a, "b =", b)
# How to run: Save as number_swap.py and execute in Python terminal or IDE
# Step 1: Ask user for birth year
birth_year = int(input("Enter your birth year: "))
# Step 2: Get current year (hardcoded or use datetime module)
current_year = 2025
# Step 3: Calculate age
age = current_year - birth_year
# Step 4: Display age
print("You are", age, "years old")
# How to run: Save as age_calculator.py and execute in Python IDE
# Step 1: Welcome message
print("Welcome to the Python Quiz!")
# Step 2: Initialize score
score = 0
# Step 3: First question
answer1 = input("What is the capital of France? ")
if answer1.lower() == "paris":
print("Correct!")
score += 1
else:
print("Wrong!")
# Step 4: Second question
answer2 = input("What is 5 + 7? ")
if answer2 == "12":
print("Correct!")
score += 1
else:
print("Wrong!")
# Step 5: Display final score
print("Your final score is:", score, "/2")
# How to run: Save as simple_quiz.py and execute in Python terminal or IDE
# Step 1: Ask principal amount
p = float(input("Enter principal amount: "))
# Step 2: Ask rate of interest
r = float(input("Enter rate of interest (%): "))
# Step 3: Ask time in years
t = float(input("Enter time (years): "))
# Step 4: Calculate interest
si = (p * r * t) / 100
# Step 5: Display result
print("Simple Interest:", si)
# How to run: Save as simple_interest.py
# Step 1: Ask user for words
adj = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
# Step 2: Create story
story = f"Today I saw a {adj} {noun} that could {verb} all day!"
# Step 3: Display story
print(story)
# How to run: Save as mad_libs.py
# Step 1: Ask user for number
num = int(input("Enter a number: "))
# Step 2: Check if even or odd
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
# How to run: Save as even_odd.py
# Step 1: Ask user for number
n = int(input("Enter a number to print its multiplication table: "))
# Step 2: Loop from 1 to 10
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")
# How to run: Save as multiplication_table.py
# Step 1: Ask user for a string
text = input("Enter a string: ")
# Step 2: Initialize counter
count = 0
# Step 3: Loop through string
for char in text.lower():
if char in "aeiou":
count += 1
# Step 4: Display result
print("Number of vowels:", count)
# How to run: Save as count_vowels.py
# Step 1: Ask for input
text = input("Enter a string: ")
# Step 2: Reverse using slicing
reversed_text = text[::-1]
# Step 3: Display result
print("Reversed string:", reversed_text)
# How to run: Save as reverse_string.py
# Step 1: Ask bill amount
bill = float(input("Enter bill amount: "))
# Step 2: Ask tip percentage
tip_percent = float(input("Enter tip percentage: "))
# Step 3: Calculate tip
tip = (bill * tip_percent) / 100
# Step 4: Total bill
total = bill + tip
# Step 5: Display result
print(f"Tip: {tip}, Total bill: {total}")
# How to run: Save as tip_calculator.py
Python has official style rules called PEP8. These rules help everyone write code in the same clean and readable way. Good style makes your programs easier to understand, fix, and improve. Beginners often ignore style, but as you grow, clean code becomes very important. Python focuses on readability, meaning code should look almost like English. PEP8 gives instructions like: use lowercase variable names, add spaces around operators, keep lines short, and always use indentation correctly. Comments also help describe what your code is doing. If someone else reads your program later—or even you after a long time—good style will save a lot of time. Tools like flake8 and Black can automatically check and fix your style. Think of PEP8 like driving rules: you can still drive without them, but following them keeps everything safe and smooth. Writing clean code is what makes you a real programmer.
Example 1: Good variable naming
name = "Majid"Example 2: Spaces around operators
x = 10 + 5Example 3: Indentation is required
if True:Example 4: Limit line length & clear message
message = "Writing short lines makes the code easier to read"Example 5: Commenting wisely
total = 100Mini projects are the best way to practice Python after learning the basics. They bring together operators, input and output, conditions, and variables into real working programs. These three beginner projects help build confidence: (1) A simple calculator teaches math operations and choosing options. (2) A temperature converter helps you practice formulas and converting user input. (3) A guess-the-number game adds randomness and looping so the player keeps trying until they succeed. You can run these projects in any Python editor like VS Code, PyCharm, or even a mobile app. Try changing numbers or adding your own features. The goal of these small programs is to make learning fun while preparing you for larger projects in the future. These examples are simple, well-commented, and perfect for YouTube tutorials or a beginner Python book.
print("Simple Calculator")
# Title of the calculator program
num1 = float(input("Enter first number: "))
# Take first number from user
num2 = float(input("Enter second number: "))
# Take second number from user
print("Choose operation: +, -, *, /")
# Show available operations
op = input("Operation: ")
# Ask the user to pick an operator
if op == "+":
# Check if operator is +
print(num1 + num2)
# Add and display result
elif op == "-":
# Check if operator is -
print(num1 - num2)
# Subtract and display result
elif op == "*":
# Check multiplication
print(num1 * num2)
# Multiply and output result
elif op == "/":
# Check division
print(num1 / num2)
# Divide and print answer
else:
print("Invalid operation")
# If wrong input, show error
print("Temperature Converter")
# Show title
celsius = float(input("Enter temperature in Celsius: "))
# Ask for Celsius input
fahrenheit = (celsius * 9/5) + 32
# Convert using formula
print("Temperature in Fahrenheit:", fahrenheit)
# Display result
fahrenheit2 = float(input("Enter temperature in Fahrenheit: "))
# Ask for Fahrenheit input
celsius2 = (fahrenheit2 - 32) * 5/9
# Convert using formula
print("Temperature in Celsius:", celsius2)
# Display result
import random
# Import random module to pick random number
secret = random.randint(1, 10)
# Random number between 1 and 10
guess = 0
# Start guess value
print("Guess a number between 1 and 10")
# Ask user to guess
while guess != secret:
# Keep looping until guess is correct
guess = int(input("Your guess: "))
# Take a guess from user
if guess < secret:
# Compare guess to secret print("Too low!")
# Hint for user
elif guess > secret:
# Check if higher print("Too high!")
# Hint for user
print("Correct! The number was", secret)
# Display success message