PYTHON
  • PYTHON v3
  • Python IDE Setup
  • Python Programming
    • Python for ABS
      • Resources
      • Ch1 - Getting Started
      • Ch2 - Types, Variables and Simple I/O
  • Python For Network Engineers-Kirk Beyers
    • Resources
    • Python Fundamentals
  • Python Inststitute (PCAP)
    • Resources
    • Course Introduction
    • Python Essentials (Part 1)
      • Module 1
        • Fundamentals
        • What is Python
        • Starting your work with Python
      • Module 2
        • The Print Function
          • Section Summary
        • Literals
          • Section Summary
        • Operations- Data Manipulation Tools
          • Section Summary
        • Variables
          • Leaving Comments in Code
          • The input () Function
  • 100 Days Of Code
    • Resources
    • What You Have To Do !!
    • 100 DAY's
      • DAY 1: Working with Variables
      • Day 2: Data Types & String Manipulation
      • Day 3: Control Flow and Operators
      • Day 4: Randomisation and Lists
      • Day 5: For Loops, Range & Code Blocks
      • Day 6: Python Functions and Karel
      • Day 7: Hangman
      • SUMMARY
  • {Pirple}
    • Resources
Powered by GitBook
On this page
  • Loops
  • EXERCISE 1 - Average Height
  • EXERCISE 2 - Highest Score
  • Hint
  • Solution
  • For Loop and range(function)
  • Exercise: Adding Even Numbers
  • Exercise: FizzBuzz
  • Project of the Day - Password Generator

Was this helpful?

  1. 100 Days Of Code
  2. 100 DAY's

Day 5: For Loops, Range & Code Blocks

PreviousDay 4: Randomisation and ListsNextDay 6: Python Functions and Karel

Last updated 4 years ago

Was this helpful?

Loops

The 1st type of loop is called the "For Loop" which means for item in list_of_items #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'

EXERCISE 1 - Average Height

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

EXERCISE 2 - Highest Score

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

  • Convert the list of strings into a list of integers using the "for loop"

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

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

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

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

Exercise: Adding Even Numbers

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.

Exercise: FizzBuzz

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)

Project of the Day - Password Generator


#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}")
#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}")
I did this without using Angela's predefined "don't change the code below" - better practice for me:)