Python

1. Input and Output
input()
Takes input from the user as a string.
print()
Displays output on the screen.
Example:
name = input("Enter your name: ")
print("Hello,", name)
2. Variables and Data Types**
int
Integer numbers
x = 10
float
Floating-point numbers
pi = 3.14
complex
Complex numbers
z = 2 + 3j
str
String (text)
name = "Alice"
str
String (text)
name = "Bob"
str
String (text)
name = 'Bob'
str
String & Multiline string (text)
name = """Bob"""
str
String & Multiline string(text)
name = '''Bob'''
bool
Boolean value: True
or False
is_valid = True
list
Ordered, mutable sequence
fruits = ["apple", "banana"]
tuple
Ordered, immutable sequence
coordinates = (10, 20)
range
Sequence of numbers
r = range(5)
dict
Key-value pairs
person = {"name": "Alice", "age": 25}
set
Unordered collection of unique items
colors = {"red", "green"}
frozenset
Immutable version of set
frozen = frozenset([1, 2, 3])
bytes
Immutable sequence of bytes
b = b"hello"
bytearray
Mutable sequence of bytes
ba = bytearray(5)
memoryview
View over binary data
mv = memoryview(bytes(5))
NoneType
Represents the absence of a value
value = None
Python manages memory automatically (no malloc
/free
like C). Garbage collection is built-in.
2.1. Main cast functions
x = str(1) # Convert to string
x = int("1") # Convert to int
x = float("1.1") # Convert to float
# String to bytes (encoding)
text = "Hello World"
encoded = text.encode('utf-8') # or 'ascii', 'utf-16', etc.
print(encoded) # Output: b'Hello World'
# Bytes to string (decoding)
decoded = encoded.decode('utf-8')
print(decoded) # Output: Hello World
3. Control Structures
num = 7
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")
4. Loops
for i in range(1, 6):
print(i)
while True:
print("ciao")
5. Functions
def add(a, b):
return a + b
def print_something(a, b):
print(a+b)
def nothing(a, b):
pass
print(add(3, 4))
5.1. Type hints:
def add(a : int, b : int) -> str:
return str(a + b)
6. File Handling
open()
Opens a file. Modes: "r"
, "w"
, "a"
, etc.
.read()
, .readlines()
, .write()
Reads from/writes to file.
.close()
Closes the file. (Not needed if using with
statement).
with open("data.txt", "w") as f:
f.write("Hello, File!")
When the program exits from the with block, the f.close()
is automatically called saving also the file content.
7. Object-Oriented Programming
Example:
class Person:
def __init__(self, name, age):
# Constructor
self.name = name # Object attribute
self.age = age # Object attribute
def method_name(self, years_gap):
self.age += years_gap
p = Person("Alice", 25) # Instatiation of an object
print(p.name, p.age) # Access object attributes
p.method_name(10) # Method call
10. Main Function (Optional in Python)
if __name__ == "__main__":
Python runs code here only if script is executed directly (not imported).
If you run the file with this instruction, the interpreter will execute the code inside the code block:
python3 file.py
If you import the file in another python script, the "if" code block will not be executed.
Example:
def greet():
print("Hello!")
if __name__ == "__main__":
greet()
Last updated