100 Days of Code: Day 05 - For Loops, Range and Code Blocks in Python

100 Days of Code: Day 05 - For Loops, Range and Code Blocks in Python

Today Goal:

#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"))

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}")

Using the for loop with Python Lists

The for loop is a powerful construct in Python for iterating over elements in a sequence, such as a list. It allows you to perform a set of operations on each element of the list. Here's an example of how to use a for loop with Python lists:

fruits = ['apple', 'banana', 'cherry', 'date']

# Iterating over the elements of the list using a for loop
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry
# date

In the above example, we have a list called fruits that contains four elements. We use a for loop to iterate over each element of the list. Inside the loop, the variable fruit represents the current element being processed. We print each element using the print() function.

You can also perform operations on the elements of the list within the loop. For instance, let's say we want to print the length of each fruit name:

fruits = ['apple', 'banana', 'cherry', 'date']

# Iterating over the elements of the list and printing the length of each element
for fruit in fruits:
    print(fruit, len(fruit))

# Output:
# apple 5
# banana 6
# cherry 6
# date 4

In this case, we use the len() function to calculate the length of each fruit name and print it alongside the fruit name within the loop.

You can also modify the elements of the list using a for loop. For example, let's capitalize each fruit name:

fruits = ['apple', 'banana', 'cherry', 'date']

# Modifying the elements of the list by capitalizing each fruit name
for i in range(len(fruits)):
    fruits[i] = fruits[i].capitalize()

print(fruits)

# Output:
# ['Apple', 'Banana', 'Cherry', 'Date']

In this case, we use the range() function to generate indices for the elements in the list. We then access each element using the index i and modify it by calling the capitalize() method. Finally, we print the modified list.

Example: Calculating Average Student Height

student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])

# print(student_heights)
total_heights = 0
for height in student_heights:
    total_heights += height

# print(total_heights)
number_of_students = 0
for student in student_heights:
    number_of_students += 1

# print(number_of_students)

avarage_heigh = round(total_heights / number_of_students)

print(avarage_heigh)

Explanation of above code:

Let's go through the code step by step and explain what each part does:

  1.     student_heights = input("Input a list of student heights ").split()
    

    This line prompts the user to input a list of student heights, which should be entered as space-separated values. The input() function is used to receive the input as a string, and then the split() method is applied to convert the string into a list of individual height values.

    For example, if the user enters: 125 145 160 182 129 145, the student_heights variable will contain ['125', '145', '160', '182', '129', '145'].

  2.     for n in range(0, len(student_heights)):
            student_heights[n] = int(student_heights[n])
    

    This loop iterates over the indices of the student_heights list using the range() function. For each index n, the corresponding height value at that index is converted from a string to an integer using the int() function. The updated integer value is then assigned back to the same position in the list.

    After this loop, the student_heights list will contain integer values instead of strings.

  3.     total_heights = 0
        for height in student_heights:
            total_heights += height
    

    This loop iterates over each height value in the student_heights list. The total_heights variable is initialized as 0, and at each iteration, the current height value is added to it.

    By the end of this loop, total_heights will hold the sum of all the heights in the list.

  4.     number_of_students = 0
        for student in student_heights:
            number_of_students += 1
    

    This loop iterates over each height value in the student_heights list. The number_of_students variable is initialized as 0, and at each iteration, it is incremented by 1.

    After this loop, number_of_students will represent the total count of student heights in the list.

  5.     average_height = round(total_heights / number_of_students)
    

    This line calculates the average height by dividing the total_heights by the number_of_students. The round() function is used to round the result to the nearest whole number.

  6.     print(average_height)
    

    Finally, the average height is printed on the console.

  7. Output:

     Input a list of student heights 125 145 160 182 129 145
     148
    

    Given the input of 125 145 160 182 129 145, the output of this code will be 148, which is the rounded average height of the students.

The code takes a list of student heights, converts the heights to integers, calculates the total height, counts the number of students, and then computes the average height.

for loops and the range() function

The range() function is often used in conjunction with for loops in Python. It provides a convenient way to generate a sequence of numbers that can be used to control the iteration of the loop. The range() function returns an iterable sequence of numbers, and the for loop can iterate over these numbers. Here's how you can use range() with a for loop:

# Iterating over a sequence of numbers using range() and for loop
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

In the above example, the range(5) generates a sequence of numbers from 0 to 4 (5 is the exclusive upper bound). The for loop iterates over these numbers, and at each iteration, the value of i is set to the current number in the sequence. We then print the value of i within the loop.

You can also specify the starting and ending points of the range by providing arguments to the range() function. For example:

# Iterating over a sequence of numbers with a defined starting and ending point
for i in range(2, 8):
    print(i)

# Output:
# 2
# 3
# 4
# 5
# 6
# 7

In this case, range(2, 8) generates a sequence of numbers from 2 to 7 (8 is excluded). The for loop iterates over these numbers and prints each value.

You can also specify a step value to control the increment between numbers in the range. By default, the step is 1, but you can provide a different value as the third argument to range(). Here's an example:

# Iterating over a sequence of numbers with a defined step
for i in range(0, 10, 2):
    print(i)

# Output:
# 0
# 2
# 4
# 6
# 8

In this example, range(0, 10, 2) generates a sequence of numbers from 0 to 8 (10 is excluded) with a step of 2. The for loop iterates over these numbers, and we print each value.

The combination of for loops and the range() function provides a flexible way to iterate over a sequence of numbers and control the behavior of the loop based on the iteration index.

Example: FinBuzz Game

Instructions

You are going to write a program that automatically prints the solution to the FizzBuzz game.

Your program should print each number from 1 to 100 in turn.

When the number is divisible by 3 then instead of printing the number it should print "Fizz".

When the number is divisible by 5, then instead of printing the number it should print "Buzz".`

And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"

e.g. it might start off like this:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

.... etc.

Hint

  1. Remember your answer should start from 1 and go up to and including 100.

  2. Each number/text should be printed on a separate line.

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)

Let's break down the code step by step to understand what it does:

  1.     for number in range(1, 101):
            # Code block inside the loop
    

    This for loop iterates over the numbers from 1 to 100 (both inclusive). The loop variable number takes each value from the range during each iteration.

  2.     if number % 3 == 0 and number % 5 == 0:
            print("FizzBuzz")
    

    This condition checks if the current number is divisible by both 3 and 5. If it is, the code prints "FizzBuzz".

  3.     elif number % 3 == 0:
            print("Fizz")
    

    This elif condition checks if the current number is only divisible by 3. If it is, the code prints "Fizz".

  4.     elif number % 5 == 0:
            print("Buzz")
    

    This elif condition checks if the current number is only divisible by 5. If it is, the code prints "Buzz".

  5.     else:
            print(number)
    

    If none of the above conditions are met, the code prints the current number.

Now, let's see the code in action with some examples:

  • When number is 1, it is not divisible by 3 or 5, so it prints the number itself: 1.

  • When number is 3, it is divisible by 3 but not 5, so it prints "Fizz".

  • When number is 5, it is divisible by 5 but not 3, so it prints "Buzz".

  • When number is 15, it is divisible by both 3 and 5, so it prints "FizzBuzz".

The loop continues in this manner for all numbers from 1 to 100, applying the appropriate conditions and printing "Fizz", "Buzz", "FizzBuzz", or the number itself based on divisibility.

The output of the code will be:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

This is a classic "FizzBuzz" problem that demonstrates the use of conditionals and loops to perform different actions based on certain conditions.

Day-05 Assignment

#Password Generator Project

#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"))

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}")

#Output

Welcome to the PyPassword Generator!
How many letters would you like in your password?
12
How many symbols would you like?
3
How many numbers would you like?
3
['z', 'w', 'Y', 's', 'H', 'a', 'M', 'J', 'P', 'u', 'h', 'd', '&', '&', '+', '5', '5', '6']
['a', 'H', '&', 'w', 'P', '5', '&', 'd', '+', 'Y', 'J', 's', '5', 'z', 'u', 'M', 'h', '6']
Your password is: aH&wP5&d+YJs5zuMh6

Let's go through the code step by step and explain what each part does:

  1. The code begins by importing the random module, which allows us to generate random values.

  2. Three lists are defined: letters, numbers, and symbols. These lists contain characters that can be used to create passwords.

  3. The user is prompted with a series of questions to determine the length and composition of the password they want.

  4. The code then proceeds to generate the password.

    • In the "Easy Level" section (commented out in the code), the password is created by concatenating characters randomly selected from the letters, symbols, and numbers lists.

    • In the "Hard Level" section, instead of using a string to store the password, a list called password_list is created.

      • The specified number of letters, symbols, and numbers are appended to the password_list using a loop and random.choice() function. This ensures that the password has the desired composition.
  5. After creating the password_list, it is shuffled using the random.shuffle() function. This step is performed to randomize the order of characters in the password.

  6. Finally, the shuffled password_list is converted back to a string by concatenating its elements. The resulting string is assigned to the variable password.

  7. The code then prints the generated password to the console.

Let's see an example execution:

Suppose the user enters nr_letters = 12, nr_symbols = 3, and nr_numbers = 3.

  • The password_list will first have 12 randomly selected letters, then 3 randomly selected symbols, and finally, 3 randomly selected numbers.

  • Suppose the password_list ends up as ['z', 'w', 'Y', 's', 'H', 'a', 'M', 'J', 'P', 'u', 'h', 'd', '&', '&', '+', '5', '5', '6'] after the shuffling step.

  • The final password will be the concatenation of the elements in password_list, resulting in "aH&wP5&d+YJs5zuMh6".

The output will be:

Your password is: aH&wP5&d+YJs5zuMh6

The code allows users to create a password with a specified number of letters, symbols, and numbers, ensuring a random composition each time.

If you miss The 100 days of the Python - Day - 01

If you miss The 100 days of the Python - Day - 02

If you miss The 100 days of the Python - Day - 03

#100DaysofCode #Python #Day5

Did you find this article valuable?

Support Ganesh Balimidi by becoming a sponsor. Any amount is appreciated!