print("Welcome")
print("Welcome", 2025)
name = "Bob"
print(name)
print("Hi", name, "!")
print(f"Hi {name}!") # using formatted string (f-string)
name = input("What's your name? ")
print("Hello, " + name + "!")
age = input("Enter your age")
age = int(age)
pi = input("what's the value of PI?")
pi = float(pi)
try:
# code
except SomeError1:
# handle error
except SomeError2:
# handle error
except Exception as e:
print(f"An error occurred: {e}")
else:
# runs if no error
finally:
# always runs; useful for cleanup, closing resorces
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
In condition check, the following = False
0
"" (empty string)
[], {}, set()
None
False
Example:
if my_list:
print("Not empty!")
Swap values in one line:
a, b = b, a
If you don't care about a variable:
for _ in range(5):
print("Hello")
Assign inside expressions:
if (n := len("hello")) > 3:
print(n)
When Python runs a file, it assigns the special variable __name__.
If the file is being run directly (like python myfile.py), then:
__name__ == "__main__"
If the file is being imported into another file (like import myfile), then:
__name__ == "myfile"
A script (something you run directly).
A module (something you import into other files).
Example: myfile.py
def hello():
print("Hello!")
# bash: python myfile.py → runs hello()
# import myfile → doesn't run hello()
if __name__ == "__main__":
hello()