Python Beginners

Created
Tags

Elementary Stuff

print(2 ** 3) # this is 2^4

multi_line_string = """
Hello Whatsup
Yo bro chillin??
"""								

print("hello", end="") # next line not initiated


# Functions and parameters
def foo(title, row_count):
  print(title, end="")
  print(" "+ str(row_count))
	return 20, 'hello'
val, string_returned = create_spreadsheet("Alapan", 10)

Errors and Others

def divide_two_numbers(x, y):
  result = x / y
  return result

try:
  result = divide_two_numbers(2,0)
  print(result)
except NameError:
  print("A NameError occurred.")
except ValueError:
  print("A ValueError occurred.") 
except ZeroDivisionError:
  print("A ZeroDivisionError occurred.")

Conditions

def simple_conditional(x):
  if x == 0:
    print("x is equal to zero.")
  elif x > 0:
    print("x is greater than zero.")
  else:
    print("x is less than zero.")

simple_conditional(0)

Lists

heights = [['Jenny', 61], ['Alexus', 70], ['Sam', 67], ['Grace', 64], ['Vik', 68]]

names_and_heights = zip(names, heights)
print(list(names_and_heights))

new_orders = orders + ['lilac', 'rose']
new_orders.append('iris')
i = new_orders.pop()

list1 = range(1, 8, 2) # equivalent to [1, 3, 5, 7]
print(list(list1))

print(len(my_list))

sublist = letters[1:6]
num_i = letters.count('i')

names.sort()
sorted_names = sorted(names)

my_info = ('Alapan', 19, 5.0)
name, age, version = my_info

Loops

# jump statements
break
continue

# loops
for i in students:
	---------------

for i in range(0, 50, 3):
	---------------

while <condition>:
	---------------

# list comprehension
new_collection = [word for word in collection if word[-1] == 'z']
numbers = [i + 10 for i in values if i > 0]

nested_lists = [[4, 8], [16, 15], [23, 42]] # given
greater_than = [i > j for (i,j) in nested_lists]

quotients = [j/i for (i,j) in list(zip(a, b))]

Lambda

check_if_A_grade = lambda grade: 'Got an A!' if grade >= 90 else 'Did not get an A...'

random.randint(a,b) # will return an integer between a and b (inclusive)