Coggle requires JavaScript to display documents.
yield
def my_range(x): i=0 while i < x: yield i i += 1
for x in my_range(5): print(x)
sq_list = [x**2 for x in range(10)] # this produces a list of squares sq_iterator = (x**2 for x in range(10)) # this produces an iterator of squares
# that executes the file and runs the code within it import 3rd_party_file_without_py as fn fn.my_function(1234)
def my_function(param): return param def main(): print("Testing my_function") assert(my_function(3) == 3) print("All tests passed") if __name__ == "__main__": # is only called when the file is executed while not being imported main()
from module_name import object_name as new_name
import os.path os.path.isdir('my_path')
import os.path.isdir
import os os.path.isdir('my_path')
*
pip install package_name
requirements.txt
beautifulsoup4==4.5.1 bs4==0.0.1 pytz==2016.7 requests==2.11.1
pip install -r requirements.txt
q3 = months[6:9]
first_half = months[:6]
months = ['January', 'February',...]
greeting = "Hello there" print('her' in greeting, 'her' not in greeting)
capitalized_cities = [] for city in cities: capitalized_cities.append(city.title())
capitalized_cities = [city.title() for city in cities]
if
squares = [x**2 for x in range(9) if x % 2 == 0]
else
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
squares = [x**2 for x in range(9) if x % 2 == 0 else x + 3]
list.append(elem)
>>> range(3, 6) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5]
dimensions = (22,33,44)
dimensions = 22,33,44
length, width, height = dimensions
numbers = [1, 2, 6, 3, 1, 1, 6] unique_nums = set(numbers) print(unique_nums)
fruit = {"apple", "banana", "orange", "grapefruit"}
union
intersection
difference
elements = {"hydrogen": 1, "helium": 2, "carbon": 6} print(elements["helium"]) print(elements.get("dilithium")) elements["lithium"] = 3
in
n = elements.get("dilithium") print(n is None) print(n is not None)
is
is not
elements['dilithium']
.get(key)
.get()
elements.get('kryptonite', 'There\'s no such element!')
range([start=0], stop, [step=1])
print(list(range(4))) [0,1,2,3]
print(list(range(2,6))) [2,3,4,5]
print(list(range(1,10,2))) [1,3,5,7,9]
print(range(4)) range(0,4)
for city in cities:
for number in range(4): print(number)
cities = ['new york city', 'mountain view', chicago', 'los angeles'] for index in range(len(cities)): // .title() capitalizes a string cities[index] = cities[index].title()
for key, value in cast.items(): print("Actor: {} Role: {}".format(key, value))
cast = { "Julia Louis-Dreyfus": "Elaine Benes", "Jason Alexander": "George Costanza", "Michael Richards": "Cosmo Kramer" }
for key in cast: print(key)
for word in book_title: word_counter[word] = word_counter.get(word, 0) + 1
while break_num < end_num: break_num += count_by
python
print()
exit()
def cylinder_volume(height, radius=5): pi = 3.14159 return height * pi * radius ** 2
cylinder_volume(20) # by position cylinder_volume(20, 6) # by position cylinder_volume(radius=7, height=10) # by name
def population_density(population, land_area): """Calculate the population density of an area. INPUT: population: int. The population of that area land_area: int or float. This function is unit-agnostic, if you pass in values in terms of square km or square miles the function will return a density in those units. OUTPUT: population_density: population / land_area. The population density of a particular area. """ return population / land_area
def multiply(x, y): return x * y
multiply = lambda x, y: x * y
multiply(4, 7)
# auto closes the file after the indented block has been executed with open('my_path/my_file.txt', 'r') as f: # type is string parameter is the amount of chars to read file_data = f.read()
# auto closes the file after the indented block has been executed # file will be created if it doesn't exist with open('my_path/my_file.txt', 'r') as f: f.write("Hello there!")
.strip()
\n
with open('my_path/my_file.txt', 'r') as f: for line in f: print(line)
list(zip(['a', 'b', 'c'], [1, 2, 3])) [('a', 1), ('b', 2), ('c', 3)]
some_list = [('a', 1), ('b', 2), ('c', 3)] letters, nums = zip(*some_list)
virtualenv --python python3 env source env/bin/activate pip3 install -r requirements.txt python3 ./foo_bar.py deactivate
python3
letters = ['a', 'b', 'c', 'd', 'e'] for i, letter in enumerate(letters): print(i, letter)
0 a 1 b 2 c 3 d 4 e
name = input("Enter your name: ")
while True: try: x = int(input('Enter a number: ')) break except (ValueError, KeyboardInterrupt as e): print('Thats not a valid number!') except(BlahBlahError as e): # some code print("Exception occurred: {}".format(e)) finally: print('Attempted Input')