<a href="https://colab.research.google.com/github/chemaar/python-programming-course/blob/master/Lab_4_Control_Flow_Loops.ipynb" target="_parent"></a>

# Lab 4: Control flow-Loops

In this notebook, we propose and solve some exercises about loops.

**As a good programming practice, our test cases should ensure that all branches of the code are executed at least once.**

## List of exercises



1. 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)


```

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


* Input: no input
* Expected output:

```
1
3
5
7
9
```


```
i = 1
while i < 11:
  print(i)
  i = i + 2
  

for i in range(1,11,2):
  print(i)
```

3. 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)
```

4. 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)


```

5. Write a program to calculate the exponentiation of a number with base b, and exponent n, both: while and for loops.
  * $base^{exponent} = a * a* a...*a$

* Input: base 2, exponent 3
* Expected output:

```
8
```


```
base = 2
exponent = 3
mipow = 1

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

print(mipow)
```

6. 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)
```

7. 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("")    
```

8. 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)
```

9. 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)
```

10. 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("")

```

    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	


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)) 
```

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


* Input: 11
* Expected output:

```
The sum between 11-100 is 4995.
```



```
top = 100
n = 11
add_top = 0
for value in range(11, top+1):
    add_top = add_top + value

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

    The sum between 11-100 is 4995


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))
```

    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


14. Write a program to show the Fibonnacci sequence of a given number n.

		fibonacci(n) = 
						fibonacci (0) = 0
						fibonacci (1) = 1
						fibonacci (n) = fibonacci(n-1) + fibonacci (n-2)


* Input: a positive number n
* Expected output:

```
0
1
1
2
3
```




```
numbersToGenerate=5
fn2 = 0
fn1 = 1
print(fn2)
print(fn1)
for i in range(2, numbersToGenerate):
  fcurrent = fn1 + fn2
  temp = fn1
  fn1 = fcurrent
  fn2 = temp
  print(fn1)
```

15. Write a program to check if an integer number is a palindrome.

* Input: 121
* Expected output:

```
The number 121 is palindrome: True
```




```
number = 121
palindrome = number
reverse = 0
while (palindrome != 0):
  remainder = palindrome % 10
  reverse = reverse * 10 + remainder
  palindrome = palindrome // 10
  

print("The number "+str(number)+" is palindrome: "+str((number==reverse)))
```

    The number 121 is palindrome: True


16. Write a program to check if an integer number of three digit is an Armstrong number.
   *  An Armstrong number of three digit is a number whose sum of cubes of its digit is equal to its number."

* Input: $153 = 1^3+5^3+3^3$ or $1+125+27=153$
* Expected output:

```
The number 153 is an Armstrong number.
```




```
number = 153
initial_number = number
result = 0
if number>=100 and number <= 999:
  while number != 0:
    remainder = number % 10
    result = result + remainder**3
    number = number // 10
  if result == initial_number:
    print("The number {} is an Armstrong number.".format(result))
  else:
    print("The number {} is NOT an Armstrong number.".format(result))
else:
  print("Number is not valid.")
```

17. Write a program to show the first N prime numbers.

* Input: N = 10
* Expected output:

```
The number 1 is prime.
The number 2 is prime.
The number 3 is prime.
The number 5 is prime.
The number 7 is prime.
The number 11 is prime.
The number 13 is prime.
The number 17 is prime.
The number 19 is prime.
The number 23 is prime.
```


```
counter = 0
MAX_PRIMES = 10
n = 1

while counter < MAX_PRIMES:
  n_divisors = 1
  divisor = 1
  #Loop if n is prime
  while divisor < n and n_divisors <= 2:
    if n % divisor == 0:
      n_divisors = n_divisors + 1
    divisor = divisor + 1
  #End loop if n is prime
  #Step second loop
  if n_divisors <= 2:
    print("The number {} is prime.".format(n)) 
    counter = counter + +1
  
  n = n + 1
```

18. Write a program to calculate the combinatorial number

$\binom{m}{n} = \frac{m!}{n! (m-n)!}$

* 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)))
```

19. 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):
  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("")
```

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


20. Write a program to print an * in the upper 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("")
```

21. 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("")
```

22. 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("")
```

23. 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("")
```

24. 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)


```

25. 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!")
```

26. Modify the program in 20 to give only 5 attempts.

* Input: target = 10
* Expected output:



```
Introduce a number: 6
The target value is greater than  6
Introduce a number: 7
The target value is greater than  7
Introduce a number: 12
The target value is less than  12
Introduce a number: 9
The target value is greater than  9
Introduce a number: 11
The target value is less than  11
You have consumed the max number of attempts.
```




```
target = 10
found = False
attempts = 0
MAX_ATTEMPTS = 5
while (not found and attempts < MAX_ATTEMPTS):
  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
  attempts = attempts + 1

if found:
  print("You have found out the target value!")
else:
  print("You have consumed the max number of attempts.")
```

27. Write a program to print the following pattern:



```
1
22
333
4444
55555
```




```
for i in range (1,6):
  print(str(i)*i)
```

28. 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
```


```
x = 54
y = 24
gcd = 1
#find x divisor
current_divisor = 1
if x != 0 and y != 0:
  if x > y:
    top = y
  else:
    top = x
  while (current_divisor < top):
    if (x % current_divisor == 0) and (y % current_divisor == 0):
      gcd = current_divisor
    current_divisor = current_divisor + 1

  print("The GCD of {} and {} is: {}".format(x,y,gcd))
else:
  print("The input must be different to 0.")
  
  
```

29. Write a program that counts the number of primer numbers between 1-MAX.

* Input: MAX = 100
* Expected output:


```
The number of primer numbers between 1 and 100 is 26.
```




```
MAX = 100
n_primes = 0
n = 1

while n < MAX:
  n_divisors = 1
  divisor = 1
  #Loop if n is prime
  while divisor < n and n_divisors <= 2:
    if n % divisor == 0:
      n_divisors = n_divisors + 1
    divisor = divisor + 1
  #End loop if n is prime
  #Step second loop
  if n_divisors <= 2:
    n_primes = n_primes + 1
  
  n = n + 1

print("The number of primer numbers between 1 and {} is {}.".format(MAX, n_primes)) 
```

    The number of primer numbers between 1 and 100 is 26.


30. Write a program that sums all primer numbers between 1-MAX.

* Input: MAX = 100
* Expected output:


```
The sum of all primer numbers between 1 and 100 is 1061.
```


```
MAX = 100
sum_primes = 0
n = 1

while n < MAX:
  n_divisors = 1
  divisor = 1
  #Loop if n is prime
  while divisor < n and n_divisors <= 2:
    if n % divisor == 0:
      n_divisors = n_divisors + 1
    divisor = divisor + 1
  #End loop if n is prime
  #Step second loop
  if n_divisors <= 2:
    sum_primes = sum_primes + n
  
  n = n + 1

print("The sum of all primer numbers between 1 and {} is {}.".format(MAX, sum_primes)) 
```

    The sum of all primer numbers between 1 and 100 is 1061.


31. Write a program to approximate the value of $e$ using the Taylor series for $e^x$.

$\begin{align}
   \sum_{n=0}^\infty \frac{x^n}{n!} &= \frac{x^0}{0!} + \frac{x^1}{1!} + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \frac{x^5}{5!}+ \cdots 
 \end{align}$

 * Input: x = 1, MAX (N) = 100
 * Expected output: 


```
The value of e is 2.7182818284590455
```




```
sum_e = 0
MAX = 100
x = 1
for n in range (1, MAX+1):
 factorial_n = 1
 for i in range(1,n):
   factorial_n = i * factorial_n
 sum_e = sum_e + (1/factorial_n)

print("The value of e is {}".format(sum_e))
```

32. Write a program to detect whether a number is a perfect number.

* A number is perfect if the addition of all positive divisors is equal to the number.

* Input: n = 6
* Expected output:


```
The number 6 is perfect.
```




```
n = 6
perfect = 0
for i in range (1,n):
  if n%i == 0:
    perfect = perfect + i

if perfect == n:
  print("The number {} is perfect.".format(n))
else:
  print("The number {} is NOT perfect.".format(n))
```

c467d4681754576e2140e865d31b4b6d09f9c534
ipynb
Jupyter Notebook
intro-programming/Lab_4_Control_Flow_Loops.ipynb
chemaar/python-programming-course
142be4008919874f61a8ed036dc0dca0025475f1
Apache-2.0
2020-03-26T08:18:14.000Z
2020-07-07T13:50:53.000Z
intro-programming/Lab_4_Control_Flow_Loops.ipynb
chemaar/python-programming-course
142be4008919874f61a8ed036dc0dca0025475f1
Apache-2.0
2021-05-11T18:31:53.000Z
2021-05-11T18:31:53.000Z
intro-programming/Lab_4_Control_Flow_Loops.ipynb
chemaar/python-programming-course
142be4008919874f61a8ed036dc0dca0025475f1
Apache-2.0
Qwen/Qwen-72B
1. YES
2. YES