我正在为我的第一个主要项目做一个全面的计算器,但是我陷入了小麻烦。我想重复一部分代码,但不知道如何重复。更明确地说,我有一个称为不平等的部分,我希望用户能够选择是否要保持不平等或回到起点。我不确定是否存在可以像检查点一样工作的代码,您可以使代码回到原来的状态。我试图找到一个可以那样工作但没有运气的代码。任何其他建议,将不胜感激。编码:
import math
while True:
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print('5.Exponent')
print('6.Square Root (solid numbers only)')
print('7.Inequalities')
choice = input("Enter choice(1/2/3/4/5/6/7): ")
if choice in ('1', '2', '3', '4'):
x = float(input("What is x: "))
y = float(input('What is y: '))
if choice == '1':
print(x + y)
elif choice == '2':
print(x - y)
elif choice == '3':
print(x * y)
elif choice == '4':
print(x / y)
if choice in ('5'):
x = float(input('Number: '))
y = float(input('raised by: '))
if choice == '5':
print(x**y)
if choice in ('6'):
x = int(input('Number: '))
if choice == '6':
print(math.sqrt(x))
if choice in ('7'):
print('1.For >')
print('2.For <')
print('3.For ≥')
print('4.For ≤')
pick = input('Enter Choice(1/2/3/4): ')
if pick in ('1', '2', '3', '4'):
x = float(input("What is on the left of the equation: "))
y = float(input('What is on the right of the equation: '))
if pick == '1':
if x > y:
print('true')
else:
print('false')
elif pick == '2':
if x < y:
print('true')
else:
print('false')
elif pick == '3':
if x >= y:
print('true')
else:
print('false')
elif pick == '4':
if x <= y:
print('true')
else:
print('false')
back = input('Do you wanna continue with intequalities: ')
if back in ('YES', 'Yes', 'yes', 'no', 'No', 'NO'):
if back == 'YES' or 'Yes' or 'yes':
print('ok')
#the print('ok') is there for test reasons, and i want to replace it with the peice of code that will allow me to return to line 33
最简单的方法是获取不等式段的代码,并使其成为一个如果要重复则返回true的函数。一个函数封装了用户希望按需运行的几行代码,python中的语法很简单def [function name]([arguments]):
。if pick == '7':
用名为函数的分支替换分支中的代码,inequality
如下所示:
def inequality():
print('1.For >')
print('2.For <')
print('3.For ≥')
print('4.For ≤')
pick = input('Enter Choice(1/2/3/4): ')
if pick in ('1', '2', '3', '4'):
x = float(input("What is on the left of the equation: "))
y = float(input('What is on the right of the equation: '))
if pick == '1':
if x > y:
print('true')
else:
print('false')
elif pick == '2':
if x < y:
print('true')
else:
print('false')
elif pick == '3':
if x >= y:
print('true')
else:
print('false')
elif pick == '4':
if x <= y:
print('true')
else:
print('false')
back = input('Do you wanna continue with intequalities: ')
if back in ('YES', 'Yes', 'yes', 'no', 'No', 'NO'):
if back == 'YES' or 'Yes' or 'yes':
return True
return False
我更正了原始代码中的逻辑错误,导致代码块提示用户是否仅在输入'4'
前一个提示的情况下才继续执行。
当我们使用语法调用函数时,python解释器将运行上面的代码块inequality()
。现在,我们已经分离了要重复的代码,我们只需用while
循环将其封装即可。我建议将计算器放入函数中,并将其封装在while循环中,因此对主执行的修改如下所示:
import math
def calculator():
# Copy-paste your main branch here
...
if choice in ('7'):
# Replace the branch for inequality with a function call
# `inequality` returns True if the user wants to continue, so the
# next line checks if the user wants to continue and calls
# `inequality` until the user inputs some variant of 'no'
while inequality():
continue
# When we call the script from the command line, run the code in `calculator`
if __name__ == '__main__':
while True:
calculator()
如果您熟悉字典的工作方式,则可以考虑使用一些方法来跟踪脚本对每种选择的作用,例如
def inequality() -> bool:
print('1. For >')
print('2. For <')
print('3. For ≥')
print('4. For ≤')
choice = int(input('Enter choice(1/2/3/4): '))
x = float(input('What is on the left of the equation: '))
y = float(input('What is on the right of the equation: '))
# Each line represents a choice, so ineq.get(1) returns True if x > y, etc.
ineq = {
1: x > y,
2: x < y,
3: x >= y,
4: x <= y
}
# Print the appropriate output for the user's choice
print(f'{ineq.get(choice, 'Bad choice, must be one of 1/2/3/4')}')
choice = input('Do you wanna continue with inequalities: ')
# Dictionary for checking if the user is done
done = {
'yes': False,
'no': True
}
# Convert the input to lowercase to make comparison more simple
return not done.get(choice.lower(), False)
看起来比以前的定义更干净inequality
。请注意,我们只需要使用'yes'
或检查用户输入,'no'
因为我们将其输入转换为小写。
在一个更无关的注意,如果你要张贴在堆栈交换,记住,人们更可能的答案,如果你只张贴代码相关的什么你问。在这种情况下,您唯一需要的代码部分就是以下内容if pick == '7':
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句