Python Basics Cheat Sheet
Tips
Practice coding regularly.
Don’t be afraid to ask for help;)
Have fun and be creative!
1. Basic Python Syntax
• Print a message:
• Comments:
2. Variables and Data Types
Variables are used to store information.
• Variables:
name = Alice
• Data Types
Common data types include:
- Strings: “Hello”
- Integers: 123
- Floats: 3.14
- Booleans: True or False
pi = 3.14
is_happy = True
greeting = “Hi”
3. Basic Operations
• Addition: +
• Subtraction: –
• Multiplication: *
• Division: /
• Arithmetic Operations:
subtraction = 5 – 3 #2
multiplication = 5 * 3 #15
division = 5 / 3 #1.666…
• String Concatenation:
4. Lists
Lists store multiple items in a single variable.
• Creating a list:
• Accesing list elements:
• Adding elements to a list:
5. Conditional Statements
Conditional statements are used to make decisions in your code.
• If, Elif, Else
if age < 13:
print(“You are a child.”)
elif age < 20:
print(“You are a teenager.”)
else:
print(“You are an adult.”)
6. Loops
Loops repeat a piece of code multiple times
• For Loop:
print(fruit)
• While Loop:
while count < 5:
print(count)
count += 1
7. Functions
Functions are blocks of code that do a specific task.
• Defining a function:
return “Hello” + name
print(greet(“Alice”)) # “Hello Alice”
8. Importing Libraries (also know as modules)
You can use external libraries to add more functionality to your code.
• Using a module:
9. Basic Input/Output
You can get input from the user with the input() function.
• Getting user input:
print(“Nice to meet you,” + user_name)
10. Simple Error Handling
Use try and except to handle errors.
• Try/Except:
result = 10/0
except ZeroDivisionError:
print(“You can’t divide by zero!””)
11. Dictionaries
Dictionaries store data in key-value pairs.
• Creating a dictionary:
student = {
“name”: “Alice”,
“age”: 13,
“grade”: “8th”,
}
# Accessing values
print(student[“name”]) # “Alice”