Python 如何用一个单词摆脱循环
我必须使用Python 如何用一个单词摆脱循环,python,Python,我必须使用制作一个程序,而必须: 将要求用户输入2个整数 并返回加法和乘法 在这两个人当中 将检查数字是否为整数 如果用户使用单词stop,则将关闭 我已经取得了1和2,但被困在3。以下是我写的: while True: try: x = int(input("Give an integer for x")) c = int(input("Give an integer for c")) if x=="stop":
制作一个程序,而必须:
将要求用户输入2个整数
并返回加法和乘法
在这两个人当中
将检查数字是否为整数
如果用户使用单词stop
,则将关闭
我已经取得了1和2,但被困在3。以下是我写的:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
您的代码不起作用,因为您首先将x
定义为一个整数,要使其等于“stop
”,它必须是一个字符串
因此,您要做的是允许将x
作为字符串输入,如果它不是stop
,则将其转换为整数:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
只需稍作更改(并且可以在try
块中使用else
稍微结构化一些)
您需要将第一个值作为字符串输入,以便您可以首先测试它的“停止”,然后才尝试将其转换为整数:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
我还解决了一些空格问题(即字符串中的多余空格和缺少空格)。您的if
将始终为false(如果x
是stop
,当您尝试将其转换为int
时,会出现异常).我已经做了1和2,但是被3卡住了。这个程序有什么问题吗?除了那样,不要使用裸的,请参见。你真的不需要其他的(尽管使用它没有错)“else
有什么帮助?@ScottHunter这没什么大不了的,但是除了
块之外,块中不再需要有一个continue
语句,它会更清楚地显示在没有异常时要执行的备用代码。最后。”。