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:
- What type of programming language is Python?
- Write a line of code to print your name.
2. Variables and Data Types
Data Types:
int- Integerfloat- Floating-point numberstr- Stringbool- Boolean
Example:
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_happy = True # bool
Type Checking:
print(type(x))
Questions:
- What data type would the value
Falsebe? - 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:
- Write a
forloop that prints numbers from 1 to 10. - 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:
- Define a function that returns the square of a number.
- 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:
- What is the key difference between a list and a tuple?
- 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:
- What does
__init__method do? - Create a class
Carwith 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:
- What does the
withkeyword do when opening a file? - 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:
- What exception type handles a file not found error?
- 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:
- What is the purpose of modules?
- How do you import only the
sqrtfunction from themathmodule?
10. Popular Libraries
NumPy– Numerical computingPandas– Data analysisMatplotlib– Plotting graphsRequests– Handling HTTP requests
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
Questions:
- Which library is used for data analysis?
- Write code to create a line plot using
matplotlib.pyplot.
11. Final Practice Quiz
- Write a Python program to find the factorial of a number using a function.
- Create a list of numbers from 1 to 100 and print all even numbers.
- Read a file and count the number of lines.
- Create a class
Studentwith attributes name and marks. Add a method to display student info.
End of Cheat Sheet
Comments
Post a Comment