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.')
Related
#user inputs a number
number = input("Enter number: ")
# 1) changes dot and creates a new string,2) verifies is it a number
if(not number.replace(".","").isnumeric()):
print("Sorry number is not numeric")
Generally replace changes old value with a new one.
isnumeric returns True if and only if every character of the string is a numeric character as defined by Unicode. Periods are not numeric, but many characters that contain or represent numbers, such as ½ or 六, are considered numeric.
First, you probably want isdigit instead, because a lot of the numeric characters in Unicode aren't valid in float numbers. isdigit only returns True if every character is one of the ASCII digits 0-9.
Second, to validate if the input is a float, it's "Better to Ask Forgiveness than Permission": try converting it as a float directly, and see if that fails:
try:
float(number)
except ValueError:
print("Sorry number is not a float")
number = input("Enter number: ")
if(not number.replace(".","").isnumeric()):
print("Sorry number is not numeric")
Replace here change dot, creates a new string and makes isnumeric() to be True for float numbers.
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.
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'm making a calculator on Python 3.4. The calculator will ask the user to enter a number. I want to restrict this so they can only enter a number (which I am fine about) or to press the 'C' key to clear the calculator. I seem to be getting stuck with allowing the C as well as any integer. Anyone suggest any way of going about this?
Thanks
You could use this code, assuming the user shall be able to enter numbers consisting of several digits like 1337, but no decimal points. Inputs being mixed of digits and "C" are invalid, "C" only gets detected if the input contains only the letter "C" and nothing else. Leading and trailing whitespaces are ignored.
def get_input():
inp = input("Enter a number or 'C' to clear: ").strip()
if inp.upper() == "C":
return "C"
if inp.isdigit():
return int(inp)
else
return None
This function will return the entered number as integer, or the string "C", or None if the input was invalid.
Assuming you're taking in the user inputs one by one:
import string
allowed = string.digits+'C'
if input in allowed:
doSomethingWith(input)
Is this what you're looking for?
I am trying to create a list where I need to input numbers as strings in one list and I am trying to do it with a while loop.
while input_list[-1] != "":
input_list.append(raw_input())
However when numbers are entered they are returned as u'X', X being the number entered. I cannot perfrom mathematical calculations on these numbers.
I would usually use str() or int() but I cant generalise in this case.
Is there a cleaner way to remove the u' ' prefix than simpley using if statements?
The "u'' prefix" is trying to indicate the type of the value. You have strings here, not numbers. If you want to do math, you need to convert your strings to numbers. If they happen to enter a string that can't be converted to a number, you should tell the user what happened
user_typed = raw_input()
try:
user_number = float(user_typed)
except ValueError:
print "Couldn't convert this to a number, please try again: %r" % user_typed
See also: LBYL and EAFP