Interactive Python Tutorial Cheat Sheet with Explanations and Questions

Interactive Python Tutorial Cheat Sheet with Explanations and Questions


1. Introduction to Python

What is Python?

Python is a high-level, interpreted, and dynamically typed programming language known for its simplicity and readability.

Key Features:

  • Interpreted and dynamically typed
  • Easy syntax
  • Extensive standard libraries
  • Great community support

Example:

print("Hello, World!")

Questions:

  1. What type of programming language is Python?
  2. Write a line of code to print your name.

2. Variables and Data Types

Data Types:

  • int - Integer
  • float - Floating-point number
  • str - String
  • bool - Boolean

Example:

x = 5       # int
y = 3.14    # float
name = "Alice"  # str
is_happy = True  # bool

Type Checking:

print(type(x))

Questions:

  1. What data type would the value False be?
  2. Assign your age to a variable and print its type.

3. Control Flow

Conditional Statements:

x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is 5")
else:
    print("x is less than 5")

Loops:

for i in range(5):
    print(i)

count = 0
while count < 5:
    print(count)
    count += 1

Questions:

  1. Write a for loop that prints numbers from 1 to 10.
  2. What will be the output of if 10 < 5: print("Hi") else: print("Bye")?

4. Functions

Defining and Calling Functions:

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Default Parameters:

def greet(name="Guest"):
    return f"Hello, {name}!"

Questions:

  1. Define a function that returns the square of a number.
  2. What is the purpose of using default parameters?

5. Data Structures

Lists:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")

Tuples:

point = (10, 20)

Dictionaries:

person = {"name": "Alice", "age": 25}
print(person["name"])

Sets:

unique_numbers = {1, 2, 3}

Questions:

  1. What is the key difference between a list and a tuple?
  2. Create a dictionary with your name and favorite color.

6. Object-Oriented Programming (OOP)

Classes and Objects:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, my name is {self.name}")

p = Person("Alice")
p.greet()

Questions:

  1. What does __init__ method do?
  2. Create a class Car with attributes make and model.

7. File Handling

Reading and Writing Files:

with open("file.txt", "w") as f:
    f.write("Hello File")

with open("file.txt", "r") as f:
    content = f.read()
    print(content)

Questions:

  1. What does the with keyword do when opening a file?
  2. Write Python code to append a new line to a file.

8. Exception Handling

Try-Except Block:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Questions:

  1. What exception type handles a file not found error?
  2. Modify the above code to also print "Finished" using finally.

9. Modules and Packages

Importing Modules:

import math
print(math.sqrt(16))

Custom Modules:

Save as mymodule.py

def add(a, b):
    return a + b

In another file:

import mymodule
print(mymodule.add(2, 3))

Questions:

  1. What is the purpose of modules?
  2. How do you import only the sqrt function from the math module?

10. Popular Libraries

  • NumPy – Numerical computing
  • Pandas – Data analysis
  • Matplotlib – Plotting graphs
  • Requests – Handling HTTP requests
import numpy as np
arr = np.array([1, 2, 3])
print(arr)

Questions:

  1. Which library is used for data analysis?
  2. Write code to create a line plot using matplotlib.pyplot.

11. Final Practice Quiz

  1. Write a Python program to find the factorial of a number using a function.
  2. Create a list of numbers from 1 to 100 and print all even numbers.
  3. Read a file and count the number of lines.
  4. Create a class Student with attributes name and marks. Add a method to display student info.

End of Cheat Sheet



Comments