How to get a string value in input as invalid? - python

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")

Related

Searching for string and outputting the column

So, I'm trying to make someone input a string and make python search for the string in the first column, if found then output the entire row.
How'd I go about doing this? (using gspread)
If I understand your question correctly this is the code:
line = ("abcd")
try:
string = input("Please enter a string: ")
if string in line:
print(line)
else:
print("Your input is not in line.")
except ValueError:
print("An error has occured")
The in statement checks to see if the input is in the text and if it is then it prints it out. (You have to change line to match what you want and for multi-line use """ text """). The try and except statements make the program more robust - especially if you can only enter numbers (integers or floats). It won't crash thus is a good habit to get into. You can google the suffixes for except as there is quite a few.

How to count the number of user input at stdin in python

Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.
I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:
count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2
But the program fails with:
ValueError: invalid literal for int() with base 10: 'Sina dumb\n'
depending on if I leave the newline in or not.
Please what am I doing wrong, and how can I make it better?
In python2.x or python 3.x
sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.
I think you need this(assuming)
import sys
input_var = input() # or raw_input() for python 2.x
# entering Sina dumb
>>>print(len(input_var.split()))
2
Update
If you want to count how much input you enter.Try this
import sys
from itertools import count
c = count(1)
while True:
input_var = input()
print ("you entered " + str(next(c)) + " inputs")
On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)
On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.
input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.
you could try regular expression:
import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)

Check if a variable is a string of numbers like "1234"

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?

How can I check if the users input is a number?

I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.

Python program isn't displaying an output [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I determine if user input is a valid hexadecimal number?
Python - Program not displaying as intended
#Hex Check
def Check(HexInput):
while True:
if HexInput in Valid:
print('That is a valid hex number.')
else:
print('That is an invalid hex number.')
return HexInput
HexInput=input('Enter a hex number: ')
Valid='1234567890ABCDEFG'
Program needs to contain Check(). It should ask the user to input a hex number and tell them whether it's a valid hex number or not.
First of all,
while False:
will never execute. You can use "while True:" or "while checked == False:" but not "while False:"
Your Check() function must also take in parameters so that it looks like
def Check(UserInput, Valid):
You also need an additional "if" statement because even if the user inputs an invalid hex value, the program will still print "That is a valid hex value."
Next,
return Check
does not make sense as you do not have any variable named "Check"
Finally, you must actually call your function like so:
Check(UserInput, Valid)
It is not clear what you want to do in your program but for start , while False: mean that the code in the while loop will always be ignored (not executed)
The body of the while False: will never execute.
while False:
print("You will never enter this loop.")
.
.
.
This will execute, but you have to make sure you test for a condition,
so you can break out of the loop. That is you do not want to loop endlessly.
while True:
print("You will enter this loop.")
print("Make sure you test for a condition that will let you "break".)
break
Edit: You asked me to check your program. There are still some problems.
Use raw_input instead of input. The Python Tutorial at http://docs.python.org suggested raw_input.
The way you've written your program, if you have a multi-digit number, you'd need to check each digit, and that's what Python's for is for.
I've written something crude. In my version you'd test for 0 or non-zero. If
zero, you don't have a hex number. I'm sure there is a more elegant way to do this.
I strongly suggest fiddling with code in the Python command line. That's what it's for.
def Check(HexInput):
valid_hex_digit = 0 #Assume invalid
for digit in HexInput:
if digit in Valid:
valid_hex_digit = valid_hex_digit + 1
else:
error_str = "Invalid hex digit " + str(digit) + " found."
print(error_str)
valid_hex_digit = 0
break
return valid_hex_digit

Categories