Functions


In [1]:
# Creating a function that sums up 2 integers
def my_sum(a,b):
    c = a + b
    return c

In [2]:
my_var = my_sum(56,44)
print(my_var)


100

In [3]:
# Creating a function that checks whether a number is 0, odd, or even.
def checker(number):
    if number==0:
        print("None of them")
    elif number%2==0:
        print("Even")
    else:
        print("Odd")

In [4]:
number_type = checker(10)


Even

In [5]:
print(number_type)


None

In [6]:
my_num = my_sum(5,10)

In [7]:
print(my_num)


15

For loop


In [8]:
for i in range(5):
    print(i)


0
1
2
3
4

In [9]:
# Calculating the cube for each i
for i in range(5):
    print(i**3)


0
1
8
27
64

In [10]:
names = ["Jack","James","Jimmy"]

In [11]:
#Approach 1
for i in range(3):
    print(names[i])


Jack
James
Jimmy

In [12]:
# Approach 2
for i in names:
    print(i)


Jack
James
Jimmy

In [13]:
students = ["John","Dorothy","James","Julia"]

In [14]:
# Using for loop to pring only female students (using modulus oeprator)
for i in range(len(students)):
    if i%2==1:
        print(students[i])


Dorothy
Julia

While loop


In [15]:
# Solving same problem above with while loop

# Approach 1
i=0
while i<len(students):
    if i%2==0:
        print(students[i])
    i = i + 1


John
James

In [16]:
# Approach 2
i = 1
while i<len(students):
    print(students[i])
    i = i + 2


Dorothy
Julia

In [17]:
stocks = ["AAPL","MSFT","DIS"]

In [18]:
# Using (a short) while loop to pop out elements from a list until its empty
while len(stocks)>0:
    stocks.pop(-1)

In [19]:
print(stocks)


[]