I am making a small interactive text game in python.
i need to check if a string, from the user, is 1234 (a number in a string that would work with int() ) or foo (just a string, python would traceback if I called int() on it)
while(True):
IN = input("[Number] >> ")
if(isNumber(IN)):
break
else:
print("Please enter a number.")
continue
IN = int(IN) #guaranteed to work at this point
someFunction(IN)
thanks in advance!
If you want to know if something is "a number in a string, one that would work with int()", you do that by just calling int:
try:
i = int(myvar)
# It's an int, and we have the value if you want it
except ValueError:
# It's not an int
This is a general case of the EAFP principle: It's Easier to Ask Forgiveness than Permission. Instead of trying to guess whether something would fail, it's usually easier to just try it and see if it fails.
That's especially try in cases where trying to guess is more complicated than it looks. For example, people always suggest using the isdigit method here, but that fails in a number of cases. For example:
isdigit is false for negative numbers, because the '-' character is not a digit.
isdigit is false for numbers with trailing whitespace (e.g., because you're not rstripping newlines from your input).
isdigit is true for hundreds of non-western digits and special-form digits that can't be used with int.
int has changed its rules at least twice between Python 2.0 and 3.4, and could always change again.
You probably could come up with a complicated rule that was exactly the same as "would work with int()" as interpreted in some specific Python version, but why, when int is obviously guaranteed to always do the same thing as int?
Related
So I am trying to write a simple code that will do the Pythagorean theorem for me after I input A, B and C but the code is skipping my While statements, and I have tried rewriting them as if statements to see if that works and again it will skip it, I need some help Please and Thank you Btw I do realize that in the picture that my while loops are open and have nothing ending them but I did have that in there at one point but I had taken them out when I changed to If statements.My Code I cant seem to understand
When you use input() the input comes as a string, and in your while loop you set your condition to be equal to 1 (as an integer).
A solution to this would be:
varname = int(input("")) #this way it converts your input into an integer
When you're taking input() from the user, it is returned as a string. Suppose user enters 1 it will be stored as "1" # which is a string. Now when you compared Yes_No == 1 it returned False because "1" == 1 is False.
So you need to parse (convert) it into a number (integer), which can be done by passing string to int() function. It will return the integer representation of that string. Do the same with all the inputs and your problem will be solved!
Another problem with your code is that you're not updating the value of Yes_No in any of the while loop. Which means that it will result in infinite loop, it will keep executing the while loop because once the condition becomes True it will not become False because value of Yes_No is not updated.
As the python documentation points out, the input function returns a string:
input([prompt])
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
If you didn't know that and you wanted to debug and figure out, you can do something like print(type(Yes_No)) and you can see that it is a string type, so when you evaluate this expression: while Yes_No == 1, it returns false.
So the fix in this situation is to change your input line to
Yes_No = int(input("Do you have the hypotenuse? For yes press 1 or for no press 2"))
The idea is, a user inputs an identification code, and, to check whether it meets a certain letter/number format, and that prohibited characters are not used in certain positions, each character is in its own variable.
number = input("What is your identification number?")
if first character is a letter:
append to list
else:
if first character number:
et cetera
First, in Python 2, input() does evaluation. To get a string, user should enter something in string syntax. E.g., input
"1234"
results in string "1234", but
1234
results in number 1234. It seems to me you need raw_input() instead. But you should notice Python3 doesn't evaluate, its input is equivalent to Python2 raw_input.
After this correction, you would get a string. If number is its variable name, number[0] is the very first character, number[1] is the second one, and so on.
I also suggest doing strip() on the string before analyzing it, because it's too typical for users to enter insignificant spaces before or after the real value.
I've been playing around with strings and I've found that when one inputs a string into a input function it gives an error.
I was wondering how to print "invalid" if a string was typed for an input variable. I want to do this the simplest way possible and the function should be the input and not the raw_input and I don't want to use try or except because that would complicate the code I'm planning to create.
testing_variable = input ("enter a number:")
# if a string is entered print invalid
if testing_variable == "":
# the "" is what im using if a string is entered and im having a hard time solving this
#Tips or advice of any coversion of the input would be helpful
print "invalid"
Using the input function in Python 2 is generally a bad idea. It is equivalent to eval(raw_input()), and thus expects the user to input a valid Python expression. If they type in something that is not valid Python, you'll always get an error.
While you could catch various exceptions and translate them into useful error messages, a better approach is to use raw_input and do your own validation for the specific types of input you want to be able to handle. If you only want to accept numbers, try converting the string you get from raw_input to int or float (and catching ValueError exceptions which indicate non-numeric input). For your desired result of printing "invalid":
try:
result = int(raw_input("enter a number"))
except ValueError:
print "invalid"
This is the most Pythonic way to solve the issue. If for some reason you don't want to use exception handling, you can save the string you get from raw_input and analyze it first to make sure it has only the characters you expect before converting it to a number. For base 10 integers this is not too hard, as only digits need to be checked for, and the isdigit method on a string will check if it contains only digit charaters:
str_input = raw_input("enter a number")
if str_input.isdigit():
result = int(str_input)
else: # string contains non-digit characters
print "invalid"
It's quite a bit more complicated to validate the input string if you want to support floating point numbers, as there's no convenient function like isdigit that will check all the characters for you. You could do it if you really wanted to, but I'd strongly recommend going with the exception catching code style shown above and just passing the string to float to see if it works.
Python 2.7 supports input and raw_input.
So, with input, you are expected to wrap your input with quotes. If you are wanting to avoid this, then use raw_input.
Example with raw_input:
>>> raw_input('hi ')
hi hey
'hey'
If you are looking to force the user to always enter a digit, then you can wrap it in a try/except as such:
try:
i = int(raw_input("Enter a number: "))
except:
print("you did not enter a number")
This is the best way in my opinion:
testing_variable = input ("enter a number:")
try:
number_var = int(testing_variable)
print(number_var)
except ValueError:
print("Invalid")
Without using try you can do:
testing_variable = input ("enter a number:")
if not testing_variable.isdigit():
print("Invalid")
I am attempting to do what should be very simple and check to see if a value in an Entry field is a valid and real number. The str.isnumeric() method does not account for "-" negative numbers, or "." decimal numbers.
I tried writing a function for this:
def IsNumeric(self, event):
w = event.widget
if (not w.get().isnumeric()):
if ("-" not in w.get()):
if ("." not in w.get()):
w.delete(0, END)
w.insert(0, '')
This works just fine until you go back and type letters in there. Then it fails.
I researched the possibility of using the .split() method, but I could not figure out a reliable regex to deal for it.
This is a perfectly normal thing that needs to be done. Any ideas?
try:
float(w.get())
except ValueError:
# wasn't numeric
It sounds like you might just need to know whether passing some string to float will give a result (i.e. it is a nice numeric value), or an error (i.e. the string doesn't represent a number). Try this:
def isnum(s):
try:
float(s)
except:
return(False)
else:
return(True)
I realise this is an old question but I've just faced this problem.
You can do something like:
if re.sub("[^0-9\\-\\.]", "", "-0.18"):
def parse(expression):
operators= set("*/+-")
numbers= set("0123456789")#not used anywhere as of now
opExtrapolate= []
numExtrapolate= []
buff=[]
for i in expression:
if i in operators:
if len(buff) >0: #prevents buff if multiple operators
numExtrapolate.append(''.join(buff))
buff= []
opExtrapolate.append(i)
opExtrapolation=opExtrapolate
else:
buff.append(i)
numExtrapolate.append(''.join(buff))
numExtrapolation=numExtrapolate
print(numExtrapolation)
print("z:", len(opExtrapolation))
return numExtrapolation, opExtrapolation
def errors():
numExtrapolation,opExtrapolation=parse(expression)
#Error for muliple operators
if (len(numExtrapolation) ==3) and (len(opExtrapolation) !=2):
print("Bad1")
if (len(numExtrapolation) ==2) and (len(opExtrapolation) !=1):
print("Bad2")
#
I posted similar code in an older question however the premise for questions is different in this post.
The code above takes a mathematical input entered in a variable expression by the user and it splits it into operands and operators. The errors function will later print errors if the input is incorrect.
Input would look something like this , where the operators can only be in the set("*/+-") and operands are real numbers. so an example input would be 45/23+233
With the help of an SO user I was able to get one of the errors to work(error for multiple operators), but I am having trouble implementing a few more error messages.
1)If the input contains items that are not numbers or not the allowed operators then an error message is displayed
2)If a user enters a number such as .23 or something like 554. where there is no number before the decimal place or after the decimal place then a different error is displayed.(note that a number like 0.23 is fine).
3)If the user attempts to divide by zero an error is displayed.
::What I have tried:
In the else statement of parse(), I tried to put conditions on buff.append(i) so that it would only run that code if buff.isdigit()==true but I got errors saying that there were no digits in buff. I also tried creating a set called "numbers"(in code below) and limiting buff.append(i) to that set through a for statement similar to the initial for statement. But unfortunately nothing worked. Any and all help would be appreciated.
Please don't introduce large amounts of code more advanced than the code below. I am trying to fix a problem, not completely change my code. Thanks for all your help.
You can use regular expressions to do these checks:
If the input contains items that are not numbers or not the allowed operators then an error message is displayed
if not re.match(r'[\d.*/+\- ]+$', expression):
print("Bad3") # Characters exist that are not allowed
Explanation: [\d.*/+\- ] will only match digits, your operators, and spaces, the + means to allow one or more of those characters, and the $ matches at the very end of the string. re.match() starts at the beginning of the string so this means that only those characters are allowed.
If a user enters a number such as .23 or something like 554. where there is no number before the decimal place or after the decimal place then a different error is displayed.(note that a number like 0.23 is fine).
if re.search(r'(?<!\d)\.|\.(?!\d)', expression):
print("Bad4") # There is a '.' without a digit before or after it
Explanation: \. in a regex matches a literal '.' character. The | in the middle is an alternation, so the regex will match if the expression on either side of it matches. (?<!\d) means that the previous character is not a number, and (?!\d) means that the next character is not a number, so this regex means "match a '.' that is not preceeded by a digit OR match a '.' that is not followed by a digit".
If the user attempts to divide by zero an error is displayed.
if re.search(r'/ *[0.]+(?![.\d])', expression):
print("Bad5") # Division by 0
Explanation: This matches / followed by any number of spaces, then one or more 0 or . characters, so this will match if anywhere in expression you have something like / 0, / 0.0, or / 0.00. The (?![.\d]) means that the next character can't be a digit or ., which will prevent you from matching something like / 0.4.
I will give you some indications, but not solve it for you :).
If you need more, ask a precise question and I'll answer it.
The answers I give you are NOT directly related with your code.
You can test if a string variable can be an integer by trying to cast it :
try:
var2 = int(var)
I let you see what Error it gives
For a version that doesn't use try, you can look at the isdigit method
You can see if a string variable if one of your operator by checking it
if (var in ["+", "-", "/", "*"])
to check even more, you can look at the variable's length first
if len(var) != and ... see above
To check if a user inputs something like .543 and refuse it, and can look at the first element of your string variable :
if myvar[0] is ".":
To check if your user wants to divide by 0, you can simply check whether the last number is equals to 0
if int(myvar) == 0:
All these expect you to be able to get operators and numbers first though.
The other solution would be to use regular expressions to perform these checks before parsing your numbers and operators.
It seems quite complex compared to the exercise you are trying to achieve though as it is homework. Might be a good idea to look at them anyway.