Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The code:
#Loop to conduct program. User input required for each option.
count = 1
while count == 1:
score = input("Enter Test Score: ")
if (score >= 90) and (score <= 100):
print "A"
elif (score >= 80) and (score <= 89):
print "B"
elif (score >= 70) and (score <= 79):
print "C"
elif (score >= 60) and (score <= 69):
print "D"
elif (score <= 59):
print "F"
elif (score == quit):
print "Program Finsihed. Goodbye."
count = 0 #Count to end loop
else:
print "Please enter valid response."
All other conditions work, however, if something typed it does not meet the parameters, the code is supposed to prompt them again (which is what the while loop is for). However, an error arises whenever a string that does not match the parameters is attempted.
Don't use input. input on Python 2 tries to evaluate the input as a Python expression, so if you type something like fhqwhgads, Python thinks that's supposed to be Python code and throws an error because there's no fhqwhgads variable.
Use raw_input, which gives you the input as a string. You can then perform string operations on it, or (try to) convert it to an integer and handle the exception if the conversion fails:
while True:
user_input = raw_input("Enter Test Score: ")
if user_input == 'quit':
print "Program Finsihed. Goodbye."
break
try:
score = int(user_input)
except ValueError:
print "Please enter valid response."
continue
if 90 <= score <= 100:
print "A"
elif 80 <= score < 90:
...
Incidentally, quit is one of the few choices you could have made for your "we're done here" option that wouldn't have caused an error with your original code, because there's (usually) an actual quit object for that to resolve to when input tries to treat it as Python code.
There were many problems with your code. I think it would be much easier to see and resolve the issues if you break your code down into functional units. I made two functions: get_score deals with prompting the user for input and score_to_grade converts a number score into a letter score. Doing this makes the code much more readable and easier to refactor, debug, etc. in the future.
def get_score():
while True:
user_in = raw_input("Enter Test Score: ")
try:
return float(user_in)
except ValueError:
if user_in == "quit":
print "Program Finished. Goodbye."
raise SystemExit
print "Please enter valid response."
def score_to_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
while True:
print score_to_grade(get_score())
quit needs to be in quotes, since it is a string, not a variable:
...
elif (score == "quit")
...
Related
I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')
This question already has answers here:
Python - User input data type
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am very new to programming and Python. To get started I'm working on a little game that will ask the user for some input and then do "something" with it. My problem is I've seem to account for if the user types in an int lower or high than my parameters BUT i can't seem to find a way to re-prompt the user if they type in anything but an int.
With my limited knowledge I thought that when using an if/elif/else statement if you didn't define what the if/elif is looking for than the else statement was there for everything else that you didn't account for?
Looking for some more insight on how to master this fundamental concept
Thank you in advance!
prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 \n >")
if user_input > 0 and user_input <= 10:
print("Good job " + str(user_input) + " is a great number")
break
elif (user_input > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")
How about something like this?
a = -1
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue
This will only allow the user to enter an int from 0 to 10, this will also remove the need to print those messages if the number is outside of this range, if you would like to keep those messages I could make adjustments and show you how to handle that as well
I have been assigned in my intro to computer science class to write a program that will print out a number that the user is asked to enter (20-99). I have been able to do that, and have created an error message if the user doesn't enter a number in this range. The issue I am having is when a number out of range is entered, the error message displays, but for some reason the program continues and still prints out a english number. I have been trying to figure out how to get the program to stop at the error message, but I have not been able to figure it out. Here is what I currently have.
a=int(input('Pick a number between 20 through 99:'))
b=a//10
c=a%10
while a<20 or a>99:
print('Error, enter number between 20 and 99:')
break
while a>20 or a<99:
if b==2:
print('The number is Twenty',end=' ')
elif b==3:
print('The number is Thirty',end=' ')
elif b==4:
print('The number is Fourty',end=' ')
elif b==5:
print('The number is Fifty',end=' ')
elif b==6:
print('The number is Sixty',end=' ')
elif b==7:
print('The number is Seventy',end=' ')
elif b==8:
print('The number is Eighty',end=' ')
else:
print('The number is Ninety',end=' ')
if c==1:
print('One')
elif c==2:
print('Two')
elif c==3:
print('Three')
elif c==4:
print('Four')
elif c==5:
print('Five')
elif c==6:
print('Six')
elif c==7:
print('Seven')
elif c==8:
print('Eight')
else:
print('Nine')
break
The second conditional you want and not or
while a>20 and a<99:
also use if because it will infinite loop if you don't
You have confused "while" with "if". You need an "if" statement here; "while" is for things you intend to repeat.
Also, note that a>20 or a<99 is always true; any number is one or the other. I believe you wanted an "and" here, which makes this merely the "else" clause of the "if" statement.
Finally, I'm not sure what you're trying to do with the "end=" in your first bank of print statements. This is a syntax error.
You have put the break statement inside of the while loop. This means that when you reach that statement, you leave the while loop. So no matter what, your function will leave the loop. A good sign that your while loop is not correct or out of place is if you call a break at the end. Here is a better way.
while True:
a=int(input('Pick a number between 20 through 99:'))
if a > 20 and a < 99:
break;
else:
print("Error, enter number between 20 and 99")
What happens is that the loop goes on indefinitely. Once the correct input is entered, it breaks from the loop. If the input is not correct, it just loops again.
Even though you didn't ask about it, I'm going to comment on the other half as well. First, your condition doesn't make sense. All numbers are either over 20 or under 99. You need to use an and so that BOTH must be true. However, the other part is that you don't even need this conditional statement. We already know that we are in this limit. That's what we made sure of in our previous while loop. Lastly, as stated before, the while itself isn't need. If you want to use a conditional that you only use one time, just use an if statement. While is mean for looping and forces you to have a break statement at the end if you will only ever use it once. Here is your completed code:
while True:
a=int(input('Pick a number between 20 through 99:'))
if a > 20 and a < 99:
break;
else:
print("Error, enter number between 20 and 99")
b=a//10
c=a%10
if b==2:
print('The number is Twenty',end=' ')
elif b==3:
print('The number is Thirty',end=' ')
elif b==4:
print('The number is Fourty',end=' ')
elif b==5:
print('The number is Fifty',end=' ')
elif b==6:
print('The number is Sixty',end=' ')
elif b==7:
print('The number is Seventy',end=' ')
elif b==8:
print('The number is Eighty',end=' ')
else:
print('The number is Ninety',end=' ')
if c==1:
print('One')
elif c==2:
print('Two')
elif c==3:
print('Three')
elif c==4:
print('Four')
elif c==5:
print('Five')
elif c==6:
print('Six')
elif c==7:
print('Seven')
elif c==8:
print('Eight')
else:
print('Nine') `enter code here`
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Thanks for the answers. This code works fine for this.
def rate_score(selection):
if selection < 1000:
return "Nothing to be proud of!"
elif selection >= 1000 and selection < 10000:
return "Not bad."
elif selection >= 10000:
return "Nice!"
def main():
print "Let's rate your score."
while True:
selection = int(raw_input('Please enter your score: '))
break
print 'You entered [ %s ] as your score' % selection
score = rate_score(selection)
print score
main()
However I also need to set the parameter of rate_score(selection) to 0 as the default and add a call to rate_score(selection) in which you pass no value to the function. I have revised the code to this:
def rate_score(selection):
if selection < 1000:
return "Nothing to be proud of!"
elif selection >= 1000 and selection < 10000:
return "Not bad."
elif selection >= 10000:
return "Nice!"
else:
selection = 0
selection = int(raw_input("Enter your score. "))
score = rate_score(selection)
print score
Did I at least set it up so that the default parameter would be 0? If not how should I go about changing it to be the default parameter of rate_score()? Also I do not know how to go about allowing no value to be passed to rate_score considering you get an error if you do not enter anything because of raw_input.
"and return a string" - That's what the return keyword is for:
def rate_score(score):
if score < 1000:
return "Nothing to be proud of."
As Lasse V. Karlsen commented on your question, you'll first need to replace your print with a return.
You probably want another condition if the score is something to be proud of, right?
Here's that, while receiving the score as input from the user:
def rate_score(selection):
if selection < 1000:
return "Nothing to be proud of!"
else:
return "Now that's something to be proud of!"
def main():
print "# rate_score program #"
while True:
try:
selection = int(raw_input('Please enter your score: '))
except ValueError:
print 'The value you entered does not appear to be a number !'
continue
print 'You entered [ %s ] as your score' % selection
response = rate_score(selection) # Now the function rate_score returns the response
print response # Now we can print the response rate_score() returned
main()
raw_input is a Built-in Function in python, which can be used to get input from a user.
Using raw_input(), and int(), we can also make sure that the input from the user is a number. This is because int() will throw a specific error if you try to give it something that is not a number. The error it throws is called a ValueError.
>>> int('notanumber')
ValueError: invalid literal for int() with base 10: 'notanumber'
By anticipating this error (ValueError), and then catching it with the except statement, we can inform a user when our program has determined that their input did not evaluate as a number. Note that in order to catch the error with the except statement, the expression which throws the error must be evaluated by the try statement, hence:
try:
# begin code which we know will throw the `ValueError`
selection = int(raw_input('Please enter your score: '))
except ValueError:
# what to do if the `ValueError` occurs?
# tell the user that what they entered doesn't appear to be a number
print 'The value you entered does not appear to be a number !'
continue
Here is the Pseudocode
Print instructions to the user
Start with the variables high = 1000, low = 1, and tries = 1
While high is greater than low
Guess the average of high and low
Ask the user to respond to the guess
Handle the four possible outcomes:
If the guess was right, print a message that tries guesses were required and quit the program
If the guess was too high, print a message that says “I will guess lower.”
If the guess was too low, print a message that says “I will guess higher.”
If the user entered an incorrect value, print out the instructions again.
I don't even know where to begin.
Here's where you begin. Insert the specifications as documentation, then do one at a time, testing along the way.
# Print instructions to the user
### 'print "xyz"' will output the xyz text.
# Start with the variables high = 1000, low = 1, and tries = 1
### You can set a variable with 'abc = 1'.
# While high is greater than low
### Python has a while statement and you can use something like 'while x > 7:'.
### Conditions like 'x > 7', 'guess == number' can also be used in `ifs` below.
# Guess the average of high and low
### The average of two numbers is (x + y) / 2.
# Ask the user to respond to the guess
### Python (at least 2.7) has a 'raw_input' for this, NOT 'input'.
# If the guess was right, print a message that tries guesses were required
# and quit the program
### Look at the 'if' statement for this and all the ones below.
# If the guess was too high, print a message that says “I will guess lower.”
# If the guess was too low, print a message that says “I will guess higher.”
# If the user entered an incorrect value, print out the instructions again.
I've also added a small comment detailing what language elements you should look in to for each section.
You don't say if this is Python 2 or 3. The following should be good for recent versions of 2; I'm not familiar with 3, but it will probably at least get you started there too. Seeing as how this is homework, I'm just going to recommend some things for you to research.
You'll want to get the guesses and check them in a loop. I recommend looking up the while loop.
To get the user inputs, try raw_input.
To output messages, look up print.
Use if for checking the user's responses.
You begin with point one:
print "instructions to the user"
(just change the string to be more informative, that's not a programming problem!-), then continue with point two (three assignments, just like your homework assignment says), then with point three:
while high > low:
There -- that's half your work already (points 1-3 out of 6). What's giving you problems beyond that? Do you know what average means, so (say) guess = (high + low) // 2 is understandable to you, or what? That's all you need for point 4! Do you know how to ask the user a question and get their response? Look up input and raw_input... OK, I've covered the first five of the six points, surely you can at least "get started" now!-)
Ok, this isn't the answer but you need to look at the program:
Print out instructions.
Make a random number or a use your own. (For rand numbers you need to use a modulus divide trick)
Probably using a while loop: check if the number guessed is higher or lower or equal
In case of higher print higher, in case of lower print lower, in case of equal break or call exit (probably breaking will do fine).
Pseudo Code:
print "intructions"
thenumber = rand() % 1000+1
while (true)
getInput(guess);
if (guess > thenumber)
print "Guess lower"
else if (guess < thenumber)
print "Guess higher")
else
exit //or break.
Just pseudo code though.
print ("*********** Hi Lo Game ***********")
import random
x = (random.randint(1,100))
num1 = int(input("Enter your number:"))
while num1 < x:
print ("Too Low")
num1 = int(input("Enter your number:"))
while num1 > x:
print ("Too High")
num1 = int(input("Enter your number:"))
if num1 == x:
print ("Congratulations! You are Correct")
Well working Hi/Low game w/score
from random import randint
import time
print '='*20
print 'The Up / Down Game'
print 'Enter up or down !'
print 'Get 10 in a row for a reward!'
print '='*20
print "= "+'GAME START'+" ="
print '='*20
print ''
ans = ' '
score = 0
while True:
n1 = randint(2,13)
n2 = randint(2,13)
print "I have = %s" % (n1)
ans = raw_input("What do you choose: ")
if ans == 'up':
print "Your number is : "
time.sleep(0.5)
print "."
time.sleep(0.5)
print ". %s" % (n2)
time.sleep(1)
if n1 > n2:
print "Sorry you lost."
time.sleep(2)
print "Final score = %s" % (score)
time.sleep(2)
print "="*20
print "Try Again"
print "="*20
score = 0
elif n1 <= n2:
score += 1
if score > 1:
print "That's %s in a row" % (score)
elif score == 1:
print "Thats 1 point"
elif score == 10:
print "Congratz you got the reward!!!"
elif ans == 'down':
print "Your number is : "
time.sleep(0.5)
print "."
time.sleep(0.5)
print ". %s" % (n2)
time.sleep(1)
if n1 < n2:
print "Sorry you lost."
time.sleep(2)
print "Final score = %s" % (score)
time.sleep(2)
print "="*20
print "Try Again"
print "="*20
score = 0
elif n1 >= n2:
score += 1
if score > 1:
print "That's %s in a row" % (score)
elif score == 1:
print "Thats 1 point"
elif score == 10:
print "Congratz. You got the reward"
else:
tryAgain = raw_input("enter up or down only")