Here's my solution to problem 1. It is just a simple raw_input
statement followed by an if statement
Problem 1 Solution
There are a lot of ways to go about solving problem 2. The basic
idea is to keep multiplying the number by higher integers until
you get to a value greater than or equal to 50. I saw good
solutions using a while loop and good
solutions using a for loop.
Problem 2 Solution
Here's my solution to problem 3.
Problem 3 Solution
The three errors were in problem 3 were:
- if userInput = "q": should be if userInput == "q": with a double equals sign to check for equality (line 4)
- elif n * n > targetNumber should have a : at the end of the line (line 13)
- shouldcontinue did not have a capital C. It should have been spelled shouldContinue (line 1)
Posted Thursday, July 30
User input and Conditionals
Write a program that asks the user for their name. If their name is "Shad", print out "Hi professor", otherwise print out "Hi there"
Here's what a run of the program would look like if the user entered: "Shad"
And here's what another run would look like if the user entered: "Joe"
Loops
Write a program that asks the user to input a number between 1 and 10 and then prints out all the multiples of that number that are less than 50. Try to match the look of the example runs exactly.
Here's what a run of the program would look like if the user entered "10":
Here's what a run of the program would look like if the user entered "7":
Here's what a run of the program would look like if the user entered "2":
Finding errors
The following program determines whether an integer is a perfect square. There are no logic bugs in the program, but there are 2 syntax errors and 1 other error. Fix the bugs so that the program runs correctly. You can copy and paste the code from the web browser or just download it using this link
shouldcontinue = True while shouldContinue == True: userInput = raw_input("Enter an integer to see if it's a perfect square (q to quit): ") if userInput = "q": print "Goodbye" shouldContinue = False else: targetNumber = int(userInput) for n in range(targetNumber): if n * n == targetNumber: print userInput + " is a perfect square!" break elif n * n > targetNumber print userInput + " is not a perfect square" break
Here's what a sample run of the program after it has been fixed should look like:
Note: that you do not need to make major changes to this program. The changes required are small. Two of the errors are invalid syntax and the other is a programming typo.
Side note, this program doesn't properly handle the case where a user enters the numbers 1 or 2, that's okay, I just wanted to keep the program as simple as possible.