Download PDF: Python Programming Basics Cheat Sheet.pdf
# Basic structure
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
# Integer
number = 10
# Float
pi = 3.14
# String
name = "Alice"
# Boolean
is_valid = True
# Integer
a = 10
# Float
b = 20.5
# String
c = "Hello, World!"
# Boolean
d = True
if condition:
# code block
elif another_condition:
# another code block
else:
# another code block
for i in range(5):
print(i)
i = 0
while i < 5:
print(i)
i += 1
# Concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
# Formatting
name = "Alice"
age = 25
formatted_str = f"My name is {name} and I am {age} years old."
# Methods
uppercase_str = "hello".upper()
lowercase_str = "WORLD".lower()
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'w') as file:
file.write("Hello, file!")
# This is a single-line comment
x = 5 # This is an inline comment
"""
This is a multi-line comment
spanning multiple lines.
"""
y = 10
+ # Addition
- # Subtraction
* # Multiplication
/ # Division
% # Modulus
** # Exponentiation
// # Floor Division
== # Equal to
!= # Not equal to
> # Greater than
< # Less than
>= # Greater than or equal to
<= # Less than or equal to
and # Logical AND
or # Logical OR
not # Logical NOT
def function_name(parameters):
# code block
return value
result = function_name(arguments)
# Define a list
my_list = [1, 2, 3, 4, 5]
# Access elements
print(my_list[0]) # First element
# Add elements
my_list.append(6)
# Remove elements
my_list.remove(3)
# Slicing
print(my_list[1:3])
# Define a tuple
my_tuple = (1, 2, 3)
# Access elements
print(my_tuple[0])
# Define a dictionary
my_dict = {"name": "Alice", "age": 25}
# Access elements
print(my_dict["name"])
# Add elements
my_dict["email"] = "alice@example.com"
# Remove elements
del my_dict["age"]
# Define a set
my_set = {1, 2, 3, 4, 5}
# Add elements
my_set.add(6)
# Remove elements
my_set.remove(3)
try:
# code block that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# code block to handle the exception
print("Cannot divide by zero!")
finally:
# code block that will always execute
print("This will always execute.")
import math # Import the entire module
print(math.sqrt(16))
from math import sqrt # Import specific function
print(sqrt(16))
import numpy as np # Import with alias
array = np.array([1, 2, 3])