Sunday, August 2, 2015

Intro to Programming with Python - Tutorial 8 - Exercise

In the 8th tutorial in the introduction to programming with python series we introduced for loops.
The video tutorial can be found here:
https://www.youtube.com/watch?v=b8R9ysVd1sg

The exercise for this tutorial is to make the previous exercise, for tutorial 7, more flexible.
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 for 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 more user friendly manner than what we did for the last exercise (See sample program output below)
Here is a sample output of running the program:


Here is the program itself for your reference:
# 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 our for loop.
# Remember using the range(numOfStudents)
# we will execute the loop that many times
for index in range(numOfStudents):
name = input('Enter student name: ')
# Read the mark and conver it to an int
mark = int(input('Enter student mark: '))
# Add the name -> mark key value pair to the grades dictionary
grades[name] = mark
# Now pretty print
print('Your class grades are as follows: ')
for name in grades:
print(' ', name, '-->', grades[name])


No comments:

Post a Comment