Python Basics Cheat Sheet

Python Basic Syntax & Data Types



Numbers


Python
Copy
int_num = 10  # Integer
float_num = 10.5  # Float
complex_num = 1 + 2j  # Complex number

Strings


Python
Copy
text = "Hello, World!"
multiline = """This is a
multiline string."""

String Methods


Python
Copy
text.upper()  # "HELLO, WORLD!"
text.lower()  # "hello, world!"
text.split(', ')  # ["Hello", "World!"]
text.replace("World", "Python")  # "Hello, Python!"

Boolean


Python
Copy
is_valid = True
is_equal = (5 == 5)  # True

Type Casting


Java
Copy
str_num = str(123)  # "123"
int_num = int("10")  # 10
float_num = float("10.5")  # 10.5

Python Print Function



Python
Copy
Print("Hello World")

# Output : Hello World

my_num = 5
print("My Number is ", my_num)

# Output : My Number is 5

# Print with sep keyword
print("Sunday", "Monday", "Tuesday", sep=',')

# Output : Sunday, Monday, Tuesday

Python Input Function



Python
Copy
print("Enter your name")
your_name = input()
print("Hello, ", my_name)

# Output : 
# Enter your name
# Hello, your name

Python len() & type() Functions

Python
Copy
msg = "Welcome"
year = 2024

len(msg)

# Output 
# 7

type(msg)

# Output 
# <class 'str'>

type(year)

# Output
# <class 'int'>

Python Math Operators



Operators Operation Example
** Exponent 2 ** 4 = 16
// Integer Division 22 // 8 = 2
(*) Multiplication 3 * 3 = 9
(/) Division 6 / 3 = 2.0
(%) Modulus / Reminder 9 % 2 = 1
(+) Addition 2 + 2 = 4
(-) Substraction 4 - 2 = 2

Python Comparison Operators



Operators Operation Example
== Equal to 2 == 2 # True
!= Not equal to 2 != 2 # False
< Less than 2 < 3 # True
> Greater Than 2 > 3 # False
<= Less than or Equal to 2 <= 3 # True
>= Greater than or Equal to 2 >= 2 # True

Python Control Structures



If-Else Statements


Python
Copy
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")

For Loop


Python
Copy
for i in range(5):
    print(i)  # Outputs: 0 1 2 3 4

While Loop


Python
Copy
count = 0
while count < 5:
    print(count)
    count += 1  # Outputs: 0 1 2 3 4

List Comprehension


Python
Copy
squares = [x**2 for x in range(10)] 

# Output
# [0, 1, 4, ..., 81]

Python Functions



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

result = add(5, 3)  # Outputs: 8

# Lambda Function
square = lambda x: x ** 2
square(4)  # Outputs: 16

Python Classes and Objects



Python
Copy
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return "Woof!"

my_dog = Dog("Buddy", 5)
print(my_dog.bark())  # Outputs: Woof!

Python File Handling



Python
Copy
# Writing to a file
with open('file.txt', 'w') as file:
    file.write("Hello, World!")

# Reading from a file
with open('file.txt', 'r') as file:
    content = file.read()
    print(content)  # Outputs: Hello, World!

Python Error Handling



Python
Copy
try:
    x = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
finally:
    print("This runs no matter what.")

Python Modules and Packages



Python
Copy
# Importing a module
import math
print(math.sqrt(16))  # Outputs: 4.0

# From import
from math import sqrt
print(sqrt(25))  # Outputs: 5.0

Python Decorators



Python
Copy
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Python Generators



Python
Copy
def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

counter = count_up_to(5)
for number in counter:
    print(number)

Python Match-Case Statement



Python
Copy
response_code = 200
match response_code:
	case 200 | 201:
		print("OK")
	case 307:
		print("Temporary Redirect")
	case 400:
		print("Bad Request")
	case 401:
		print("Unauthorized")
	case 500:
		print("Internal Server Error")
	case 503:
		print("Service Unavailable")
	case _:
		print("Invalid Code")
		
# Output : OK