Python
Python
Naming conventions:
Strings
Guess = 9
Print(f”your guess of {guess} was incorrect”) F strings!!! Sames a ` ${var}` in JS.
If Statements
if name == “Tim”:
print(f”Hi {name}, you’re smelly”)
elif == “sam”:
print(f”Hi {name}, you’re cute”)
else:
print(“Hi nice stranger!”)
NOTE: Python is space sensitive. The indent of the print or the if block needs to be there or
python views it as the next line of code to read. Not part of the if statement.
Truthiness / falsiness
Falsy values are Empty objects, empty strings, None, and zero.
Logical operators
and or not
if a and b no caps, just write and, or between the conditions.
Use not to negate. IE:
if not is_weekend:
print(“go to work”)
is vs ==
“is” is reference the same place in memory
== is reference values of variables.
Import Library
Import random Allow you to use the random.randint(min, max)
Player = Input(“what is your name Player?”).lower() Converts all the string to lower case.
For loops
Ranges
Range(7) – array with 7 (0-6)
Range(1, 8) – array with 6 items, 1-7
Range(1, 10, 2) – Gives odds from 1 to 10
Range(7, 0, -1) counts down from 7 to 1
While loops
While im_tired:
# Do something
Lists (Arrays)
len(exampleList) -> 4
print[0] Prints 1
print[1] dog
[num*2 if num % 2 ==0 else num/2 for num in numbers] If num is even, multiply by 2, else num/2
Nest Lists
A list with list elements nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Nums[0][2] 3
Nums[3][1] 8
Dictionary
Instructor = {
“name”: “bob”,
“age”: 3,
“gender”: “male”,
}
For k, v of cat.items():
Print(f”Key {k}, value: {v}”)
if name in cat:
print(f”Cat’s name is: {name}”)
cat.clear() -> removes all key value pairs in a dictionary. Completely removes key and value to have {}
newList = cat.copy() Creates a copy of cat (doesn’t reference the location of memory
{}.fromkeys([“name”, “age”, “gender”], “unknown”) Gives you name: unknown,
age: unknown, gender unknown
** Usually used to create default values.
Cat.get(“name”) will return name value if it exists, otherwise it’ll give “none” vs an error
Cat.pop(“name”) removes key value pair of “name” gets rid of name: eddie. Leaving the other K/P