我如何在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
诺兰·福特

最简单的方法是获取不等式段的代码,并使其成为一个如果要重复则返回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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么Python3执行一段注释掉的代码?

如何在一定时间段内循环执行nodejs中的一段代码?

我如何在sublimetext 3中使用python

如何使用while循环重复一段代码并使用每个“ Counts”?

我如何使一段代码每x秒重复一次?

如何跳过一段代码并转到硒中的所需代码

如何跟踪一段代码中变量的使用?

如何在C ++中获得一段代码的执行时间?

当队列的计数为零时,如何在C#中锁定一段代码?

如何计划一段代码在Swift的下一个runloop中执行?

如何重复一段文字?

我有一段服务器-客户端代码,但是此位在AS3中,并且我在C#中工作。有人可以帮我翻译吗?

如何在我的主要活动中循环一段代码?

如何在IntelliJ IDEA中缩进/移动一行代码或一段代码

我如何在不使用while循环的情况下在python3中重复一个函数?

如何区分字符串中的代码是一段JS还是CSS代码?

如何重复一段代码以对 r 中的 2 个值进行采样?

如何在android的后台运行一段代码?

如何在 AWS Lambda 中将 Python 变量输入到一段 xml 代码中?

我对python 2.7非常陌生。我不知道如何将一段特定的代码从 2.7 转换为 3+

我如何在 python 3 中打印出数字变量?

如何在python3中将我的oneliner小代码变成multiliner?

我想在shinyapp中添加一个runexample按钮,但是又不想写一段重复的代码来实现它的功能

我如何在 python 3 中获取 http 请求并让程序对状态代码进行排序

如何在指标菜单中获取选项以启用或禁用指标(一段代码,交易视图)?

如何重复一段C代码,每次只换几个关键字

如何在 kotlin native 中推迟执行一段代码?

如何在递归中跳过一段代码?

如何在一段代码中实现 .each() 函数?