본문 바로가기
Coding : Python

Python_Day 5

by Jackykim 2023. 11. 23.

Python Day 5_Python loops

For loop
for item in list_of_items: #do something to each item
fruits = ["apple", "peach", "pear"]

for fruit in fruits:

    print(fruit)

 

Allows us to execute the same line of code multiple number of times.
However if the print function or another code is out of the indentation loop then it won’t be part of the loop. We can add into the loop with print(fruit + “ pie”) which will print:
apple
apple pie
peach
peach pie etc

Average Height coding exercise
You are going to write a program that calculates the average student height from a List of heights.

e.g. student_heights = [180, 124, 165, 173, 189, 169, 146]

The average height can be calculated by adding all the heights together and dividing by the total number of heights.

# Input a Python list of student heights

student_heights = input().split()

for n in range(0, len(student_heights)):

  student_heights[n] = int(student_heights[n])

# 🚨 Don't change the code above 👆

 

# Write your code below this row 👇

total_height = 0

for height in student_heights:

  total_height += height

print(f"total height = {total_height}")

 

number_of_students = 0

for students in student_heights:

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

total height = 475

number of students = 3

average height = 158

 

High Score coding exercise
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
# 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 👇

# Setting up the highest score viable.

# This line sets the initial value of highest_score to the first score in the list. This provides a starting point for comparison.

highest_score = student_scores[0]

 

# Using the loop to find the high score

# The if statement checks if the current score is greater than the current highest_score. If it is, the highest_score is updated with the current score.

for score in student_scores:

  if score > highest_score:

    highest_score = score

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

For loops and the range() function
Range is good for ranging numbers to loop through
for number in range (1, 10):

 Print(number) -> output would be 1 ~ 9 (does not include the 10)

You can add steps in range by adding a comma
for number in range (1, 11, 3):

 Print(number) -> output would be 1 4 7 10

To get the sum of all the numbers in range we can use the previous loop + range functions
total = 0
for number in range(1, 101):
 total += number
 print(total) -> output 5050

Adding even numbers coding exercise
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 👇

even_score = 0

# The range(2, target + 1, 2) generates a sequence of even numbers starting from 2 up to and including the target, with a step size of 2.

for total in range (2, target + 1, 2):

  even_score += total

print(f"{even_score}")

Alternative code:
even_sum = 0
for number in range(1, target +1):
if number % 2 ==0:
even_sum += number
print(f"{even_sum}")

Question: For the loop why is it The range(2, target + 1, 2) instead of range(2, target, 2)?
range(2, target + 1, 2)

This includes the number target in the range.

The + 1 in target + 1 ensures that the number target is included in the sequence.

The 2 at the end of the range specifies a step size of 2, ensuring that only even numbers are included in the sequence.


range(2, target, 2)

This does not include the number target in the range.

Without the + 1, the upper bound of the range is exclusive, so target itself is not included.

Similar to the previous case, the 2 at the end specifies a step size of 2, ensuring that only even numbers are included.

The fizzBuzz Job Interview coding exercise
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"

# Write your code here
👇

fizzbuzz = 0

for fizzbuzz in range(1, 101):

  if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:

    print("FizzBuzz")

  elif fizzbuzz % 3 == 0:

    print("Fizz")

  elif fizzbuzz % 5 == 0:

    print("Buzz")

  else:

    print(fizzbuzz)

alternate code:
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)

Project 5: Create a random password generator
#Easy version

random_letters = ""

random_symbols = ""

random_numbers = ""

 

# Generate random letters

for _ in range(nr_letters):

    random_letters += random.choice(letters)

 

# Generate random symbols

for _ in range(nr_symbols):

    random_symbols += random.choice(symbols)

 

# Generate random numbers

for _ in range(nr_numbers):

    random_numbers += random.choice(numbers)

 

# Concatenate the random characters to form the password

random_password = random_letters + random_symbols + random_numbers

 

print(random_password)

Alternative
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.append(random.choice(symbols))

 

for char in range(1, nr_numbers +1):

    password_list.append(random.choice(numbers))

 

random.shuffle(password_list)

 

password = ""

for char in password_list:

    password += char

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

'Coding : Python' 카테고리의 다른 글

Python_Day 7  (0) 2023.12.02
Python_Day 6  (0) 2023.11.30
Python_Day 4  (0) 2023.11.17
Python_Day 3  (0) 2023.11.15
Python_Day 2  (0) 2023.11.10