我如何在 python 3.8 中重复一段代码
How can i repeat a piece of code in python 3.8
我正在为我的第一个主要项目做一个全能计算器,但我遇到了一个小问题。我想重复一部分代码,但不知道如何重复。为了更清楚,我有一个名为不等式的部分,我希望用户能够选择他是想留在不等式中还是回到起点。我不确定是否有像检查点一样工作的代码可以让您的代码返回。我试图找到一个可以像那样工作但没有运气的代码。任何其他建议将不胜感激。
代码:
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
最简单的方法是获取不等式部分的代码,并使其成为 returns 如果您希望它重复则为 true 的函数。一个函数封装了用户想要运行on-demand的几行代码,python中的语法就是def [function name]([arguments]):
。用名为 inequality
的函数替换分支 if pick == '7':
中的代码,如下所示:
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'
的情况下继续执行。
当我们使用语法 inequality()
调用函数时,python 解释器将 运行 上面的代码块。既然我们已经分离了要重复的代码,我们只需用 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'
检查用户输入,因为我们将他们的输入转换为小写。
关于一个更不相关的说明,如果你要 post 进行堆栈交换,请记住,如果你只 post 代码 与您的要求相关。在这种情况下,您唯一需要的代码部分就是以 if pick == '7':
开头的行下方的内容
@Nolan Faught 给出了一个有效的解决方案。
我喜欢这个。和我做的第一件好事差不多pythonprogram.First给大家指点一下,喜欢改不改
- 因为您已经使用了
if choice in ('1', '2', '3', '4')
,所以不使用 if choice in ('5')
并且对 6
和 7
使用 if choice == '5'
是有意义的,然后获取输入.
- 也使用
back.lower()
以避免将其与 YES
的不同情况进行比较,例如 back.lower() in ['yes', 'no]
和 back.lower() == 'yes'
- 如果您愿意,可以使用
print(x>y)
或 print(x<y)
跳过某些 if
语句。这些先自己尝试,了解后再使用。
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'):
ineq = True
while ineq:
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':
print(x>y)
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.lower() == 'no':
ineq = False
我正在为我的第一个主要项目做一个全能计算器,但我遇到了一个小问题。我想重复一部分代码,但不知道如何重复。为了更清楚,我有一个名为不等式的部分,我希望用户能够选择他是想留在不等式中还是回到起点。我不确定是否有像检查点一样工作的代码可以让您的代码返回。我试图找到一个可以像那样工作但没有运气的代码。任何其他建议将不胜感激。 代码:
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
最简单的方法是获取不等式部分的代码,并使其成为 returns 如果您希望它重复则为 true 的函数。一个函数封装了用户想要运行on-demand的几行代码,python中的语法就是def [function name]([arguments]):
。用名为 inequality
的函数替换分支 if pick == '7':
中的代码,如下所示:
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'
的情况下继续执行。
当我们使用语法 inequality()
调用函数时,python 解释器将 运行 上面的代码块。既然我们已经分离了要重复的代码,我们只需用 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'
检查用户输入,因为我们将他们的输入转换为小写。
关于一个更不相关的说明,如果你要 post 进行堆栈交换,请记住,如果你只 post 代码 与您的要求相关。在这种情况下,您唯一需要的代码部分就是以 if pick == '7':
@Nolan Faught 给出了一个有效的解决方案。 我喜欢这个。和我做的第一件好事差不多pythonprogram.First给大家指点一下,喜欢改不改
- 因为您已经使用了
if choice in ('1', '2', '3', '4')
,所以不使用if choice in ('5')
并且对6
和7
使用if choice == '5'
是有意义的,然后获取输入. - 也使用
back.lower()
以避免将其与YES
的不同情况进行比较,例如back.lower() in ['yes', 'no]
和back.lower() == 'yes'
- 如果您愿意,可以使用
print(x>y)
或print(x<y)
跳过某些if
语句。这些先自己尝试,了解后再使用。
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'):
ineq = True
while ineq:
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':
print(x>y)
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.lower() == 'no':
ineq = False