Python Tutorial - 2  

4.Loops
4.1 For Loop
4.2 Range
4.3 While loop
4.4 Break loop
4.5 Nested loop
4.6 List Comprehension

5.Functions
5.1 Built-In Functions
5.2 Functions
5.3 Lambda Expressions
5.4 Map
5.5 Filter

4.Loops
A loop statement allows us to execute a statement or group of statements multiple times.

4.1 For Loop
# For loops are used for iterating over a sequence (a list, a tuple, a dictionary, a set, or a string).
# An action can be executed once for each item in a list, tuple of the for loop.
my_list = [1, 2, 3]
my_list
[1, 2, 3]
for i in my_list:
    print(i)
1 2 3
# you can do more than one task for every loop such as printing out 'Hello world'
for i in my_list:
    print(i)
    print('Hello World')
1
Hello World
2
Hello World
3
Hello World
# List of strings
my_list = ['AAPL', 'GOOG', 'T', 'TSLA', 'SP500']

for i in my_list:
    print(i)
AAPL
GOOG
T
TSLA
SP500
# you can loop over a string as follows
for i in 'TSLA':
    print(i)
T
S
L
A

Write a code that takes in a string and prints it out on the screen except for any letter 'T'. You can replace the letter 'T' with '*'.
for letter in 'TUSHAR':
  if letter == 'T':
    print('*')
  else:
   print(letter)
*
U
S
H
A
R
4.2 Range
# Range() generates a list of numbers, which is used to iterate over with for loops.
# range() is 0-index based, meaning list indexes start at 0, not 1. 
# The last integer generated by range() is up to, but not including, last element. 
# Example: range(0, 10) generates integers from 0 up to, but not including, 10.

for i in range(6):
    print(i)
0
1
2
3
4
5
# Range of numbers from 1 to 20 with steps of 2
for i in range(1, 20, 2):
print(i)
1
3
5
7
9
11
13
15
17
19
for i in reversed(range(5)):
print(i)
4
3
2
1
0

Write a code that takes in the maximum and minimum limits from the user and prints out even numbers only between the provided range
min = int(input("Enter the price (lower bound: "))
max = int(input("Enter the price (Upper bound: "))

for i in range(min, max):
    if i%2 == 0: 
        print(i)
Enter the price (lower bound: 2
Enter the price (Upper bound: 6
2
4

Write a code that generates the following table:
1   1    1
2   4    8
3   9   27
4  16   64
5  25  125
6  36  216
7  49  343
8  64  512
9  81  729
10 100 1000
for x in range(1, 11):
print('{} {} {}'.format(x, x*x, x*x*x))
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

4.3 While Loop
# While loop can be used to execute a set of statements as long as a certain condition holds true.
i = 0
while i &lt= 15:
    print(i)
    i = i + 1 
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Write a code that displays numbers from 1 to 30 (including 30) using for and while loops
i = 1
while (i &lt 10):
  print (i)
  i = i+1
1
2
3
4
5
6
7
8
9
for i in range(1, 6):
    print(i)
1
2
3
4
5

Create a rolling dice game that assume we have two dice (#1 and #2). The dice is being thrown and a random number is generated everytime. The game should be designed such that it prompts the user to ask if he/she would like to keep playing or exit the game.
import random

keep_rolling = "y"

while keep_rolling == "y":
    print("Rolling the dices, please wait!...")
    print("Rolling results for Dice #1:", random.randint(1, 6))
    print("Rolling results for Dice #2:", random.randint(1, 6))

    keep_rolling = input("Do you want to roll again?")
Rolling the dices, please wait!...
Rolling results for Dice #1: 2
Rolling results for Dice #2: 3
Do you want to roll again?y
Rolling the dices, please wait!...
Rolling results for Dice #1: 3
Rolling results for Dice #2: 3
Do you want to roll again?n

4.4 Break a Loop
# break() is used to exit a for loop or a while loop
# continue() is used to skip the current block, and return to the "for" or "while" statement.
my_list = ["GOOG", "AAPL", "T", "TSLA", "SP500"]
my_list
['GOOG', 'AAPL', 'T', 'TSLA', 'SP500']
# print out all elements in the list
for i in my_list:
    print(i)
GOOG
AAPL
T
TSLA
SP500
# print out all elements in the list up until the AT and T stock (Ticker Symbol = T) is detected
for i in my_list:
    print(i)
    if i == 'T':
        break 
GOOG
AAPL
T
# Print only odd elements and skip even numbers
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in my_list:
    if i%2 == 0:
        continue
    print(i)
1
3
5
7
9

Write a code that continiously gets data from the user and calculates the average and print out on the screen. The code exits when the user enters 'e'.
print("Keep entering numbers and 
I will display the average to you!")
avg = 0
n = 0
while True:
    x = input("Enter a number: ")
    
    # Check if the user wants to exit (i.e.: break the loop)
    if x == 'e':
      break
    
    x = int(x)
    n = n + 1
    
    avg =   ((avg * (n - 1) ) + x) / n
    print ("The current average is ", avg)

Keep entering numbers and
I will display the average to you!
Enter a number: 2
The current average is 2.0
Enter a number: 3
The current average is 2.5
Enter a number: e

4.5 Nested Loop
# Nested loops are loops that exist inside the body of another loop
for x in range(1, 3): # slow loop 
    for y in range(1, 11):   # fast loop
        print('{} * {} = {}'.format(x, y, x*y))
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
color_list = ['black', 'white', 'gold']
phone_list = ['iphone', 'samsung', 'blackberry']
for i in color_list:
    for j in phone_list:
        print(i, j)
black iphone
black samsung
black blackberry
white iphone
white samsung
white blackberry
gold iphone
gold samsung
gold blackberry

Write a code that takes in a number (range between 1 and 9) from the user and print out the multiplication table up until that number.
number = int(input("Enter a number between 1 and 9: "))

for x in range(1, number+1): # slow loop 
  for y in range(1, 11):   # fast loop
   print('{} x {} = {}'.format(x, y, x*y))
black iphone
Enter a number between 1 and 9: 1
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10

4.6 List Comprehension
# List comprehension is an elegant tool to transform one list into another list. 
# Instead of using loops and append, list comprehension is used to iterate over a list, condition its elements and include them in a new list.
# Let's take a look at the traditional way of taking a list and squaring its elements
input_list = [1, 2, 3, 4]
output_list = []

for element in input_list:
    output_list.append(element **2)

print(output_list)
[1, 4, 9, 16]
# List comprehension is a super powerful one line of code!
[ element ** 2  for element in input_list]
[1, 4, 9, 16]
# Let's square even numbers only 
# We need to insert a condition 
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
output_list = []
for i in input_list:
    if i % 2==0:
        output_list.append(i**2)
print(output_list)
[4, 16, 36, 64, 100]
# All this could be done with one line of code as well using List Comprehension 
output_list = [i**2  for i in input_list if i%2 == 0  ]
output_list
[4, 16, 36, 64, 100]
# All this could be done with one line of code as well using List Comprehension 
output_list = [i**2  for i in input_list if i%2 == 0  ]
output_list
[4, 16, 36, 64, 100]

Write a code that takes in a list of prices of a stock for the past 7 days and then normalize the prices
print('Enter a list of past 7-days prices separated by a space:')
prices = [int(x) for x in input().split()]
Enter a list of past 7-days prices separated by a space:
70 50 80 70 80 30 20
normalized_prices = [ (i/prices[0]) for i in prices]
print('Orginal Prices: {}\nNormalized Prices: {}\n'.format(prices, normalized_prices))
Orginal Prices: [70, 50, 80, 70, 80, 30, 20]
Normalized Prices: [1.0, 0.7142857142857143, 1.1428571428571428, 1.0, 1.1428571428571428, 0.42857142857142855, 0.2857142857142857]


5. FUNCTIONS

A function is a block of code which only runs when it is called.

5.1 Built-In Functions

# There are many built-in functions that you can leverage directly 
# Let's define 2 lists x and y
x = [4, 5, 1, 2, 8, 5]
y = list(range(1, 7))

x
[4, 5, 1, 2, 8, 5]
y
[1, 2, 3, 4, 5, 6]
# Let's obtain the length of y
len(y)
6
# Let's obtain the minimum value
min(x)
1
# Let's obtain the maximum value
max(x)
8
# Let's create a tuple out of the list
z = tuple(x)

z
(4, 5, 1, 2, 8, 5)
type(z)
tuple
# Let's obtain the sum of elements in x
print(sum(x))
25

Write a code that takes in 2 lists x = [-1 -4 -7] and y = [-3 7 4] and calculates the absolute sum of all its elements |x+y|
x = [-1, -4, -7]
y = [-3, 7, 4]
z = abs(sum(x+y))
z
4

5.2 Functions
# Let's define a function named "my_function" that does not receive any arguments
# The function simply prints out content and does not return anything
def my_function():
    print('Welcome to Python course!')

# Function call
my_function()
Welcome to Python course!
# Define a function that takes in argument x and return the squared value 
def squared(x):
    return x ** 2

# Call the function
output = squared(4)
output
16
# Define a function with default value 
def my_function(amount = 20000):
    print("My total amount is = {}".format(amount))

# If you pass an argument to the function, it overwrites the default value  
my_function(600000)
My total amount is = 600000
# If you don't pass an argument, the default value "20000" will be used instead
my_function()
My total amount is = 20000

Write a code that takes in two inputs (number of units and prices) from the user and calculate the total account balance

def total(units, price):
    amount = units * price
    return(amount)

num_unit = int(input("Enter the number of unit: "))
price = int(input("Enter the price per unit: "))
account_balance = total(num_unit, price)

print('Total account balance = {}'.format(account_balance))
Enter the number of unit: 5
Enter the price per unit: 50
Total account balance = 250

5.3 LAMBDA EXPRESSIONS
# Lambda function is used to create a function without a name 
# Lambda functions are mainly used with filter() and map() [they will be discussed later on]. 
# Lambda function can receive any number of arguments, but can only have one expression.

# let's see how to create a basic function that squares the input
def my_function(x):
    return x**2

# Function callmy_function(3)
9
# We can do the same task using Lambda expression
# Note that there is no function name
y = lambda x:x**2


y(3)

# Note that lambda expression can take in more than one argument 
# there is only one expression that could be performed
def summation(x, y, z):
    return x+y+z
9
result = summation(1, 2, 3)
result
6
result = lambda    x, y, z : x+y+z 


result(1, 2, 3)
6

Write a code that takes in two inputs from the user and calculates the total using lambda expressions instead
num_unit = int(input("Enter the number of unit: "))
price = int(input("Enter the price per unit: "))

account_balance = lambda num_unit, price : num_unit * price
print('Total = {}'.format(account_balance(num_unit, price)))
Enter the number of unit: 5
Enter the price per unit: 50
Total = 250

4. MAP
# The map() function takes in a function and a list.
# map() performs an operation on the entire list and return the results in a new list.
# Define two lists a and b
a = [1, 4, 5, 6, 9]
b = [1, 7, 9, 12, 7]

# Let's define a function that adds two elements together
def summation(a, b):
    return a + b

# You can now use map() to apply a function to the entire list and generate a new list
c = list(map(summation, a, b))
c
[2, 11, 14, 18, 16]
# map could be used with Lambda as follows
# lambda function is an anonymous function that take any number of arguments and can only have one expression
input_list = [1, 2, 3, 4]

out_list = list(map ( lambda x:x**2 , input_list))
out_list
[1, 4, 9, 16]

MINI CHALLENGE #4 SOLUTION: Write a function that takes an argument and return its cubic value Define a list of integers ranging from -10 to 10 Apply the function to the entire list and generate a new output list
def cubic(x):
    return (x*x*x)

numbers = range(-10, 11)
numbers_cubed = list(map(lambda x: cubic(x), numbers))
print(list(numbers))
print(numbers_cubed)
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[-1000, -729, -512, -343, -216, -125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

5.5 FILTER
# filter is used to create a list of elements for which a function returns "True".
prices = [105, 5055, 40, 356, 923, 1443, 222, 62]

# return only even numbers
out = list(filter( lambda x: (x % 2 == 0) , prices  ))
out
[40, 356, 222, 62]
# Return prices that are greater than or equal 100
prices = [105, 5055, 40, 356, 923, 1443, 222, 62]
out = list(  filter(lambda x: (x>=100) , prices) )
out
[105, 5055, 356, 923, 1443, 222]
# Return values between 200 and 250
out = list(  filter(lambda x: (x>=200 and x<=250) , prices) )
out
[105, 5055, 356, 923, 1443, 222]
# Return values between 200 and 250
out = list(  filter(lambda x: (x>=200 and x<=250) , prices) )
out
[222]

Write a code from the user that takes in a range (upper and lower bounds) and returns a list of positive and even numbers only
min = int(input("Enter a number (lower bound) *must be negative* : "))
max = int(input("Enter a number (Upper bound:) "))

numbers = range(min, max)
even_greater_than_zero = list(filter(lambda x: (x > 0 and x%2 == 0), numbers))
print(even_greater_than_zero)
Enter a number (lower bound) *must be negative* : 1
Enter a number (Upper bound:) 5
[2, 4]