我的任务如下:
给定三个整数。确定其中有多少个彼此相等。程序必须打印以下数字之一:3(如果所有数字都相同)、2(如果其中两个相同且第三个不同)或 0(如果所有数字都不同)。
我想我可以做一个 def 函数来检查输入是否都是整数而不是浮点数或字符串。虽然程序在仅输入整数的情况下可以工作,但它会卡在 my 上,除非输入另一种类型
def valuecheck(checker):
loopx = True
while loopx:
try:
#first it checks if the input is actually an integer
checker = int(checker)
loopx = False
return(checker)
#if input isn't an integer the below prompt is printed
except:
input("Value isn't a valid input, try again: ")
varA = input("please input an integer: ")
varA = valuecheck(varA)
x = varA
varB = input("please input anther integer: ")
varB = valuecheck(varB)
y = varB
varC = input("please input another integer: ")
varC = valuecheck(varC)
z = varC
if x == y == z:
print(3,"of the integers are of the same value")
elif x == y or y == z or x == z:
print(2,"of the integers are of the same value")
else:
print(0, "of the integers are of the same value")
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的代码。它应该能够告诉用户是否输入了整数以外的任何内容,并允许他们重试。
如果checker不是有效的 int,您将到达该except块并调用另一个输入,但您错过了将该值分配回checker:
def valuecheck(checker):
loopx = True
while loopx:
try:
#first it checks if the input is actually an integer
checker = int(checker)
loopx = False
return(checker)
#if input isn't an integer the below prompt is printed
except:
checker = input("Value isn't a valid input, try again: ") # Here!
Run Code Online (Sandbox Code Playgroud)