New to Python (2.7). I'm trying to collect a user input that can either be an int or string (I'm assuming this is possible, though I'm not 100% sure). When I get to the statement that I've posted below, any number I enter prints the 'Invalid input' message and prompts me for a user input again, even if it's within the range I want it to be. Entering 'q' still works properly and returns if entered.
I've tried changing that first if statement to read (0 <= collectEyesBlade <= 9) ... with no luck either.
while True:
collectEyesBlade = raw_input(
"\nEnter desired blade number: ")
if collectEyesBlade in [range(0,9)]:
break
elif collectEyesBlade.lower() == 'q':
return
else:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
Since raw_input returns a str, start with the comparison that uses another string. Then, try to convert it to an int. Finally, if that succeeds, try the integer comparision.
while True:
collectEyesBlade = raw_input("\nEnter desired blade number: ")
if collectEyesBlade.lower() == 'q':
return
try:
collectEyesBlade = int(collectEyesBlade)
except ValueError:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
if collectEyesBlade in range(0,9):
break
if collectEyesBlade in [str(x) for x in range(0,9)] - this should work since collectEyesBlade is a string so we need to compare it to a string
You've hit at two of the little quirks of Python. One: a range is itself an iterable, but it's possible to put an iterable inside of another iterable.
In other words, your statement
if collectEyesBlade in [range(0,9)]:
is checking to see whether collectEyesBlade is an item in the list, which has only one item: a range iterable. Since you're not entering a range iterable, it's failing.
You can instead say
if collectEyesBlade in list(range(0,9)):
which will turn the range iterable into an actual list, or just
if collectEyesBlade in range(0,9):
Either should do what you intend.
However, as another answerer has mentioned, that's only half the problem. If your input were actually possibly integer type, the above would be sufficient, but you're asking for a string input. Just because the input is a "1" doesn't mean it's not a string one.
There are a couple of options here. You could do a try-except converting the string input into an integer, and if it fails because the string can't be converted into an integer, move on; or you could convert the range/list of numbers to compare to into strings.
Related
I am currently working on the pseudocode of a project and it has just come to mind that, while I have a way of checking if User Input is strictly numerical, I have no idea of how to check if the input is strictly Alphabetical.
For Example:
def valueCheck_Int(question):
while (True):
try:
return int(input(question))
except:
question = "That is not a valid integer, try again: "
def main():
userInput = valueCheck_Int("Enter an integer: ")
print(userInput)
main()
This piece of code checks if the user's input is strictly numerical, and will only break the loop until the user has entered an integer.
Is there any possible way to do this, but with string input being alphabetical, with no numbers at all?
The str type in Python have methods for checking it, you don't need try, except at all.
These methods called isnumeric and isalpha.
isnumeric - If a string is a number, it'll return True, otherwise return False.
isalpha - If a string is alphabetical, it'll return True, otherwise return False.
Code Example:
string = 'alphabetical'
if string.isnumeric():
print('String is numeric!, it contains numbers and valid for integer casting!')
elif string.isalpha():
print('String is alpha!, it contains alphabetical letters.')
I need to accept a number from the user and print the sum. I want the object defined to accept the characters entered by the user to be of integer type only.
I do not want to check the type of the object after the value is entered. I would like a method by which the program doesn't even accept strings or other data types, only integers.
I'm quite sure you'd be fine with try/except and converting the user's input to an int:
# Repeat until a "break" is issued
while True:
number = input('Enter number: ')
# Attempt to convert the input to an integer
try:
number = int(number)
# If there was an error converting...
except ValueError:
print("That's not a number! Try again.")
# Break the loop if no error, i.e. conversion was successful
else:
break
I want to check if a user entered a number as percent format (18.06) instead of decimal format (0.1806), and always convert to decimal format.
Currently, I check to see if the value > 1, and if so, divide by 100. This works in my use case, but I can imagine some edge cases where it doesn't work. Is there a better solution?
UPDATE: let's assume it's a float, and therefore all strange characters, i.e. %s, have been removed.
Since you likely take the user input as a string(?) you could check the last digit to see if it is a "%"
if user_input[-1] == "%":
user_val = float(user_input[:-1]) / 100.0
else:
user_val = float(user_input)
assuming that you want to keep the original str value as well, otherwise use the same var.
It would be preferable imho to be explicit with the users as to the format that you want the input to be, as (pointed out by #pushkin) vals can be 0.5% as a valid input.
to be clear about the format of the input, then perhaps
while True: # if Py2.7 use raw_input instead of input
user_res = input("For 5% please enter 5. For 44.7%, please enter 44.7")
try: # handle invalid input that is not a number
user_val = float(user_res)
if (user_val >100) or (user_val < 0): # check upper and lower bound
print("Invalid entry- outside bonds")
else:
confirm = input("{}% to be recorded as your entry- confirm (Y/n) ".format(user_val))
if confirm.upper == "Y":
break
else:
print("Please try again")
except:
print("Invalid entry- nAn")
Someone downed me for this answer even though it's the only one and not marked as duplicate, so if you find it useful please upvote- thanks.
Below is a piece of code from Python which has been bothering me for a while.
var=0
while (var <1 or var>100):
var=raw_input('Enter the block number ')
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
The problem is that the while loop iterates continuously without breaking. Can anyone help me how to break the loop.
Is there any way to implement a do..while in Python?
The problem is that raw_input returns a string. You're comparing a string with an integer which you can do in python 2.x (In python 3, this sort of comparison raises a TypeError), but the result is apparently always False. To make this work you probably want something like var=int(raw_input('Enter the block number'))
From the documentation:
objects of different types always compare unequal, and are ordered consistently but arbitrarily.
You're needlessly checking var twice, and you're trying to compare int and str (because raw_input returns a string), which doesn't work right. Try this:
var=0
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
You should convert your string to int.
var=0
while (var <1 or var>100):
# I changed here
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
You're running into an issue that strings (as returned by raw_input) are always greater than integers:
>>> "25" > 100
True
You need to convert your input to an integer first:
var = int(raw_input("Enter the block number "))
Of course, you'll want to be resilient in the face of bad input, so you'll probably want to wrap the whole thing in a try block.
hello you need to enter "break" and also var should be an integer, see below
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
continue
hope this helps
I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'