# Day 5: For Loops, Range & Code Blocks

## Loops

The 1st type of loop is called the **"For Loop"** which means \
\&#xNAN;**`for item in list_of_items`**\
&#x20;   **`#Do something to each item`**

If we have a list called "fruits" and inside the list we have \["Apple", "Peach", "Pear"] and we want to access **each item in the list individually** and print **each one out one by one**, them we use the '**for loop'**

![](/files/-MMX4H7Lc3YwvlL5eYvM)

![](/files/-MMX6FFoGEByuO76oeiv)

![](/files/-MMX8MjkMr7P6Ry5p26C)

![](/files/-MMX6kLylQr-OTf7CjrT)

## EXERCISE 1 - Average Height

![](/files/-MM_LM8bytL_LnwtkQ7p)

![](/files/-MM_PdyvMQeGNYEtaIaS)

![](/files/-MM_aEmRdAmnfECuM_-X)

{% tabs %}
{% tab title="Code" %}

```
# 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
#print(student_heights)
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])
print(student_heights)

# 🚨 Don't change the code above
total_height = 0
for height in student_heights:
  total_height += height
print(total_height)

number_of_students = 0
for students in student_heights:
  number_of_students += 1
print(number_of_students)

av = total_height/number_of_students
print(round(av))
```

{% endtab %}
{% endtabs %}

![I did this without using Angela's predefined "don't change the code below" - better practice for me:)](/files/-M_MtUZKpKpfPy_jr7mA)

![](/files/-M_Mu6UvHAml2FaQQ2kG)

## EXERCISE 2 - Highest Score

![](/files/-MM_cQnfZ_zqrn6HrjLl)

### Hint

1. Think about the logic before writing code. How can you compare numbers against each other to see which one is larger?

### Solution

Break down the code into steps:

* Input student scores **`78 65 89 86 55 91 64 89`**( this will end up as strings) eg&#x20;
* Convert the list of strings into a list of integers using the "for loop"

![](/files/-MM_rlV2dYsajqAC-Dhu)

```
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
  student_scores[n] = int(student_scores[n])
print(student_scores)

highest_score = 0
for score in student_scores:
  if score > highest_score:
    highest_score = score
print(f"The highest score in the class is: {highest_score}")

```

![](/files/-M_Pxpr0yATze_axYtjx)

My new update - Angela uses her own ("don't change the code") I wanted to do the whole thing from my perspective - this is the first time that I have had to use a new function to change strings into integers in a list :) It works so that's cool :)

![](/files/-M_UtvivvUol3PK8IvYp)

## For Loop and range(function)

We have been using the for loop in association with lists, ie looping through the lists and getting hold of each item within the list and then doing something with it.\
However sometimes we might want to use a "for loop" completely independent of a list\
For example if we wanted to add all the numbers from 1-100 we use the **"range" command** however if we issued a print command this would print out all the numbers from 1-99. So we have to **ADD an extra 1 to the end. So  in this case the range(1, 101)**\
If we wanted to have it add in steps of say 3 for a range(1, 11, 3) we would add the step in a the end

The syntax is this

![](/files/-MMa8Qc4vzCR_XBxYKvk)

![](/files/-MMa8oA6RoIyMyFYkF0U)

![](/files/-MMa9B9hy7OOG6Ktwx8S)

Going back to us wanting to add up all the numbers from 1-100

![](/files/-MMaEmwnUvtRHlPIvKNS)

### Exercise: Adding Even Numbers&#x20;

#### Instructions

You are going to write a program that calculates the sum of all the even numbers from 1 to 100, including 1 and 100.

e.g. 2 + 4 + 6 + 8 +10 ... + 98 + 100

Important, there should only be 1 print statement in your console output. It should just print the final total and not every step of the calculation.

![](/files/-MMaIZhytnlFSt9cLkug)

![](/files/-M_V2oP8CJfSjKA9iU7j)

### Exercise: FizzBuzz

![](/files/-MMac15r-MS-5cF7fnyl)

![](/files/-MMb2yoo_tJUp4Fqomqm)

{% tabs %}
{% tab title="Code" %}

```
for number in range (1, 101):
  if number % 3 == 0 and number % 5 == 0:
    print("FizzBuzz")
  
  elif number % 3 == 0:
    print("Fizz")
    
  elif number % 5 == 0:
    print("Buzz")

  else:
    print(number)

```

{% endtab %}
{% endtabs %}

### Project of the Day - Password Generator

![](/files/-MMb4cKguQIBfGYExbnN)

![](/files/-MMfNRgL3IIASftU99nf)

{% tabs %}
{% tab title="My Effort" %}

```

#Password Generator Project
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n")) 
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

#Eazy Level - Order not randomised:
#e.g. 4 letter, 2 symbol, 2 number = JduE&!91


#Hard Level - Order of characters randomised:
#e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P

#random.shuffle(letters)
#random.shuffle(numbers) ----------all just shuffles the list around so a print(letters) will show all shuffled from original
#random.shuffle(symbols)

count=(nr_letters + nr_symbols + nr_numbers)

ran_let = random.sample(letters, nr_letters)
ran_num = random.sample(numbers, nr_numbers)
ran_sym = random.sample(symbols, nr_symbols)

user_choice = ran_let + ran_num + ran_sym
ran_user_choice = random.sample(user_choice, count)

passwd = ""
for characters in ran_user_choice:
  passwd += characters

print(f"Here is your password: {passwd}")
```

{% endtab %}

{% tab title="Angela's Answer" %}

```
#Password Generator Project
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n")) 
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

#Eazy Level
# password = ""

# for char in range(1, nr_letters + 1):
#   password += random.choice(letters)

# for char in range(1, nr_symbols + 1):
#   password += random.choice(symbols)

# for char in range(1, nr_numbers + 1):
#   password += random.choice(numbers)

# print(password)

#Hard Level
password_list = []

for char in range(1, nr_letters + 1):
  password_list.append(random.choice(letters))

for char in range(1, nr_symbols + 1):
  password_list += random.choice(symbols)

for char in range(1, nr_numbers + 1):
  password_list += random.choice(numbers)

print(password_list)
random.shuffle(password_list)
print(password_list)

password = ""
for char in password_list:
  password += char

print(f"Your password is: {password}")
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://python.microcisco.com/python-bootcamp/100-days/day-5-for-loops-range-and-code-blocks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
