CMSC 201

Lab 4: Loops

Remember, before running each program type:

scl enable python33 bash

Programs

Calculate the average!

To practice using while loops, we are going to make a program where the user enters how many numbers they would like to take the average of, the numbers they would like to average, and prints out the average to the user.

Steps to complete this program:

  1. Prompt the user to enter how many numbers they would like to be averaged (don't forget casting!)
  2. For every number the user wants averaged, prompt the user to enter their number and updates the current sum of entered numbers
  3. When all the numbers have been entered, print out the average to the user

**This program should only have two input statements, and should work no matter how many values the user wants to average**

The Guessing Game!

In this program, you will be given code that generates a random number between 1 and 10 (inclusive). Your job is to write code that adds on to it, prompting the user to enter a guess repeatedly until they no longer want to play.

Sample output code:

Guess a number between 1 and 10 (inclusive) and I'll tell you if you're right!
Enter your guess: 2
NOPE. Would you like to guess again? (y,n) y
Enter your guess: 3
NOPE. Would you like to guess again? (y,n) y
Enter your guess: 5
NOPE. Would you like to guess again? (y,n) y
Enter your guess: 7
YOU WIN!!!!!!!

or

Guess a number between 1 and 10 (inclusive) and I'll tell you if you're right!
Enter your guess: 3
NOPE. Would you like to guess again? (y,n) y
Enter your guess: 6
NOPE. Would you like to guess again? (y,n) y
Enter your guess: 2
NOPE. Would you like to guess again? (y,n) n

Steps to complete this program:

  1. Initialize a variable called choice to represent the user's choice of whether to continue guessing or not.
  2. Initialize a variable called guess to represent the user's guess. The variable should be initialized to 0 so that it is not in the range of correct answers.
  3. Write a loop that will execute based on the two initialized variables, choice and guess. (This is a way to force the user to enter a guess at least once).
  4. Prompt the user for a guess.
  5. If the guess was incorrect, inform the user and ask if they would like to guess again.
  6. If they would like to guess again, save their choice in such a way that the test condition will cause the loop to repeat. If they do not want to guess again, the loop should exit the program.
  7. If the user's guess was correct, tell the user and end the loop (which should end the program).

Provided code:

import random

randnum = random.randint(1,10)

print("Guess a number between 1 and 10 (inclusive) and I'll tell you if you're right!")