编辑: 这篇文章与Asking the user for input until they give a valid response不同,因为我不会根据响应的数据类型结束循环。字符串和整数都是有效的。只有当两个条目是不同的数据类型时,循环才会回退
我试图通过input()收集两个单词或两个整数如果两个值都是整数我想计算answer1**answer2.
如果两个值都是非整数,我想连接字符串。最后,如果数据类型不匹配,我希望将用户发送到开头以输入两个新值
这是我的尝试。我为你将要看到的事提前道歉
## collect first value
print("Please type a word or an integer:")
answer1 = input()
## check for blanks
if answer1 == "":
print("Blank space detected. Please retry.")
answer1 = input()
## collect second value
print("Please type another word or integer:")
answer2 = input()
## check for blanks
if answer2 == "":
print("Blank space detected. Please retry.")
answer2 = input()
## define test for integer status
def containsInt(intTest):
try:
int(intTest)
return True
except ValueError:
pass
## check for matching data types and produce final value
if containsInt(answer1) == True:
containsInt(answer2)
if containsInt(answer2) == True:
finalInt = (int(answer1))**(int(answer2))
print("\n")
print(finalInt)
else:
print("Sorry, the data types must match - both words or integers.")
continue
else:
containsInt(answer2)
if containsInt(answer2) !=True:
print("\n")
print(answer1 + answer2)
else:
print("Sorry, the data types must match - both words or integers.")
continue
我试图用“continue”让它回到开头,但它对我很生气。你可能知道我是个十足的新手,这是我的第一篇帖子。请不要对我太苛刻(
continue
仅适用于循环,即for
和while
。您试图在循环之外使用continue
,这就是Python不喜欢它的原因您可以做的一件事是检查数据类型是否匹配,然后基于此执行操作:
默认情况下,Python将输入视为}比
string
,因此即使为输入指定一个数字,它也将是string
类型。您可以通过多种方式解决此问题,其中之一是尝试将输入转换为数字^在本例中,{int
工作得更好,因为否则您无法很好地处理小数。例如:这样做的目的是尝试将默认输入的字符串转换为浮点数,如果这不起作用,那么它将保持为字符串
这应该起作用:
请注意,如果您输入像
1.5
这样的数字,它将被视为字符串。 因此输入1.5
和a
将导致1.5a
相关问题 更多 >
编程相关推荐