0% found this document useful (0 votes)
15 views

LAB #3 - Solved - Exercises

Ejercicios Python control resueltos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

LAB #3 - Solved - Exercises

Ejercicios Python control resueltos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab 3: Control flow-Conditional Statements

Coding CONDITIONALS
1. Write a program that given the 3 angles of triangles, checks whether is valid (the sum must be 180).

Input: 45, 45, 90

Expected output:

The triangle: 45, 45, 90 is valid.

a1 = int(input("Introduce the first angle: "))


a2 = int(input("Introduce the second angle: "))
a3 = int(input("Introduce the second angle: "))

if (a1+a2+a3 == 180):
print("The triangle: {}, {}, {} is valid.".format(a1,a2,a3))
else:
print("The triangle is not valid.")

2. Write a function check_even() that given an integer, returns "odd" or "even" depending on whether it is an odd or even
number. Use print() in a line to print the function output. Write the condition as a conditional expression. ("ternary
operator").

Input: 4
Expected output:

The number is even

def check_even(n):
is_even = "even" if (n%2==0) else "odd"
return is_even

print("The number is", check_even(4))

3. Write a program that given a quantitative grade, prints out the qualitative value.

A if input in [9-10]

B if input in [7-9)

C if input in [5-7)

D if input < 5
Input: 7.5 (test limit values like 7, 5, 9, 10 as an input)

Expected output:

Your grade is B.
a = float(input("Introduce your grade as a number: "))
grade = ""
if a < 5:
grade = "D"
elif a < 7:
grade = "C"
elif a < 9:
grade = "B"
else:
grade = "A"

print("Your grade is {}.".format(grade))

Coding CONTROL FLOW


4. Write a program that prints out the numbers from 0 to 10 (only even numbers). Use both: while and for loops.

Input: no input

Expected output:

0
2
4
6
8
10

i = 0
while i <= 10:
print(i)
i = i + 2

for i in range(0,12,2):
print(i)

5. Given an integer number, n, print a wedge of stars as follows.

Input: 5
Expected output:

*
**
***
****
*****

n_stars = 5
for i in range (0, n_stars+1, 1):
print("*"*i)

C4. Given an integer number, n, print a wedge of stars as follows.

Input: 5
Expected output:
*
**
***
****
*****

n_stars = 3
for i in range (0, n_stars+1, 1): # option 1
print( "* "*i)

for i in range(n_stars): # option 2


print((i+1)*"* ")

*
* *
* * *
*
* *
* * *

LAB 3 - Exercises
1. Write a program that given an integer numbers, prints out if it is divisible by 5 and 11.

Input: 55
Expected output:

The number 55 is divisible by 5 and 11.

value = int(input())
if value % 5 == 0 and value % 11 == 0:
print ("The number {} is divisible by 5 and 11.".format(value))

2. Write a program to check that a character is a letter in uppercase. Make use of these functions:
value.isupper() -->Returns True if the value is in uppercase.

value.isalpha() -->Returns True if the value is a letter.

Input: A

Expected output:

The character A is in uppercase.

value = input()
is_upper = len(value) == 1 and value.isupper() and value.isalpha()
if is_upper:
print("The character {} is in uppercase.".format(value))
else:
print("It is not.")

3. Write a program that given a month name, prints the number of days (if the name is not correct, it shall print out some error
message). Remember: April, June, September, November have 30 days.

Input: January
Expected output:

January has 31 days.

5. Write a program that prints out the numbers from 10 to 0 (only odd numbers). Use both: while and for loops.
Input: no input

Expected output:

9
7
5
3
1

i = 9
while i >= 0:
print(i)
i = i - 2

for i in range(9,0,-2):
print(i)

6. Write a program to calculate the factorial of an integer number. Use both: while and for loops.
factorial (n) = n * factorial (n-1)

Input: an integer number, 5


Expected output:

120

number = 5
fact = 1

if number < 0:
fact = -1
elif number == 0 or number == 1:
fact = 1
else:
for i in range(1,number+1):
fact *= i

print(fact)

7. Write a program to calculate the exponentiation of a number with base b, and exponent n, both: while and for loops.

Input: base 2, exponent 3

Expected output:

base = 2
exponent = 3
mipow = 1

if exponent > 0:
for i in range(0,exponent):
mipow *= base

print(mipow)

8. Given an integer number, n, make the sum of all the numbers from 0 to n.

Input: 5
Expected output:

15

n = 5
add_n = 0
for i in range(0,n+1,1):
add_n += i

print(add_n)

9. Given an integer number, n, print a cross of radius n as follows.

Input: 9
Expected output:

* . . . . . . . *
. * . . . . . * .
. . * . . . * . .
. . . * . * . . .
. . . . * . . . .
. . . * . * . . .
. . * . . . * . .
. * . . . . . * .
* . . . . . . . *

n = 9
for i in range(0, n, 1):
for j in range (0, n, 1):
if (i==j or n-i-1 == j):
print(" *", end="")
else:
print(" .", end="")
print("")

10. Given an integer number, n, print a wedge of stars as follows.

Input: 5
Expected output:

*****
****
***
**
*

n_stars = 5
for i in range (n_stars, 0, -1):
for j in range (0, i, 1):
print("*", end="")
print("")

#Pythonic
for i in range (n_stars, 0, -1):
print("*"*i)

11. Make a program to display the multiplication table (1-10).

Input: no input
Expected output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

for i in range(1,11,1):
for j in range (1, 11, 1):
print(i*j, end = "")
print("\t", end = "")
print("")

12. Write a program to sum all odd numbers between n and 100 (included).

Input: 11
Expected output:

The sum between 11-100 is 2475

top = 100
bottom = 11
add_top = 0
for value in range(bottom, top+1):
if(value % 2 != 0):
add_top = add_top + value

print("The sum between {}-{} is {}".format(bottom,top,add_top))

The sum between 11-100 is 2475

13. Write a program to show the square of the first 10 numbers.

Input: no input
Expected output:

The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100

for i in range(0, 11):


print("The square of {} is {}".format(i,i**2))

14. Write a program to calculate the combinatorial number

Input: m = 10, n = 5
Expected output:

252

m = 10
n = 5
factorialmn = 1
factorialn = 1
factorialm = 1

if (m < n):
print("M must be >= n");
else:
#Factorial m
if m == 0 or m == 1:
factorialm = 1
else:
i = m
while i > 0:
factorialm = i * factorialm
i = i - 1
#Factorial n
if n == 0 or n == 1:
factorialn = 1
else:
i = n
while i>0 :
factorialn = i * factorialn
i = i - 1
#Factorial m-n
if (m - n == 0 or m - n == 1):
factorialmn = 1
else:
i = m - n
while i>0 :
factorialmn = i * factorialmn
i = i - 1
print("The result is: ",(factorialm / (factorialn * factorialmn)))

17. Write a program to print an * in the lower diagonal of an implicit matrix of size n.

Input: n = 3
Expected output:

* . .
* * .
* * *

n = 3
for i in range(1,n+1):
for j in range (1,n+1):
if (i >= j):
print("*", end = "")
else:
print(".", end = "")
print("")

18. Write a program to print a diamond of radius n.

Input: n = 7
Expected output:
. . . * . . .
. . * * * . .
. * * * * * .
* * * * * * *
. * * * * * .
. . * * * . .
. . . * . . .

n = 7
mid = n//2
lmin=0
rmax=0
if (n % 2 != 0):
for i in range(0,n):
if i <= mid:
lmin=mid-i
rmax=mid+i
else:
lmin=mid-(n-i)+1
rmax=mid+(n-i)-1
for j in range (0,n):
if j>=lmin and j<=rmax:
print(" *", end = "")
else:
print(" .", end = "")
print("")

19. Write a program that displays a table of size (n x n) in which each cell will have * if i is a divisor of j or "" otherwise.

Input: n = 10
Expected output:

* * * * * * * * * * 1
* * * * * * 2
* * * * 3
* * * * 4
* * * 5
* * * * 6
* * 7
* * * * 8
* * * 9
* * * * 10

N = 10
for i in range (1, N+1):
for j in range (1, N+1):
if (i%j == 0 or j%i == 0):
print(" *", end = "")
else:
print(" ", end = "")
print(" ",i)
print("")

20. Write a program to display a menu with 3 options (to say hello in English, Spanish and French) and to finish, the user shall
introduce the keyword "quit". If any other option is introduced, the program shall display that the input value is not a valid
option.

Input: test the options


Expected output:
----------MENU OPTIONS----------
1-Say Hello!
2-Say ¡Hola!
3-Say Salut!
> introduce an option or quit to exit...

option = "1"
while option != "quit":
print("----------MENU OPTIONS----------")
print("1-Say Hello!")
print("2-Say ¡Hola!")
print("3-Say Salut!")
option = input("> introduce an option or quit to exit...")
if option == "1":
print("Hello!")
elif option == "2":
print("¡Hola!")
elif option == "3":
print("Salut!")
elif option == "quit":
print("...finishing...")
else:
print("Not a valid option: ", option)

21. The number finder: write a program that asks the user to find out a target number. If the input value is less than the target
number, the program shall say "the target value is less than X", otherwise, the program shall say "the target value is greater
than X. The program shall finish once the user finds out the target number.

Input: target = 10
Expected output:

Introduce a number: 3
The target value is greater than 3
Introduce a number: 5
The target value is greater than 5
Introduce a number: 12
The target value is less than 12
Introduce a number: 10

target = 10
found = False
while (not found):
value = int(input("Introduce a number: "))
if target < value:
print("The target value is less than ", value)
elif target > value:
print("The target value is greater than ", value)
else:
found = True

if found:
print("You have found out the target value!")

Homework
4. Write a program that given the 3 integer numbers, it prints out the sorted values (in descending order) using conditional
statements..

Input: 3, 5, 2
Expected output:
5, 3, 2

a = 3
b = 5
c = 2

if a > b:
if a > c:
if b > c:
print("{} {} {}".format(a,b,c))
else:
print("{} {} {}".format(a,c,b))
else:
print("{} {} {}".format(c,a,b))
else:
if b > c:
if c > a:
print("{} {} {}".format(b,c,a))
else:
print("{} {} {}".format(b,a,c))
else:
print("{} {} {}".format(c,b,a))

15. Write a program to print a Christmas tree of 15 base stars.

Input: base_stars = 15
Expected output:

*
***
*****
*******
*********
***********
*************
***
***
***

base_stars = 15
half_blank_spaces = 0;
for i in range(1,base_stars, 2):
half_blank_spaces = (base_stars-i) // 2
for j in range(0, half_blank_spaces):
print(" ",end="")
for k in range(0, i):
print("*",end="")
for j in range(0, half_blank_spaces):
print(" ",end="")
print("")

half_blank_spaces = (base_stars//2)-1;
for i in range(3): # tree trunk
for j in range(0,half_blank_spaces):
print(" ",end="")
for k in range(0, 3):
print("*",end="")
for j in range(0, half_blank_spaces):
print(" ",end="")
print("")

11. Write a program to detect if a number is a prime number.


Input: 5, 8
Expected output:

The number 5 is prime.


The number 8 is not prime.

n = 1
n_divisors = 1
divisor = 2
while divisor < n and n_divisors <= 2:
if n % divisor == 0:
n_divisors = n_divisors + 1
divisor = divisor + 1

if n_divisors > 2:
print("The number {} is not prime.".format(n))
else:
print("The number {} is prime.".format(n))

22. Write a program to find greatest common divisor (GCD) of two numbers.

Input: x = 54, y = 24
Expected output:
Tip: try to improve the algorithm following the strategies here: https://en.wikipedia.org/wiki/Greatest_common_divisor

The GCD of 54 and 24 is: 6

#Python version in the math library


def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.

Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a

You might also like