[英]AttributeError: 'int' object has no attribute 'isdigit' from user input
I'm running python 3 in the default IDE. 我在默认的IDE中运行python 3。
Here is my code: 这是我的代码:
def print_():
f = open("height.txt","r")
content = f.read()
print(content)
f.close()
main()
def main():
name = str(input("What is your name?"))
data = int(input("How tall are you? (CM)"))
if data.isdigit() == True:
print("\n")
elif data.isdigit() == False:
print("Must be a number!")
main()
# a+ is read only mode
f = open("height.txt","a+")
f.write(name)
f.write(str(data))
f.write("cm, ")
f.close()
data_1 = str(input("1 = View Contents. Other = Quit"))
if data_1 == '1':
print_()
else:
print("Exiting")
main()
You're trying to check isdigit()
on data you already casted to int. 您正在尝试检查已转换为int的数据的
isdigit()
。 Read it in as a str
then cast it once you've checked it's a digit: 作为
str
读入,然后在检查到数字后将其转换:
def main():
name = str(input("What is your name?"))
data = str(input("How tall are you? (CM)"))
while !data.isdigit():
print("Must be a number!")
data = str(input("How tall are you? (CM)"))
print("\n")
data = int(data)
print("\n")
this loop will continue to ask for an int until provided with one, then cast it as int 该循环将继续请求一个int,直到提供一个int,然后将其强制转换为int
The issue is that isdigit operates on a string; 问题是isdigit在字符串上操作; however you cast the data object to an int already: data = int(input("How tall are you? (CM)")).
但是,您已经将数据对象强制转换为int了:data = int(input(“您有多高?(CM)”))。 You should let the data be a string if you want to use the isdigit function.
如果要使用isdigit函数,则应让数据为字符串。 data = str(input("..."))
数据= str(input(“ ...”))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.