+ 2
Can't properly check if the variable is a string or not.
x = input("Enter a name: ") if type(x) == str: print("Access granted!") else: print("Error: please enter a name") # Why does this code gives me "Access granted" when I type in a number? How to fix it?
9 Réponses
+ 9
input() always return string, use int(input()) or float(input()) to transform input into numeric form.
+ 7
You don't need to use int() or float() if you're only expecting string input. I was only pointing out that your decision making branch (if) will always return true, because input() returns a string, so even if you type a number it will be transformed into its string representation.
e.g. 2018 → "2018".
I hope you understand : )
+ 5
I guess this discussion on SO is related to your question, you might want to take a look at it:
https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number
Hth, cmiiw
+ 4
sorry didn't finish typing, you'll want to create a forloop or whileloop checking each character and using .isdigit() here is an example:
https://code.sololearn.com/cHValtYPTC4e/?ref=app
sorry doing this on the phone is not that easy for me
+ 3
it will always be a string, the only way to make it an int is by putting int(input("enter a name: "))
+ 3
and if you want, you can do x.title().strip() to remove any empty spaces before/after the name while capitalizing the first letter of the name, but it's your preference
+ 3
You can use mystring.isalpha(), which returns True if mystring contains only alphabetical characters, otherwise returns False.
if x.isalpha():
print("It's a name")
else:
print("Not a name")
But then it will return False for strings that contain whitespace. Then you'd have to first split the input word-by-word, then test each word.
list_of_words = x.split(' ')
If your only problem is input numbers, you can use mystring.isdigit().
if x.isdigit():
print("You entered a number!")
else:
print("All good")
It would also be nice to use a while loop instead of if/else, so the person has more than one chance of inputing a name.
x = input("Enter a name: ")
while x.isdigit():
print("That's a number!")
x = input("Enter a name: ")
print("That's a name")
But I'm not sure how that would look on SoloLearn.
0
why would I make it int(input("enter a name: ")? The code says enter a name, not a number.
0
how do I fix the program in a sense that when someone enters a number instead of a name it will give him a message stating that he must enter a name?