Functions and Conditions (if statements)#

Last recitation:#

  • Variables

  • Assignments

  • Types

Agenda#

Functions

if-else statements

  • if-else
  • elif
  • nested if

Functions#

Definition: functions are “self-contained” modules of code that accomplish a specific task#

Define a new function#

Function syntax#

def name(param1, param2, ...):  
    ''' documentation''' #Optional documentation   
    # your code here...
    return ...

Exercise 1#

Write code that receives the length of the two legs of a right triangle, a and b.#

  • Calculate the length of the hypotenuse, c

  • Calculate the triangle’s area

  • Calculate the triangle’s circumference

  • Print all three values

alt_text

## "Input" values
a=3
b=7

c=(a**2 + b**2)**0.5
area=(a*b)/2
circum=a+b+c
print(c,area,circum)
7.615773105863909 10.5 17.61577310586391

Now with function…#

Define the pythagoras function#

def pythagoras(a, b):  
    .
    .
    .
    return ...
def pythagoras(a, b):
    c = (a**2 + b**2)**0.5
    area=(a*b)/2
    circum=a+b+c
    return c,area,circum
hypo1 = pythagoras(1,3)
hypo2 = pythagoras(3,7)
hypo3 = pythagoras(1,7)

print(hypo1)
print(hypo2)
print(hypo3)
(3.1622776601683795, 1.5, 7.16227766016838)
(7.615773105863909, 10.5, 17.61577310586391)
(7.0710678118654755, 3.5, 15.071067811865476)

Conditional statements if#

alt_text alt_text

Each block contains:

  • exactly 1 if

  • 0 or more elif

  • 0 or 1 else

  • Note how each of if and else has its own indented statements under its own block.

Example #1: if vs elif#

# "Input" values 
rick_chips = 137
morty_chips = 731

if rick_chips > morty_chips:
    print("Rick won")
elif morty_chips > rick_chips:
    print("Morty won")
else:
    print("It's a tie!")
    
print("end")
Morty won
end
# "Input" values 
rick_chips = 137
morty_chips = 731

if rick_chips > morty_chips:
    print("Rick won")
if morty_chips > rick_chips:
    print("Morty won")
else:
    print("It's a tie!")
    
print("end")
Morty won
end

Example #2: nested if#

Write a function that returns whether a number is “positive even”, “positive odd”, “negative even”, “negative odd” or “zero”#

# "Input" values 

def categorize_number(n):
    if n > 0:
        if n%2 == 0:
            return "positive even"
        else:
            return "positive odd"
    elif n < 0:
        if n%2 == 0:
            return "negative even"
        else:
            return "negative odd"
    else:
        return "zero"
categorize_number(138)
categorize_number(-57)
categorize_number(0)
'zero'

Self learning#

Reminder: Exercise 1#

  • Return the number resulting from reversing the digit of a given four-digit number

  • No str functions

Example: 1370 –> 731 (0731)

num=1370

num1=(num%10)*1000 
num2=(num%100//10)*100 
num3=(num%1000//100)*10 
num4=((num)//1000)*1

print(num1,num2,num3,num4)
print(num1+num2+num3+num4)
0 700 30 1
731

Now with functions…#

def reverse_digits(num):
    num1=num%10*1000 
    num2=num//1000 
    num3=num%100//10*100 
    num4=num%1000//100*10 
    return num1+num2+num3+num4
print(reverse_digits(1370))
print(reverse_digits(1375))
731
5731

Reminder: Exercise 2#

Write a code that receives a string s with only lower letters, and prints a similar string, but with the middle letter in an upper case format.#

e.g.,
efghi \(\rightarrow\) efGhi
efghij \(\rightarrow\) efgHij

Putting in all together in a function#

 def cap_in_middle(s):
    n = len(s)
    middle = n // 2
    middle_letter = s[middle]
    U_middle_letter = middle_letter.upper()
    return s[0:middle] + U_middle_letter + s[middle+1:]
    
print(cap_in_middle('limerick'))
print(cap_in_middle('rickandmorty'))
limeRick
rickanDmorty