Skip to content

Instantly share code, notes, and snippets.

View adrianmarkperea's full-sized avatar

Adrian Perea adrianmarkperea

View GitHub Profile
def sum_all(*args):
result = 0
# args is a list
for arg in args:
result += arg
return result
result = sum_all(1, 2, 3, 4, 5)
print(result) # => 15
# The basic syntax is as follows:
# new_list = [<expression> <for loop(s)> <conditions>]
my_list = [1, 2, 3, 4, 5]
doubled = [x*2 for x in my_list] # no conditions in this case
print(doubled) # => [2, 4, 6, 8, 10]
# Equivalent to the following for loop:
doubled = []
my_list = [1, 2, 5, 6, 9, 21, 30]
odds = [x for x in my_list if x % 2 == 1]
print(odds) # => [1, 5, 9, 21]
# Equivalent to the following for loop:
odds = []
for x in my_list:
if x % 2 == 1:
odds.append(x)
x, y = y, x
print(x) # => 16
print(y) # => 1
a = 3.14
foo(b, c):
return (4/3) * a * b^2 * c
# value of pi
a = 3.14
# calculate the volume of a cylinder
# b -- radius
# c -- height
foo(b, c):
return (4/3) * a * b^2 * c
pi = 3.14
calculate_cylinder_volume(radius, height):
return (4/3) * pi * radius^2 * height
a = 1 # namespace {a: 1}
# does `a` exist in the namespace? Yes!
# proceed without error
print(a) # => 1
# does `b` exist in the namespace? No.
# Throw a `NameError`
print(b) # => NameError: name `b` is not defined.
# scopes.py
# Scope A
a = 1
b = 16
def outer():
# Scope B
c = 24
d = 'Hello, World!'
i_am_global = 5
def foo():
i_am_global = 10
print(i_am_global)
foo()
print(i_am_global)
# outputs