Python Tutorial from Scratch


The site is under development.

Python Tutorial

Introduction to Python

Python is a high-level, beginner-friendly programming language known for its easy-to-read syntax. It allows new learners to focus on logic instead of complex symbols. Python is used in almost every field like websites, apps, AI, automation, and data science.

Examples:
1. print("Hello, World!")
2. print(5 + 9)
3. name = "Majid"
4. print(type(name))
5. if 10 > 3: print("Python is easy!")


What is Python?

Python is an interpreted, open-source programming language created in 1991 by Guido van Rossum. It is used worldwide because it is powerful yet simple. Python can run on Windows, Mac, Linux, and even mobile devices. Major companies like Google, Netflix, and NASA use Python — meaning learning it gives you real job opportunities.

Examples:
1. print("Learning Python!")
2. age = 20; print(age)
3. print("A" * 5)
4. print(10 == 10)
5. for i in range(3): print(i)


Python Versions & Differences

There are two major versions: Python 2 and Python 3. Python 3 is modern, faster, and supported today. Python 2 is outdated and no longer updated. Printing changed from print "Hi" to print("Hi"). Python 3 supports emojis, modern math operations, and improved security. Always use Python 3 for new projects.

Examples:
1. print("Python 3!")
2. print(8/3) (float division)
3. print(8//3) (integer division)
4. print("Emoji 😊")
5. input("Enter your name: ")


Installation & Setup (Windows, Mac, Linux)

You can download Python from python.org. On Windows, check “Add Python to PATH” before installing. Mac already comes with Python, but you can install Python 3 using Homebrew. On Linux, use a command like sudo apt install python3. After installing, run a simple program to verify everything works.

Examples:
1. Command: python3 --version
2. Run script: python3 hello.py
3. Create directory: mkdir MyPython
4. Navigate: cd MyPython
5. Start Python REPL: python3


Python IDEs (VS Code, PyCharm, Jupyter)

IDE stands for Integrated Development Environment. VS Code is lightweight and recommended for beginners. PyCharm is strong for bigger projects. Jupyter Notebook is great for data science and lets you run code step-by-step inside small cells. All IDEs help you write code faster and fix errors easily.

Examples:
1. VS Code: Write print("VS Code!") and run.
2. PyCharm: Create new project → run x = 5
3. Jupyter: 2 + 2 → Shift + Enter
4. Install Python extension in VS Code
5. PyCharm Debugger to check variables

Running Python Programs

Python programs can run in different ways depending on your setup. You can run code inside a terminal or command prompt by typing commands directly, or you can save your code in a file ending with .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.

Examples (ways to run code):
1. python3 myscript.py
2. Terminal interactive: python3
3. VS Code: Click the "Run" button
4. Double-click a Python file (Windows)
5. Jupyter Notebook: Press Shift + Enter
6. Linux script run: ./myscript.py (after chmod +x)


Interactive Mode vs Script Mode

Python offers two ways to write and test programs. "Interactive mode" is when you type code line-by-line inside the Python shell (REPL). It immediately shows the result, which is great for testing small commands, math, or learning new functions. "Script mode" is used when writing longer programs in a .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.

Examples:
1. Interactive: python33 + 4
2. Script: Save file test.pypython3 test.py
3. Interactive: print("Hi")
4. Script: name = "Majid"; print(name)
5. Interactive: Trying commands like type("Hello")
6. Script: Creating a calculator program saved as calc.py


Writing Your First Program (print("Hello World"))

Your first Python program usually begins with a simple command using the print function. The print statement displays text or numbers on the screen. Writing print("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.

Examples:
1. print("Hello World")
2. print("Welcome to Python!")
3. print("Majid is learning Python")
4. print(5 + 5)
5. print("Age:", 25)
6. print("😊 Happy Coding!")

Basic Syntax & Comments

Python syntax refers to the rules that define how we write code so the computer understands it. Python uses simple and human-friendly syntax, meaning we don’t need heavy punctuation like other languages (no semicolons required). Every statement must follow correct spelling and structure — even a small mistake causes an error. Comments are notes written in code that the computer ignores; they help explain what the code does. Comments are very useful when learning Python because they help others (and your future self) understand your program better. Proper syntax and comments make your code clean, readable, and professional.

Examples:
1. print("Python Syntax")
2. # This is a comment
3. name = "Majid"
4. print(name)
5. x = 10; y = 20; print(x + y)
6. print("Syntax is easy!")


Indentation Rules

Indentation means adding spaces at the beginning of a line. In Python, indentation is "not optional" — it tells the program which statements belong together. Instead of using curly braces like other languages, Python uses indentation to group code blocks such as inside loops, functions, and conditions. Usually, developers use 4 spaces for each indentation level. If indentation is wrong or inconsistent, Python will show “IndentationError.” This teaches new programmers how to structure logic cleanly, making Python code beautiful and easy to understand.

Examples:
1. if 5 > 3:
    print("Yes")

2. for i in range(3):
    print(i)

3. def hello():
    print("Hello!")

4. x = 10
if x == 10:
    print("x is 10")

5. while True:
    break

6. if True:
    # inside block



Single-line & Multi-line Comments

Comments allow you to write notes inside your code that Python ignores. A "single-line comment" begins with # 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.

Examples:
1. # This is a single-line comment
2. print("Hello") # Comment after code
3. ''' Multi
Line
Comment '''

4. """Explain program here"""
5. # TODO: Add more features
6. # Python ignores comments completely

Variables and Data Types

Variables are containers used to store data in Python, such as numbers and text. You can give any name to a variable, and Python will remember the value assigned to it. Unlike other programming languages, Python does not require a special keyword to create variables — just write the name and assign a value using the equals sign (=). Data types represent the nature of data stored in a variable, like numbers for math and text for words. Python automatically detects the type. Understanding variables and data types is important because they help the computer store, manage, and process information correctly.

Examples:
1. x = 10 # variable storing a number
2. name = "Majid" # variable storing text
3. price = 9.99 # variable storing decimal value
4. is_learning = True # variable storing a Boolean
5. print(x) # prints value of x
6. print(type(name)) # shows data type


Integers, Floats, Strings & Booleans

Python has several built-in data types. Integers (int) are whole numbers used for counting. Floats (float) are numbers with decimal points used for more accurate calculations. Strings (str) represent text inside quotes, like names or messages. Booleans (bool) can only be True or False and are often used in decision-making. Knowing these data types is essential because they help you choose the correct type depending on what you want your program to do — like math, storing names, or checking conditions. Python automatically assigns a type depending on your value, which makes coding easier.

Examples:
1. age = 25 # integer
2. height = 5.8 # float value
3. message = "Hello" # string text
4. is_adult = True # boolean value
5. print(type(height)) # shows float
6. print(10 + age) # integer math


Naming Conventions

Naming conventions are rules that help create clean and readable variable names. A Python variable must start with a letter or underscore, never a number. It cannot contain spaces or special characters except for underscores. Variables should have meaningful names so others can understand your code. Python is case-sensitive, meaning Name 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.

Examples:
1. first_name = "Majid" # clear name
2. _count = 10 # valid name starting with underscore
3. user_age = 20 # snake_case format
4. total_price = 99.99 # descriptive
5. # Wrong: 1name = "Error" # cannot start with number
6. # Wrong: user-name = "error" # hyphen not allowed


Type Casting

Type casting means converting one data type into another. Python provides built-in functions for conversion such as int() 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.

Examples:
1. x = "5"; y = int(x) # convert string to integer
2. num = 10; txt = str(num) # number to text
3. value = float("3.14") # string to float
4. print(bool(1)) # True
5. print(int(3.99)) # becomes 3
6. print(type(txt)) # shows string type

Input & Output — Full Explanation (180 words)

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.

Examples (Fully Commented)
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 — Full Explanation (180 words)

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.

Examples
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 — Full Explanation (180 words)

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.

Examples
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 — Full Explanation (180 words)

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.

Examples
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 — Full Explanation (180 words)

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.

Examples
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 — Full Explanation (180 words)

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.

Examples
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

Strings — Full Explanation (180 words)

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.

✔ Examples
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

String Indexing & Slicing — Full Explanation (180 words)

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.

✔ Examples
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 — Full Explanation (180 words)

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.

✔ Examples
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 — Full Explanation (180 words)

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.

Examples
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.


1. Number Swap Program
# 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
2. Simple Age Calculator
# 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
3. Simple Quiz Game
# 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
4. Simple Interest Calculator
# 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
5. Mad Libs — Fun Word Game
# 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
6. Even or Odd Number Checker
# 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
7. Multiplication Table Generator
# 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
8. Count Vowels in a String
# 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
9. Reverse a String
# 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
10. Tip Calculator
# 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.


5 Simple Examples (Every line commented)

Example 1: Good variable naming

name = "Majid"
age = 25
print(name, age)

Example 2: Spaces around operators

x = 10 + 5
y = x * 2
print(y)

Example 3: Indentation is required

if True:
    print("Indented correctly")

Example 4: Limit line length & clear message

message = "Writing short lines makes the code easier to read"
print(message)

Example 5: Commenting wisely

total = 100
spent = 40
remaining = total - spent
print(remaining)

Mini 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.


Mini Project 1 — Simple Calculator
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

Mini Project 2 — Temperature Converter
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

Mini Project 3 — Guess-the-Number Game
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