List
Session 1: Getting Started with Python and Fundamentals
What is Python?
Python is a high-level, readable, and multi-purpose programming language. Its simple syntax makes writing code feel very similar to writing in English, which is why it is widely considered the best choice for beginners.
Essential Tools & Installation
- Installing Python: Visit python.org and download the latest version. (Ensure you check the box "Add Python to PATH" during installation).
- What is PyCharm? A professional Integrated Development Environment (IDE) specifically for Python. It offers smart tools that act as an assistant for large-scale projects.
- What is Jupyter Notebook? An interactive environment that allows you to run code in separate blocks and see the results instantly. It is perfect for learning, data analysis, and quick testing.
- What is Pip? It stands for "Preferred Installer Program." It is a tool used to download and install Python libraries and packages from the internet.
Variables and Data Types
In Python, variables are used to store data. The primary types include:
- int: Integers (e.g.,
10) - float: Floating-point numbers (e.g.,
15.5) - str: Strings or text (e.g.,
"Hello") - bool: Logical values (
TrueorFalse)
Type Detection and Casting
To check a variable's type, use the type() function:
x = 10
print(type(x)) # <class 'int'>
To convert between types (Casting):
y = float(x) # Convert int to float -> 10.0
s = str(x) # Convert int to string -> "10"
Input and Output
Use input() to receive data from the user and print() to display results:
name = input("Enter your name: ")
print("Hello", name)
Note: input() always returns a string. If you need a number, you must cast it: int(input()).
Mathematical Operators
- Addition:
+| Subtraction:-| Multiplication:*| Division:/ - Power:
**(e.g.,2 ** 3equals 8) - Modulus (Remainder):
% - Floor Division:
//
Exercise Solutions: Session 1
1. Swapping Two Variables Without a Temporary Variable
Python allows you to swap values in a single line:
a = 5
b = 10
a, b = b, a
print("a:", a, "b:", b)
Explanation: Python creates a "tuple" of the right-hand side first and then unpacks it into the variables on the left.
2. Calculating Tip, Tax, and Total
food_cost = float(input("Enter the meal charge: "))
tip = food_cost * 0.18
tax = food_cost * 0.07
total = food_cost + tip + tax
print(f"Tip: {tip}")
print(f"Tax: {tax}")
print(f"Total: {total}")
Explanation: We cast the input to float for precise decimal calculations, calculated the percentages, and summed them up.
3. Cookie Ingredient Adjuster
Since the original recipe makes 48 cookies, we find the ratio for one cookie and multiply it by the desired amount.
cookies_needed = int(input("How many cookies do you want to make? "))
ratio = cookies_needed / 48
sugar = 1.5 * ratio
butter = 1 * ratio
flour = 2.75 * ratio
print(f"Sugar needed: {sugar} cups")
print(f"Butter needed: {butter} cups")
print(f"Flour needed: {flour} cups")
4. Solving a Quadratic Equation
We use the Discriminant formula: $$Delta = b^2 - 4ac$$.
import math
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
print(f"Two real roots: {x1} and {x2}")
elif delta == 0:
x = -b / (2*a)
print(f"One repeated root: {x}")
else:
print("This equation has no real roots.")
Explanation: We imported the math library to use sqrt(). The if-elif-else structure handles the three possible mathematical outcomes based on the value of Delta.
Session 2: Logic, Conditionals & Control Flow
1. Comparison Operators (The Basis of Logic)
We use these operators to compare values. The result is always a Boolean value: either True or False.
==: Equal to!=: Not equal to</>: Less than / Greater than<=/>=: Less than or equal to / Greater than or equal to
2. Logical Operators (Combining Conditions)
Sometimes we need to check multiple conditions at once:
and: Returns True if both sides are true.or: Returns True if at least one side is true.not: Inverts the result (turns True to False and vice-versa).
3. Conditional Statements (If, Elif, Else)
This is how we tell Python to make decisions.
Crucial Note: In Python, you must use a colon (:) after each condition, and the next line must be indented (4 spaces). This indentation defines the block of code belonging to that condition.
if: If the condition is true, execute this code.elif: (Short for else if) If the previous condition was false, but this one is true, execute this.else: If none of the above conditions were true, execute this as a fallback.
4. The Match-Case Structure (Python 3.10+)
This is a cleaner alternative to long if-elif chains when you are checking a single variable against multiple specific values. The _ symbol acts as a "default" or "catch-all" case (similar to else).
Programming Challenges: Solutions & Explanations
1. Triangle Analyzer
Goal: Practice comparison operators and nested conditions.
a = float(input("Enter side A: "))
b = float(input("Enter side B: "))
c = float(input("Enter side C: "))
# Checking the Triangle Inequality Theorem
if (a + b > c) and (a + c > b) and (b + c > a):
if a == b == c:
print("Result: Equilateral triangle")
elif a == b or a == c or b == c:
print("Result: Isosceles triangle")
else:
print("Result: Scalene triangle")
else:
print("Result: Invalid Triangle")
Explanation: First, we check if the sides can mathematically form a triangle. If valid, we enter a "nested" condition to determine its type based on how many sides are equal.
2. Advanced Discount System
Goal: Prioritizing conditions and handling independent logic.
amount = float(input("Enter amount: "))
is_member = input("Are you a member (True/False)? ").lower() == "true"
if amount > 200:
discount = 0.20 if is_member else 0.10
elif 100 <= amount <= 200:
discount = 0.05
else:
discount = 0
final_price = amount * (1 - discount)
print(f"Final Price: {final_price}")
if amount > 500:
print("Message: You get a Special Gift!")
Explanation: We use elif to define price ranges. Note that the "Special Gift" check is a separate if block because it applies regardless of the specific discount applied.
3. Leap Year Logic
Goal: Understanding complex logic using and, or, and %.
year = int(input("Enter year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Result: It is a Leap Year.")
else:
print("Result: Not a Leap Year.")
Explanation: A year is a leap year if it's divisible by 400 OR (divisible by 4 AND NOT divisible by 100). We combined this into a single logical expression.
4. Nested Security Check
Goal: Practicing priority in nested structures and using not.
username = input("Username: ")
password = input("Password: ")
is_banned = input("Is user banned (True/False)? ").lower() == "true"
if is_banned:
print("Result: Account Locked")
else:
if username == "admin":
if password == "1234":
print("Result: Welcome Admin")
else:
print("Result: Wrong Password")
else:
print("Result: User Not Found")
Explanation: Safety comes first. We immediately check if the user is banned. Only if they are not banned do we proceed to check the username and then the password.
5. Smart Converter (with Match Case)
Goal: Using match case with internal conditional checks.
number = float(input("Enter number: "))
mode = input("Enter mode (1-3): ")
match mode:
case "1":
if number < 0:
print("Negative input not allowed")
else:
print(f"Result: {number * 0.62} miles")
case "2":
if number < -273.15: # Absolute zero
print("Negative input not allowed")
else:
print(f"Result: {(number * 1.8) + 32} Fahrenheit")
case "3":
res = "Even" if number % 2 == 0 else "Odd"
print(f"Result: The number is {res}")
case _:
print("Result: Invalid Code")
Explanation: The match statement allows us to jump to the correct logic based on the user's choice. Inside cases 1 and 2, we added a safety if to handle invalid inputs like negative distances or temperatures below absolute zero.