Python Basics
Essential Python fundamentals including variables, strings, lists, dictionaries, conditionals, loops, and functions.
Variables & Strings
# Hello world
print("Hello world!")
# Hello world with a variable
msg = "Hello world!"
print(msg)
# f-strings (using variables in strings)
first = 'albert'
last = 'einstein'
full = f"{first} {last}"
print(full) # albert einstein
Lists Basics
# Making a list
bikes = ['trek', 'redline', 'giant']
# Get first and last item
first = bikes[0] # trek
last = bikes[-1] # giant
# Looping through a list
for bike in bikes:
print(bike)
# Adding items to a list
bikes = []
bikes.append('trek') # add to end
bikes.insert(0, 'giant') # insert at position
Dictionaries
# Simple dictionary
alien = {'color': 'green', 'points': 5}
# Accessing a value
print(alien['color']) # green
alien.get('points', 0) # safe access with default
# Adding new key-value pair
alien['x_position'] = 0
If Statements
# Conditional tests
x == 42 # equal
x != 42 # not equal
x > 42 # greater than
x >= 42 # greater or equal
# Simple if statement
if age >= 18:
print("You can vote!")
# If-elif-else chain
if age < 4:
price = 0
elif age < 18:
price = 10
else:
price = 40
Functions
# Simple function
def greet():
print("Hello!")
greet()
# Passing an argument
def greet(username):
print(f"Hello, {username}!")
greet('jesse')
# Returning a value
def add(x, y):
return x + y
sum = add(3, 5) # 8