我怎样才能使它更紧凑和更快?新学员

Posted

技术标签:

【中文标题】我怎样才能使它更紧凑和更快?新学员【英文标题】:How would I make this more compact and faster? New learner 【发布时间】:2022-01-05 22:38:13 【问题描述】:

很抱歉问了一个很长的问题,但我对 Python 很陌生。我开始了关于 FutureLearn 的免费课程,任务是创建一个计算器。我最终得到的代码比其他答案长得多,而且太大而无法放入评论部分。只是为我的代码中可能被压扁的任何部分寻找提示。 *** 上的第一个问题,如果这是一个不好的问题,我很抱歉。

def main():
    operations = ['multiplication', 'division', 'addition', 'subtraction', 'x^y']

    def find_op():
        while True:
            try:
                operation = input('What do you want to do? Addition, subtraction, multiplication, division, or x^y??\n')
                operations.index(operation.lower())
                break
            except ValueError:
                input('Error!, you must input one of the five options, enter to try again.')
        return operations.index(operation.lower())

    operation_index = find_op()

    match operation_index:
        case 0:
            num_question_ending = 'multiply with'
        case 1:
            num_question_ending = 'divide with'
        case 2:
            num_question_ending = 'add with'
        case 3:
            num_question_ending = 'subtract with'
        case 4:
            num_question_ending = 'create an exponential with'

    def add():
        add_ans = global_number1 + global_number2
        print(f'global_number1 + global_number2 =\nadd_ans')

    def sub():
        sub_ans = global_number1 - global_number2
        print(f'global_number1 - global_number2 =\nsub_ans')

    def mult():
        mult_ans = global_number1 * global_number2
        print(f'global_number1 multiplied by global_number2 =\nmult_ans')

    def div():
        while True:
            try:
                div_ans = global_number1 / global_number2
                break
            except ZeroDivisionError:
                input('Naughty naughty boy trying to divide by 0. '
                      'Now you gonna have to restart the code. Press enter plz')
                main()
        print(f'global_number1 divided by global_number2 =\ndiv_ans')

    def power():
        if global_number1 == 0 and global_number2 == 0:
            input('Naughty boy trying 0^0, dat is undefined boi. Enter to restart the whole thing.')
            main()
        pow_ans = global_number1 ** global_number2
        print(f'global_number1 to the power of global_number2 =\npow_ans')

    def get_number1():
        while True:
            try:
                numba1 = input(f'what\'s the first number you want to num_question_ending??\n')
                float(numba1)
                break
            except ValueError:
                input('input must be a number. enter to try again.')

        numba1 = float(numba1)
        return numba1

    def get_number2():
        while True:
            try:
                numba2 = input(f'what\'s the second number you want to num_question_ending??\n')
                float(numba2)
                break
            except ValueError:
                input('input must be a number. enter to try again.')

        numba2 = float(numba2)
        return numba2

    global_number1 = get_number1()

    global_number2 = get_number2()

    match operation_index:
        case 0:
            mult()
        case 1:
            div()
        case 2:
            add()
        case 3:
            sub()
        case 4:
            power()

    def repeat():
        go_again_ans = input('would you like to go again? Y/N\n')
        if go_again_ans == 'Y':
            main()
        elif go_again_ans == 'N':
            exit()
        else:
            input('Error! You need to answer with either Y or N, enter to try again.')
            repeat()
    repeat()

if __name__ == '__main__':
    main()

【问题讨论】:

由于您的代码似乎可以工作,也许这更适合 codereview.stackexchange.com 而不是 ***。 don't repeat yourself,这是我最喜欢的规则。你的函数get_number 使用大部分相同的代码。找到一种融合它们的方法,两者的不同之处在于最终函数所需的参数。然后跟踪所有重复 【参考方案1】:

我认为这是最简洁的方式 我使用菜单提示保存文本,第一类函数不搜索操作和 lambda 函数以避免在 3 行中定义每个函数,也不检查零我只捕获异常

我还在学习,如果有问题请见谅

谢谢

menu_prompt = f"""
Please enter:
'a' For addition
's' For Subtraction
'm' For Multiplication
'd' For Division
'p' For Exponential operations
'q' To quit
"""

add = lambda x, y: f"x + y =  x + y"
subtract = lambda x, y: f"x - y =  x - y"
multiply = lambda x, y: f"x * y =  x * y"
divide = lambda x, y: f"x / y =  x / y:.2f"
power = lambda x, y: f"x ^ y =  x ** y"

operations = 
    'a': add,
    's': subtract,
    'm': multiply,
    'd': divide,
    'p': power


def get_number(order):
    while True:
        try:
            return float(input(f"Please enter the order number: "))
            
        except ValueError:
            print("Please enter a valid number")

def run_selected_operation(operation):
    x = get_number("first")
    y = get_number("second")
    try:
        print(operation(x, y))
    except ZeroDivisionError:
        print("Can not divide by zero, try again")

user_selection = input(menu_prompt)

while user_selection.lower() != 'q':
    if user_selection in operations:
        selected_operation = operations[user_selection]
        run_selected_operation(selected_operation)
    else:
        print("Please enter a valid selection")
        user_selection = input(menu_prompt)

    user_selection = input(menu_prompt)

print(menu_prompt)

【讨论】:

以上是关于我怎样才能使它更紧凑和更快?新学员的主要内容,如果未能解决你的问题,请参考以下文章

我有一个工作布尔函数,但我的代码非常笨拙。我怎样才能使它更顺畅? [关闭]

赢得内在游戏,才能面对外在人生!||虢海平NLP执行师学员分享

编程培训开班典礼

UICollectionView 太宽。我怎样才能使它成为设备的宽度?

第三章 给自学者和JAVA培训机构学员的朋友的建议(怎样获得学习资料)

如何部署包括 .NET 文件的新程序