Getting an Integer Input in a Range - python

I'm trying to take a raw input and detect whether it is in a range.
Here's my code.
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if next == int in range(50):
how_much = int(next)
else:
dead("Man, learn how to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
When I enter a number it gives me the else: "Man, learn how to type a number."
I guess the line that isn't working is "if next == int in range(50):
Could anyone help me out?
Thanks in advance!
Edit:
I'm a noob so that line was just me ballparking.
I thought it would check next to see if it was an integer in the range of numbers 0-50.

If you want to "get an integer input in a range", you'll need two things:
Check if the input is an int
Check if it's in your range
Check if the input is an int
try/except will be perfect here:
n = raw_input('> ')
try:
n = int(n)
except ValueError:
dead() # or what you want
Why this is good?
Because if n is an int you'll have it convert it to an integer and if it's not an exception get raised and you can call your dead() funcion.
Check if it's in your range
If you get to this point it means that the exception before it was not raised and n was converted to an integer.
So you just need to do:
if 0 <= n <= 50:
print 'You win'
else:
print 'You lose'
Don't do:
if n in range(50):
# ...
Beacuse it will build a list of 50 numbers for nothing.
Note: don't use next as a variable, beacuse it'll shadow the built-in next()

Since raw_input returns a string, you need to convert to an int first. Try replacing the line with this:
if int(next) in range(50):

The result of raw_input() will be a string, so first you need to check to see if next is all digits. There are a few ways to do this, the easiest is to use the str.isdigit() function:
next = raw_input("> ")
if next.isdigit():
how_much = int(next)
else:
dead("Man, learn how to type a number.")
Note that you do not need to check to see if the value for next is in the range from 0 to 50, since your next if statement already checks to see if the value is less than 50 and negative numbers will be excluded by next.isdigit().

The test "next == int in range(50)" evaluates to "(next == int) and (int in range(50))" which is fairly meaningless and always equates to false.
Instead you could try
try:
how_much = int(next)
if not (0<=how_much<50):
print 'Too greedy'
except ValueError:
dead("Man, learn how to type a number.")

Using try .. except will allow you to make sure entered value is an int. # raise is a place holder for your handling a non-int contition:
try:
next = int(raw_input("> "))
except ValueError:
# raise
if not 0 <= next <= 50:
print 'Too greedy'

Related

Python: random number game with input validation

I'm writing a program that is a guessing game where the user has one chance to guess a number between 1 and 20.
There are two problems with the code:
Number one is still the input validation. The firstGuess variable is actually in main().
firstGuess = userguess()
def userGuess():
while True:
try:
guess = int(input('Enter a number between 1 and 20: '))
if 1 <= guess >= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break
What I'm trying to do is put the input validation in a loop (while True:) until the user gives good input (in this case a positive number between 1 and 20). If the user were to enter 'd', or '-5', the program should continue looping until good input is given. However, this is not the case. By adjusting the code, I have been able to ask for the input again once bad input is entered, but if bad input is given a third time I get "another exception occured while handling this exception."
*Removed other problem, #Henry Woody was correct in that I wasn't using the conditionals correctly.
The issues are with the conditionals.
The first is the line:
if 1 <= guess >= 20:
in userGuess, which is checking for a number greater than or equal to 20, which is not what you want. You can fix this issue by changing the condition to:
if 1 <= guess <= 20:
Next, the conditional:
if guess1 == randomOne or randomTwo or randomThree:
checks whether guess1 == randomOne or if randomTwo is truthy or if randomThree is truthy. It does not check if guess1 == randomOne or guess1 == randomTwo or guess1 == randomThree as intended. You can fix this by changing the condition to:
if guess1 in [randomOne, randomTwo, randomThree]:
to check if guess1 is equal to either of the three random variables.
Edit:
There is also an issue in the try/except block. If the user enters a non-digit character in the input, a ValueError will be raised before guess is defined. But then guess is referenced in the except block, but guess isn't defined at that point.
You can fix this by getting the user input and then, separately, trying to convert the input to an int.
Here's an example:
while True:
guess = input('Enter a number between 1 and 20: ')
try:
guess = int(guess)
if 1 <= guess <= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break

Why do I get "ValueError: invalid literal for int() with base 10". in this Python code?

I'm a beginner trying to improve my Python skills. I've found a very similar question to mine but since the source code was different, it did no benefit. Here is the link for the question: ValueError: invalid literal for int() with base 10: ''
Anyways, here is my code:
correct_answer= 41
guess = int(input("Guess the number"))
if int(input()) == correct_answer:
print ("You found my number!")
if int (input()) >= correct_answer:
print ("My number is lower.")
if int (input()) <= correct_answer:
print ("My number is higher.")
else:
print ("You didn't write any numbers!")
Here, I wanted to write a simple guessing game. The number computer has in mind is 41, and the user has to guess the number after "Guess the number". If the input of a user is greater than 41, the program says "My number is lower" and if the input is smaller than 41, the program says "My number is greater."
When I run this code, I get the "ValueError: invalid literal for int() with base 10: ''
Thank you in advance for helping me solve this problem :)
The problem is that you are calling input() again and again. Everytime you do this, the program expects input and the user has to retype their guess in order for the program to work as intended. Replace all instances of int(input()) (with an empty prompt) with guess, and you'll see more reasonable behavior. E.g.
if guess == correct_answer:
print ("You found my number!")
Try this -
correct_answer= 41
guess = raw_input("Guess the number")
try:
guess = int(guess)
except ValueError:
print "Wrong value entered"
if guess == correct_answer:
print ("You found my number!")
elif....
Let me know if that helps
When you take the input and someone enters an alphabet or something which is not an integer, and you try to typecast it, python will throw a ValueError.
To catch such cases, we use try except block will catch it. More about python try except in python
Couple of pointers about your code -
if int(input()) == correct_answer:
here, you are just calling input() function and your program will not work, use variable guess, this is the variable you have put your input into.
and
if int(input()) == correct_answer:
print ("You found my number!")
if int (input()) >= correct_answer:
print ("My number is lower.")
if int (input()) <= correct_answer:
print ("My number is higher.")
Use python's if elif elif else instead.
Also, since you have typecasted to integer already, you don't need to do that with every if condition, this would suffice -
if input > correct_answer and you don't need >= or <=.
>= means greater or equal, but you have handled the equal case in first condition, if it's equal, it'll be caught there, similar with less than or equal

Check for a string in if-statement

I have a program with some user inputs and I need to check if what the user entered was a string or an integer value between 1 and 10 million.
My code looks like this (simplified):
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if inp < 1:
print "Must be higher than 1"
continue
elif inp > 10.000.000:
print "Must be less than 10.000.000"
continue
elif 'inp is a string': #here's my problem
print "Must be an integer value!"
continue
else:
'execute the rest of the code'
I don't know how to solve this. My program always terminates when I enter a string by mistake.
Thank you!
First, you're using Python 2, which will happily compare strings to integers. You don't want to do that. Secondly, raw_input() will always return a string. What you're hoping to do is check if that string could possibly represent a number. Third, 10.000.000 is improper syntax. Don't use separators. Fourth, you only need to continue if you want to go to the top of the loop early. If everything's in an if..elif..else block at the end of the loop, only one of those will be executed, so you don't need to put a continue at the end of each branch. You can use continue statements or restructure your branch. Finally, don't use in as a variable name, because that's a Python keyword.
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if not inp.isdigit():
print "Must be an integer value!"
continue # each of these continue statements acts like a "failed, try again"
inp = int(inp)
if inp < 1:
print "Must be higher than 1"
continue # same for this one
if inp > 10000000:
print "Must be less than 10.000.000"
continue # and this one
# execute the rest of the code
You can use .isdigit() to check if string consists of numbers to make sure it can be convertible to integer:
while True:
in = raw_input("Enter a value between 1 and 10 million: ")
if in.isdigit():
number = int(in)
if number < 1:
print "Must be higher than 1"
continue
elif number > 10**6:
print "Must be less than 10.000.000"
continue
else:
'execute the rest of the code'
else:
print "Must be an integer value!"
continue
I have no idea how you came up with your code but here are different suggestions:
Don't use "in" as variable name because it's a python operator.
After the input you can check whether it is an int or a string.
Your program can look like this:
while True:
try:
input_int = int(raw_input("Enter a value between 1 and 10 million: "))
if input_int < 1 :
print "Must be higher than 1"
elif input_int > 10**7:
print "Must be less than 10.000.000"
except:
print "Must be an integer value!"
else: #You can use else with try/except block
#'execute the rest of the code'
VoilĂ 

I'm really new to Python, and I was wondering why my "Else:" isn't working

import random
number = 50
guess = raw_input("Try to guess my number...")
while guess!=number:
if guess>number:
print "Lower"
elif guess==number:
print "Correct, you win!"
else:
print "Higher"
guess = raw_input("Try again...")
I'm really new, and I'm wondering why it won't display "Higher" when the number I input is less than the number, plus, how can I make the number random, since randrange(1,100) won't work
It's not working because raw_input returns a string.
"50" == 50 # False!
You will need to ensure you are checking for equality of the same types. Try converting to an int first:
int(raw_input("Try to guess my number..."))
Of course this will throw an exception if you try to convert a non-numeric string to an int, so you will need some error-handling as well:
valid_num = False
while not valid_num:
guess = raw_input()
try:
guess_num = int(guess)
valid_num = True
except ValueError:
print "Please enter a valid number"
while guess!=number:
if guess>number:
print "Lower"
elif guess==number:
print "Correct, you win!"
else:
print "Higher"
First of all when you use raw_input("Try to guess my number...") ir returns a string and str!=int in any case so you were running an infinite while guess!=number: loop, as the condition would always hold true for comparison of a string and an integer.
Another thing was contradicting statements of while and elif, when you are running a while condition with while guess!=number: then how can you expect this elif guess==number: statement to run inside the while statement , So the answer would be handle this case outside the while loop.
import random
number = 50
guess = int(raw_input("Try to guess my number..."))
while guess!=number:
if guess>number:
print "Lower"
else:
print "Higher"
guess = int(raw_input("Try again..."))
print "Correct, you win!"
raw_input returns a string. You will want to convert that to an int for your comparison:
guess = int(raw_input("Try to guess my number..."))
a str will never == an int
About your randrange problem:
You should use random.randint(a,b) instead. It chooses a random integer between the number a and b (exclusive, I think.)

Python program not accepting decimal raw input

I am working on small python payroll project where you enter employee name, wage, and hours worked. When I enter decimals for the wage input, I am getting "invalid entry" because of my exception handling. Why are decimals being returned as invalid? Also, how can I loop this program so that it keeps the same 3 questions until the user types "Done"?
Any help will be greatly appreciated!
Thanks!
import cPickle
def getName():
strName="dummy"
lstNames=[]
strName=raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
def getWage():
lstWage=[]
strNum="0"
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intWage=int(raw_input("Enter employee's wage: "))
if intWage >= 6.0 and intWage <=20.0:
lstWage.append(float(strNum)) #convert to float
blnDone=True
else:
print "Wage must be between $6.00 and $20.00"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getHours():
lstHours=[]
blnDone=False
while blnDone==False: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if intHrs >= 1.0 and intHrs <=60.0:
blnDone=True
else:
print "Hours worked must be 1 through 60."
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
def getDone():
strDone=""
blnDone=False
while blnDone==False:
try:
srtDone=raw_input("Type \"DONE\" if you are finished entering names, otherwise press enter: ")
if strDone.lower()=="done":
blnDone=True
else:
print "Type another empolyee name"
except(ValueError): #if you have Value Error exception. Explicit on error type
print "Invalid entry"
##### Mainline ########
strUserName=getName()
strWage=getWage()
strHours=getHours()
srtDone1=getDone()
Here's the core of it:
>>> int("4.3")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.3'
You can't convert a string to an integer if it's not an integer. So when you do intWage=int(raw_input("Enter employee's wage: ")) it throws the ValueError. Perhaps you should convert it directly to float.
Because you're converting the input to int:
intWage=int(raw_input("Enter employee's wage: "))
You are assuming that the wage is an integer, which by definition does not have a decimal place. Try this:
intWage=float(raw_input("Enter employee's wage: "))
Try using
intWage=int(float(raw_input("Enter employee's wage: ")))
This will accept a decimal number as input.
Error w/ Floats
As others said before, you are assuming the input will be a float. Either use float() or eval()instead of int():
intWage = float(raw_input("Enter employee's wage: "))
Or use input() instead of int(raw_input()):
intWage = input("Enter employee's wage:")
Both will accomplish the same thing. Oh, and change intWage to floatWage atleast, or even better, don't use Hungarian Notation.
The Code
As for your code, I did a couple of things:
Used break and/or return to terminate loops instead of keeping track of booleans (that's the whole purpose of the break and continue statements)
Changed intWage to floatWage
Rewrote number comparisons in a more concise way (x <= y and x >= z can be written as z >= x >= y)
Added return statements. I don't get why you didn't put them yourself, unless you wanted to assign None to strUserName, strWage and strHours)
Added a loop as you requested when asking for an employee's details.
Modified getDone() to work w/ the loop.
import cPickle
def getName():
strName = "dummy"
lstNames = []
strName = raw_input("Enter employee's Name: ")
lstNames.append(strName.title() + " \n")
return strName
def getWage():
lstWage = []
strNum = "0"
while True: #Loop to stay in program until valid data is entered
try:
floatWage = float(raw_input("Enter employee's wage: "))
if 6.0 <= floatWage <= 20.0:
lstWage.append(floatWage)
return floatWage
else:
print "Wage must be between $6.00 and $20.00"
except ValueError: #Catches ValueErrors from conversion to float
print "Invalid entry"
def getHours():
lstHours = []
while True: #loop to stay in program until valid data is entered
try:
intHrs=int(raw_input("Enter number of hours worked: "))
if 1.0 <= intHrs <= 60.0:
return intHrs
else:
print "Hours worked must be 1 through 60."
except ValueError: #Catches ValueErrors from conversion to int
print "Invalid entry"
def getDone():
strDone = ""
while True:
srtDone = raw_input('Type "DONE" if you are finished entering names, otherwise press enter: ')
if strDone.strip().lower() == "done":
return True
else:
print "Type another empolyee name"
while not getDone():
strUserName = getName()
strWage = getWage()
strHours = getHours()
An Example of break and continue
The break statements inside a loop (for and while) terminate the loop and skip all 'else' clauses (if there are any).
Thecontinue statements skips the rest of the code in the loop and the continues the loop as if nothing happened.
The else clause in a for...else construct, executes its code block when the loop exhausted all the items and exited normally, i.e., when it's not terminated by break or something.
for no in range(2, 10):
for factor in range(2, no):
if no % factor == 0:
if factor == 2:
print "%d is even" % no
continue
# we want to skip the rest of the code in this for loop for now
# as we've already done the printing
print "%d = %d * %d" % (no, factor, n/x)
break
# We've asserted that the no. isn't prime,
# we don't need to test the other factors
else:
# if 'break' wasn't called
# i.e., if the loop fell through w/o finding any factor
print no, 'is a prime number'

Categories