1. Variable Assignment:
my_variable = 42 # now my_variable references 42
2. Primitive Data Types:
my_integer = 42 # int
my_float = 3.14 # float
my_string = "Hello, World!" # string
my_boolean = True # boolean
3. How to Use Dictionaries:
my_dict = {"key1": "value1", "key2": "value2"}
print(my_dict["key1"]) # Accessing a dictionary value
4. How to Use Lists:
my_list = [1, 2, 3, 4]
print(my_list[0]) # Accessing list elements
my_list.append(5) # Appending to a list
5. if/elif/else:
# an if/elif/else statement
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
# or just an if statement
if x == 10:
print("x is 10")
# or an if/else statement
if x < 10:
print("x is less than 10")
else:
print("x is equal to or greater than 10")
6. for Loops:
# iterate over a range
for i in range(5):
print(i) # Prints numbers from 0 to 4
# or iterate over a list
list_of_items = ["some item", "some other item"]
for item in items:
print(item)
# or iterate over a dictionary
some_dictionary = {
"some key": "some value"
}
for key, val in some_dictionary.items():
print(key, val)
7. while Loops:
count = 0
while count < 5:
print(count) # Prints numbers from 0 to 4
count += 1 # always be sure to increment
# your counter to avoid an infinite loop
8. Ranges:
# Creates a range from 0 to 4 (exclusive of 5)
my_range = range(5)
for i in my_range:
print(i)
# creates a range from 2 to 10, exclusive of 11, stepping by 2
my_even_range = range(2, 11, 2)
for num in my_even_range:
print(num)
9. Built-in Methods, String Manipulation, List Manipulation:
my_string = "Hello, World!"
length = len(my_string) # Get the length of a string
substring = my_string[0:5] # Get a substring using slice shorthand
my_list = [1, 2, 3]
my_list.append(4) # Appending to a list
10. How to Use Return in a Function:
# always returning something, otherwise the function will return None by default
def add_numbers(x, y):
result = x + y
return result
sum_result = add_numbers(5, 3) # Calling the function and storing the result