Python Programming

Class 2

Author: Jose Miguel Arrieta R.

if/else

The if/else statement executes a block of code if a specified condition is true. If condition is not met, another block of code can be executed.

var = 10

if (var >= 5): 
    print('var mayor o igual que 5')
elif (var < 0):
    print('var es negativo')
elif (var == 0): 
    print('var es cero')
else: 
    print('var es menor que 5')

For loops

Loops through a block of code a number of times

* See others examples

# One parameter
for i in range(10):
    print(i)

While loops

Loops through a block of code while a specified condition is met


var = 10

while(var <= 20):
	print('var es menor o igual a 20')
	var+=2

Functions

A function is a block of code designed to perform a particular task.

Note: save and import

def suma_dos_numeros(a,b):
    suma = a+b 
    return suma


suma_dos_numeros(4,4)

Exercise 1 [easy]

  • Using function suma_dos_numeros, create a function suma_tres_numeros that sums three input numbers and returns the result.
#TestCase
suma_tres_numeros(2,4,12)
18
  • Answer 1 

from funcion import suma_dos_numeros

def suma_tres_numeros(a,b,c): 
    d = suma_dos_numeros(a,b)
    suma_total = suma_dos_numeros(d,c)
    return suma_total

suma_tres_numeros(2,4,12)

#Note: Optional reduce to 2 number of lines

"""
def suma_tres_numeros(a,b,c): 
    return suma_dos_numeros(suma_dos_numeros(a,b),c)
"""
  • Exercise 2 Fizbuzz 

  • Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”
  • Answer 2 

for i in range(0,100):
    if (i%3 ==0 and i%5 ==0): 
        print("FizzBuzz")
    elif i%3 ==0:
        print("Fizz")
    elif i%5 ==0:
        print("Buzz")
    else:
        print(i)
  • Exercise 3 

Remember:

  • A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
  • Create a function that determine if positive integer number is a prime number or not.
  • #TestCases
#Test cases 

>>> is_prime(5)
'Primo'

>>> is_prime(4)
'No es primo'

>>> is_prime(7)
'Primo'

>>> is_prime(10)
'No es primo'

>>> is_prime(147)
'No es primo'

>>> is_prime(149)
'Primo'
  • Answer 3 

def is_prime(n):
    for i in range(2,n):
        if n%i==0:
            return 'No es primo'
    return 'Primo'
Made with Slides.com