Skip to main content

Command Palette

Search for a command to run...

πŸ‘©πŸΌβ€πŸ’» Day5 - #100DaysOfCode in Python

Day 5 β€” Beginner β€” Python Loops

Published
β€’7 min readβ€’View as Markdown
πŸ‘©πŸΌβ€πŸ’» Day5 - #100DaysOfCode in Python
F

I'm starting my journey as a Data scientist. I am also Senior UX Designer specialized in dataviz. Experience in predictive modeling, data cleansing, feature engineering, data visualization and pipeline building.

Today’s Goals:

Learn enough to build a Password Generator

In order to build this, I had to address some skills, such as working with Loops, Range and Code Blocks πŸ‘©πŸΌβ€πŸ’».

What I’ve Know:

πŸ“Œ For loops.
πŸ“Œ Range function.
πŸ“Œ More uses of lists[].
πŸ“Œ join method β†’ join in Python takes all the elements of an iterable and joins them into a single string. It will return the joined string.
πŸ“Œ The sample() method returns a list with a randomly selection of a specified number of items from a sequence.
and more!

What I Learned Today:

In Python, a for loop is used to iterate over a sequence of elements, such as a list, tuple, dictionary, set, or string. It's a way to execute a block of code repeatedly for each element in the sequence. Here is the basic structure and a simple example:

Basic structure:

for variable in sequence:
    # Block of code to execute
  • variable is a temporary variable that takes the value of the current element of the sequence in each iteration.

  • sequence is the collection of elements that will be iterated over.

Example:

for number in [1, 2, 3, 4, 5]:
    print(number)

In this example, the for loop iterates through the list [1, 2, 3, 4, 5]. In each iteration, the variable number takes a value from the list (1, then 2, and so on) and executes the block of code within the loop, which in this case is simply printing the number.

For loops are a powerful and flexible tool in Python, commonly used for efficiently and readably performing repetitive actions.

For Loop with Range

In Python, range is often used with a for loop to iterate over a sequence of numbers. It generates a series of integers in a specified range. Here's a brief explanation:

  • Basic Usage: for i in range(n): Iterates from 0 to n-1.

  • Custom Start and End: for i in range(start, end): Iterates from start to end-1.

  • Step Size: for i in range(start, end, step): Iterates from start to end-1, incrementing by step.

For example:

for i in range(5):
    print(i)

This will print numbers 0 to 4.

range is useful for repeating an action a specific number of times or iterating through sequences by their indices.

Here are some examples demonstrating the use of range in a for loop in Python:

1)Basic Iteration: Iterate from 0 to 4 and print each number

for i in range(5):
    print(i)

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

2) Specifying Start and End: Iterate from 2 to 5 (5 is not included) and print each number.

for i in range(2, 6):
    print(i)

#Output: 2, 3, 4, 5

3) Using Step Size: Iterate from 1 to 9, stepping by 2 (i.e., count in odd numbers)

for i in range(1, 10, 2):
    print(i)

#Output: 1, 3, 5, 7, 9

4) Iterating Backwards: Iterate backwards from 5 to 1.

for i in range(5, 0, -1):
    print(i)

#Output: 5, 4, 3, 2, 1

5) Using range with Lists: Print each element in a list using its index.

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(fruits[i])

#Output: apple, banana, cherry

These examples demonstrate the versatility of range in controlling the flow and count of iterations in a for loop.

Code Sample:

1)You are going to write a program that calculates the highest score from a List of scores.

e.g. student_scores = [78, 65, 89, 86, 55, 91, 64, 89]

Important you are not allowed to use the max or min functions. The output words must match the example. i.e The highest score in the class is: x

Example Input 78 65 89 86 55 91 64 89 In this case, student_scores would be a list that looks like: [78, 65, 89, 86, 55, 91, 64, 89]

Example Output The highest score in the class is: 91

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

# Write your code below this row πŸ‘‡
total_height = 0

for height in student_scores:
  total_height += height
print(f"total height = {total_height}")

number_of_students = 0
for student in student_scores:
  number_of_students += 1
print(f"number of students = {number_of_students}")

average_height = round(total_height / number_of_students)
print(f"average height = {average_height}")

And if we wanted like to get the highest score:

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

# Write your code below this row πŸ‘‡
# Find the highest score
highest_score = max(student_scores)
print(f"The highest score in the class is: {highest_score}")

Another solution:

student_scores = input().split()
for n in range(0, len(student_scores)):
  student_scores[n] = int(student_scores[n])

# Your code below this row πŸ‘‡
highest_score = 0
for score in student_scores:
  if score > highest_score:
    highest_score = score
    # print(highest_score)

print(f"The highest score in the class is: {highest_score}")

2) You are going to write a program that calculates the sum of all the even numbers from 1 to X. If X is 100 then the first even number would be 2 and the last one is 100:

i.e. 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.

Also, we will constrain the inputs to only take numbers from 0 to a max of 1000.

target = int(input()) # Enter a number between 0 and 1000
# 🚨 Do not change the code above ☝️

# Write your code here πŸ‘‡

# iterating each number in list

even_sum = 0

for number in range(2, target + 1, 2):
  #accumulate even_sum here
  even_sum += number
print(even_sum)

or

target = int(input()) # Enter a number between 0 and 1000
# 🚨 Do not change the code above ☝️

# Write your code here πŸ‘‡

# iterating each number in list

alternative_sum =  0
for number in range(1, target + 1):
  if number % 2 == 0:
    alternative_sum += number

print(alternative_sum)

3) You are going to write a program that automatically prints the solution to the FizzBuzz game. These are the rules of the FizzBuzz game:

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

  • 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

I will show solutions from a beginner to a more experienced level:

# Write your code here πŸ‘‡
target = 100
for number in range(1, target + 1):
  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)
# Write your code here πŸ‘‡
target = 100
is_fizz = lambda x: x % 3 == 0
is_buzz = lambda x: x % 5 == 0

for number in range(1, target + 1):
  message = ""
  if is_fizz(number) and is_buzz(number):
    message = "FizzBuzz"
  elif is_fizz(number):
    message = "Fizz"
  elif is_buzz(number):
    message = "Buzz"
  else:
    print(number)
  if message:
    print(message)

or

# Write your code here πŸ‘‡
target = 100
is_fizz = lambda x: x % 3 == 0
is_buzz = lambda x: x % 5 == 0

for number in range(1, target + 1):
  if is_fizz(number) and is_buzz(number):
    print("FizzBuzz")
  elif is_fizz(number):
    print("Fizz")
  elif is_buzz(number):
    print("Buzz")
  else:
    print(f"{number} is not divisible by 3 nor by 5")

Project: Password Generator

For the password generator, I used different methods to reach the solution. On the one hand, we have an option with a more β€œsimple” level, where we obtain a password with randomly drawn characters of each type (letters, symbols and numbers), but they are concatenated in an orderly manner. On the other hand, we have a more optimal option, of medium to high level, where we obtain the password with random characters of each type, but also random in itself, instead of concatenating them, they are inserted in a list. As a bonus, I have included a solution where there is no for loop, and I use random.sample() instead.

Example of eazy solution

Eazy level β†’ Not Randomized

First option

Second option β†’ In a function

Third option β†’ With random.sample()

Hard level β†’ Randomized

First option

Option 2 β†’ Using random.sample with List[]

Thanks 🫢🏻

πŸ“ŒNow you can also find me at the following links:

πŸ‘‰πŸ» Instagram
πŸ‘‰πŸ» Twitter
πŸ‘‰πŸ» Medium
πŸ‘‰πŸ» LinkedIn