I'm currently coding a text based game in python in which the narrative will start differently depending on answers to certain questions. The first question is simple, a name. I can't seem to get the input to display in the correct text option after the prompt.
I tried using
"if name is True"
and
"if name is str"
but they both skip to the else option, instead of displaying the correct option after input.
while True:
try:
# This will query for first user input, Name.
name = str(input("Please enter your name: "))
except ValueError:
print("Sorry, I didn't understand that.")
# No valid input will restart loop.
continue
else:
break
if name is str:
print("Ah, so " + name + " is your name? Excellent.")
else:
print("No name? That's fine, I suppose.")
So if I enter John as my name, I'd expect the output to be "Ah, so John is your name? Excellent."
But instead I enter John and it outputs:
Please enter your name: John
No name? That's fine, I suppose.
Any help would be appreciated. Thanks.
The exception handling around input
is not required as the input
function always returns a string. If the user does not enter a value an empty string is returned.
Therefore your code can be simplified to
name = input("Please enter your name: ")
# In python an empty string is considered `False` allowing
# you to use an if statement like this.
if name:
print("Ah, so " + name + " is your name? Excellent.")
else:
print("No name? That's fine, I suppose.")
Further regarding usage of is
:
is
is used to compare identity as in two variables refer to the same object. It's more common use is to test if a variable is None
eg if name is None
( None
is always the same object). As mentioned you can use type(name)
to obtain the type of variable name but this is discouraged in place of the builtin check isinstance
.
==
on the other hand compares equality as in if name == "Dave"
.
isinstance
does more than just check for a specific type, it also handles inherited types.
问题是您要检查name是否为str,而不是type(name)是否为str。
if type(name) is str:
use isinstance
instead of is
. And, You do not need to use str(input())
because input
returns str
.
while True:
try:
# This will query for first user input, Name.
name = input("Please enter your name: ")
except ValueError:
print("Sorry, I didn't understand that.")
# No valid input will restart loop.
continue
else:
break
if isinstance(name, str):
print("Ah, so " + name + " is your name? Excellent.")
else:
print("No name? That's fine, I suppose.")
The result is:
Please enter your name: John
Ah, so John is your name? Excellent.
But, You have to use string.isalpha()
if you want to check whether name
is real name in consist of alphabets.
if name.isalpha():
print("Ah, so " + name + " is your name? Excellent.")
else:
print("No name? That's fine, I suppose.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.