我应该如何检查一个条件,如果不是真的,重复上一步?(How should I check for a condition and when not true, repeat a previous st

编程入门 行业动态 更新时间:2024-10-28 18:29:48
我应该如何检查一个条件,如果不是真的,重复上一步?(How should I check for a condition and when not true, repeat a previous step?)

我正在尝试python代码的初学者级别,我希望项目检查某个变量是否被赋予1或0. 1和0表示加法或减法的选择。

代码如下:

print("This program can be used to add and subtract") x=int(input("x:")) y=int(input("y:")) print("Choose for addition :1 or subtraction 0") z = int(input("z:")) if z==1: print("Addition selected.") a= x+y print("The sum of ",y,"and",x,"is",a) elif z ==0: print("Subtraction selected.") a= x-y print("The difference between ",y,"and",x,"is",a) else: print("Kindly input either 1 or 0")

我想运行它,以便当z不等于1或0时,它将重定向用户为z选择一个值,直到没有选择正确的值!

提前致谢!

I'm trying the beginner level of python code, where I want the project to check if a certain variable has been given either 1 or 0. 1 and 0 represent the selection of addition or subtraction.

The code is given below:

print("This program can be used to add and subtract") x=int(input("x:")) y=int(input("y:")) print("Choose for addition :1 or subtraction 0") z = int(input("z:")) if z==1: print("Addition selected.") a= x+y print("The sum of ",y,"and",x,"is",a) elif z ==0: print("Subtraction selected.") a= x-y print("The difference between ",y,"and",x,"is",a) else: print("Kindly input either 1 or 0")

I want to run it so that when z is not equal to 1 or zero, it redirects user to pick one value for z again, till the correct value isn't selected!

Thanks in advance!

最满意答案

您可以将第一部分代码放入方法中,以便可以重复使用它。 喜欢这个:

z = 0 def getInput(): print("This program can be used to add and subtract") x=int(input("x:")) y=int(input("y:")) print("Choose for addition :1 or subtraction 0") z = int(input("z:"))

z需要在方法之外,以便可以从方法之外调用它。

然后,你可以改变你的代码

else: getInput()

You can put the first half of the code in a method so that you can reuse it. Like this:

z = 0 def getInput(): print("This program can be used to add and subtract") x=int(input("x:")) y=int(input("y:")) print("Choose for addition :1 or subtraction 0") z = int(input("z:"))

The z needs to be outside of the method so that it can be called from outside of the method also.

Then, you can change your code to

else: getInput()

更多推荐

本文发布于:2023-07-07 15:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1065223.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不是真的   上一步   条件   check   condition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!