Created
October 15, 2024 03:19
-
-
Save davidhartsough/8fbf4014fc0f25868d91ef0e69f49408 to your computer and use it in GitHub Desktop.
Intro to Python basics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# My comment | |
# Remember: use cmd i to run this file as a script | |
"""Style guide | |
module_name | |
package_name | |
ClassName | |
method_name | |
ExceptionName | |
function_name | |
GLOBAL_CONSTANT_NAME | |
global_var_name | |
instance_var_name | |
function_parameter_name | |
local_var_name | |
snake_case: | |
modules, packages, methods, functions, variables, parameters | |
PascalCase: | |
Classes, Exceptions | |
""" | |
""" | |
multi-line | |
comment | |
""" | |
# variables | |
fav_food1 = "sushi" | |
fav_food2 = "pizza" | |
my_number = 2**7 # 2 to the power of 7 | |
# log or echo or print with print() | |
print("I love to eat {} and {}.".format(fav_food1, fav_food2)) | |
print(f"I love to eat {fav_food1} and {fav_food2}.") | |
print( | |
""" | |
What's good. this is a multi line string | |
""" | |
) | |
# concat | |
print("pizza " + "sushi") | |
# repeat | |
print(3 * "yo ") | |
print("hey " * 3) | |
# strings and their characters can be treated like arrays | |
print(fav_food1[3]) | |
# using a negative number starts from the end | |
print(fav_food1[-1]) | |
# slicing a string using indexes | |
print(fav_food2[0:4]) | |
# omit an index to assume the beginning or end | |
print(fav_food1[-2:]) | |
print(fav_food2[:4]) | |
# access the length of a string using len() | |
print(len(fav_food1)) | |
# 4 space indentation for code blocks | |
# for loop | |
for val in fav_food1: | |
pass | |
print("**** data types: boolean, number, string, tuple, list, dict ****") | |
# data types | |
# booleans | |
my_bool = True | |
my_bool = False | |
# numbers | |
integer = 123 | |
floatingpoint = 12.3 | |
# strings | |
my_string = "this is a string" | |
# immutable tuples -- referenced like lists | |
immutable_tuple = ("string", 321, True) | |
print(immutable_tuple[0]) | |
# lists are basically arrays | |
my_list = ["some string", "some thing"] | |
print(my_list[1]) | |
# dictionaries are basically objects | |
my_dictionary = {"name": "steve", "age": 42, "weight": 150.7, "likes_pizza": True} | |
print(my_dictionary["name"]) | |
print("**** type() ****") | |
# find out the data type of a variable using type() | |
print(type(my_dictionary)) | |
print(type(my_list)) | |
print(type(immutable_tuple)) | |
print("**** len() ****") | |
# use len() to get the length of dictionaries, lists, and tuples | |
print(len(my_dictionary)) | |
print(len(my_list)) | |
print(len(immutable_tuple)) | |
print("**** casting: str() int() ****") | |
# casting a number to a string | |
print("Here is a number converted to a string: " + str(integer)) | |
# casting a string to a number | |
string_number = "24" | |
print(int(string_number) / 4) | |
print("**** conditionals: if elif else ****") | |
print(f"number = {my_number}") | |
# conditionals | |
# if elif else | |
if my_number < 10: | |
print("less than 10") | |
elif my_number == 10: | |
print("equals 10") | |
else: | |
print("greater than 10") | |
if my_number >= 100 and my_number <= 200: | |
print("between 100 and 200") | |
if my_number == 10 or my_number > 20: | |
print("is 10 or greater than 20") | |
if not my_number < 10: | |
print("not less than 10") | |
if my_number != 10: | |
print("is not 10") | |
print("**** for in loops ****") | |
# for in loops | |
for value in my_list: | |
print(value) | |
for key in my_dictionary: | |
print(f"{key}: {my_dictionary[key]}") | |
my_dict_keys = my_dictionary.keys() | |
for key in my_dict_keys: | |
print(f"{key} --> {my_dictionary[key]}") | |
my_dict_values = my_dictionary.values() | |
for value in my_dict_values: | |
print(value) | |
for key, value in my_dictionary.items(): | |
print(f"{key} => {value}") | |
print("**** range ****") | |
# using range | |
for i in range(0, 5, 1): | |
print(i) | |
# start is inclusive | |
start = 1 | |
# stop is exclusive | |
stop = 11 | |
step = 1 | |
for i in range(start, stop, step): | |
print(i) | |
start = 5 | |
stop = 55 | |
step = 5 | |
for i in range(start, stop, step): | |
print(i) | |
# step is assumed as 1 | |
for i in range(0, 5): | |
print(i) | |
# start is assumed as 0 | |
for i in range(5): | |
print(i) | |
# break | |
print("**** break ****") | |
abbrev = "" | |
for char in "string": | |
if char == "i": | |
break | |
abbrev += char | |
print(abbrev) | |
# continue | |
print("**** continue ****") | |
no_vowels = "" | |
for char in "mississippi": | |
if char == "i": | |
continue | |
no_vowels += char | |
print(no_vowels) | |
print("**** while loops ****") | |
# while loops | |
count = 0 | |
while count < 5: | |
print(count) | |
count += 1 | |
print("**** while else ****") | |
# else in a while is like do while but in reverse, syntactically | |
count = 0 | |
while count < 5: | |
print(count) | |
count += 1 | |
else: | |
print("else boy") | |
print("**** functions ****") | |
# function definition | |
def printHi(): | |
print("hi -- from printHi() function") | |
printHi() | |
print("**** parameters ****") | |
def sayHey(name): | |
print(f"Hey {name}!") | |
sayHey("Steve") | |
print("**** return ****") | |
def add(a, b): | |
sum = a + b | |
return sum | |
print("add(3, 4) => ", add(3, 4)) | |
total = add(16, 64) | |
print("total => ", total) | |
print("**** default parameters ****") | |
def sayHello(name="Jimmy", caps=False): | |
greeting = f"Hello {name}!" | |
if caps: | |
greeting = greeting.upper() | |
print(greeting) | |
print("**** named arguments ****") | |
sayHello(name="James", caps=False) | |
sayHello(caps=True) | |
print("**** multiple args using splat operator: *args ****") | |
def getTheSum(*nums): | |
sum = 0 | |
for num in nums: | |
sum += num | |
return sum | |
print(getTheSum(4, 4, 8)) | |
print("**** ternary operators ****") | |
# ternary --> <result_if_true> if <condition> else <result_if_false> | |
my_name = "David" | |
is_cool = True if my_name == "David" else False | |
print("Yeah David is cool" if is_cool else "Nah that person ain't cool") | |
print("**** lambdas ****") | |
# a lambda is an anonymous function | |
print(list(map(lambda x: x**2, [1, 2, 3]))) | |
print("**** classes ****") | |
class Person: | |
def __init__(self, name, age, city): | |
self.name = name | |
self.age = age | |
self.city = city | |
steve = Person("Steve", 25, "Boise") | |
jen = Person("Jen", 35, "Brooklyn") | |
print(f"{steve.name} is {steve.age} years old and lives in {steve.city}") | |
print(f"{jen.name} is {jen.age} years old and lives in {jen.city}") | |
print("**** methods ****") | |
class House: | |
def __init__(self, color="purple"): | |
self.color = color | |
def paint(self, color): | |
self.color = color | |
my_house = House("teal") | |
print("My house is painted ", my_house.color) | |
my_house.paint("yellow") | |
print("Now my house is painted ", my_house.color) | |
print("**** encapsulation ****") | |
class Family: | |
def __init__(self, members=[steve, jen]): | |
self.members = members | |
self.house = House() | |
def printPaint(self): | |
print(self.house.color) | |
def printMembers(self): | |
for member in self.members: | |
print(f"{member.name} is {member.age} years old.") | |
def addMember(self, member): | |
self.members.append(member) | |
my_family = Family() | |
my_family.addMember(Person("Alicia", 30, "San Fran")) | |
my_family.printPaint() | |
my_family.printMembers() | |
print("**** chaining methods ****") | |
class Maths: | |
def __init__(self): | |
self.result = 0 | |
def add(self, *nums): | |
for num in nums: | |
self.result += num | |
return self | |
def subtract(self, *nums): | |
for num in nums: | |
self.result -= num | |
return self | |
my_maths = Maths() | |
print(my_maths.add(4, 8).subtract(2, 2).add(4, 4, 4).result) | |
print(my_maths.add(2).add(2, 5, 1).subtract(3, 2).result) | |
print("**** the end ****") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python → let's learn it
This one goes out to all the homies who are juuusssttt getting started learning Python.
Cheat sheets (as PDFs):