我正在尝试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()更多推荐
发布评论