Saturday, August 15, 2015

Intro to Programming with Python - Tutorial 9 - Exercise 2

This is our second exercise for tutorial 9 (https://youtu.be/rW-iqRxP6Cs)

In this exercise we have to redo the exercise from tutorial 8 using a while loop.

So for this exercise:
  • Initialize an empty grades dictionary variable.
  • Prompt the user for the number of students in the class. 
  • Convert the number of students to an integer
  • Use a WHILE loop to allow the user to enter each student name and grade and add them to the grades dictionary.
  • When finished print the grades dictionary back to the user in a friendly manner. You can use the same for loop to pretty print the dictionary as used in tutorial 8
Here is a sample output of running this program:


Here is the code that accomplishes this:
# Ask the user how many students they have in their class
numOfStudents = int(input('How many students do you have in your class? '))
# Create an empty grades dictionary
grades = {}
# Here is how we loop N times using a while loop
num = 0
while num < numOfStudents:
name = input('Enter student name: ')
# Read the mark and convert it to int
mark = int(input('Enter student mark: '))
grades[name] = mark
# Now we increment the num variable by 1
num += 1
# Now pretty print
print('Your class grades are as follows: ')
for name in grades:
print(' ', name, '-->', grades[name])

No comments:

Post a Comment