- Variables
- Type Conversion
- Comments
- Input
- Operators
- String Formatting
.2f,.1f,.3fprint()with commaprint()with+- f-strings
# Python Fundamentals Cheat Sheet
A beginner-friendly reference for Python basics with examples.
## 1. Variables
Variables are used to store values.
```python
name = "Alice"
age = 25
height = 5.4- Strings use quotes:
"text"or'text' - Integers and floats do not use quotes
Python can convert between types using int(), float(), and str().
age = "25"
age_int = int(age) # Converts to integer
height = 5
height_str = str(height) # Converts to stringUse comments to explain code:
# This is a single-line comment
'''
This is a
multi-line comment
'''The input() function reads user input as a string.
name = input("What is your name? ")
print("Hello,", name)Convert input to a number if needed:
age = int(input("Enter your age: "))| Type | Operator | Example |
|---|---|---|
| Arithmetic | + - * / // % ** |
a + b, a ** b |
| Assignment | = += -= *= |
x += 1 |
| Comparison | == != > < >= <= |
x == y |
| Logical | and or not |
x > 5 and x < 10 |
Example:
a = 10
b = 3
print(a + b) # 13
print(a % b) # 1name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))pi = 3.14159
print("Value of pi is {:.2f}".format(pi)) # 2 decimal places.2f= 2 decimal places.1f= 1 decimal place.3f= 3 decimal places
name = "Bob"
score = 91.235
print(f"Name: {name}, Score: {score:.2f}") # Score: 91.24Using commas in print() separates values with a space and auto-converts types.
name = "Alice"
age = 30
print("Name:", name, "Age:", age)Output:
Name: Alice Age: 30
You must convert non-strings using str().
name = "Bob"
age = 28
print("Name: " + name + ", Age: " + str(age))name = "Sam"
salary = 1234.5678
print(f"Name: {name}")
print(f"Salary (2 decimal): {salary:.2f}")
print(f"Salary (3 decimal): {salary:.3f}")
print(f"Salary (1 decimal): {salary:.1f}")Use if statements to make decisions in your program.
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")- Variables store data
- Input gives user data (as string)
- Use
int(),float(),str()for conversions - Use comments (
#,''') to explain code - Use
print()with,,+, orf""for output - Use
.2f,.1f, etc. for formatting floats
