【发布时间】:2021-05-24 11:13:53
【问题描述】:
编辑: 这篇文章与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
我试图用“继续”让它回到开头,但它对我很生气。您可能会说我是一个完整的新手,这是我的第一篇文章。请不要太用力地撕扯我。 :(
【问题讨论】:
标签: python input types while-loop continue