如何使用用户定义的函数(如“富有成果”)来缩短这个 Python 程序?功能

发布于 2025-01-13 06:25:55 字数 2037 浏览 3 评论 0原文

我是编程新手,我试图使用用户定义的函数来缩短程序的一部分,但我有点迷失了。如何使用用户定义的函数缩短此过程或使其更有效?

import math


while True:
    print('#####################')
    print('# GEOMETRIC OBJECTS #')
    print('#####################')
    print('[1] Circle')
    print('[2] Triangle')
    print('[3] Rectangle')
    print('[4] Cone')
    print('[5] Triangular Pyramid')
    print('[6] Pyramid')
    print('[7] Exit')

    option = input('Option: ')

    if option == '7':
        print('You have exited.')
        exit()
        
    if option == '1': #Circle Geometric Object
        print('You have chosen circle.')
        print('')
        print('================')
        print('     CIRCLE     ')
        print('================')
        print('[1] Enter the length of the radius')
        print('[2] Area')
        print('[3] Circumference')
        print('[4] Back to main menu')

        optionCircle = input('Option: ')
        
        if optionCircle == '4':
            continue
        
        if optionCircle == '1':
            print('Enter the length of the radius.')

            Rad = float(input('> Radius: '))
            
        while True:
            
            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')
        
            if optionRadius == '2':
                area = math.pi * Rad * Rad
                print('')
                print('> The area of the circle with a radius of ' + str(Rad) + ' is ' + str(area))
            
            elif optionRadius == '3':
                circum = 2 * math.pi * Rad
                print('')
                print('> The circumference of the circle with a radius of ' + str(Rad) + ' is ' + str(circum))
            
            else:
                break

I'm new to programming and I'm trying to shorten a part of my program using user-defined functions, but I'm kinda lost. How do I shorten this or make it more efficient using user-defined functions?

import math


while True:
    print('#####################')
    print('# GEOMETRIC OBJECTS #')
    print('#####################')
    print('[1] Circle')
    print('[2] Triangle')
    print('[3] Rectangle')
    print('[4] Cone')
    print('[5] Triangular Pyramid')
    print('[6] Pyramid')
    print('[7] Exit')

    option = input('Option: ')

    if option == '7':
        print('You have exited.')
        exit()
        
    if option == '1': #Circle Geometric Object
        print('You have chosen circle.')
        print('')
        print('================')
        print('     CIRCLE     ')
        print('================')
        print('[1] Enter the length of the radius')
        print('[2] Area')
        print('[3] Circumference')
        print('[4] Back to main menu')

        optionCircle = input('Option: ')
        
        if optionCircle == '4':
            continue
        
        if optionCircle == '1':
            print('Enter the length of the radius.')

            Rad = float(input('> Radius: '))
            
        while True:
            
            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')
        
            if optionRadius == '2':
                area = math.pi * Rad * Rad
                print('')
                print('> The area of the circle with a radius of ' + str(Rad) + ' is ' + str(area))
            
            elif optionRadius == '3':
                circum = 2 * math.pi * Rad
                print('')
                print('> The circumference of the circle with a radius of ' + str(Rad) + ' is ' + str(circum))
            
            else:
                break

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难忘№最初的完美 2025-01-20 06:25:55

一个非常简单的例子是这段代码,您已经重复了两次:

            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')

您可以将其转换为一个函数:

def circle_menu() -> str:
    """Show the menu for a circle, return selection."""
    print('')
    print('================')
    print('     CIRCLE     ')
    print('================')
    print('[1] Enter the length of the radius')
    print('[2] Area')
    print('[3] Circumference')
    print('[4] Back to main menu')
            
    return input('Option: ')

然后将复制并粘贴上述代码的两个位置替换为:

    optionRadius = circle_menu()

更进一步 - - 假设你有很多这样的菜单,而且它们都做同样的事情?您可以定义一个通用的 menu 函数,并根据该函数定义所有其他菜单:

def menu(title: str, options: list[str]) -> str:
    """Display a menu, return selection."""
    # Show the title with marquee around it.
    title_width = max(16, len(title))
    print('=' * title_width)
    print(title.center(title_width))
    print('=' * title_width)

    # Show all the options, numbered starting at 1.
    for i, option in enumerate(options, 1):
        print(f'[{i}] {option}')

    return input('Option: ')


def circle_menu() -> str:
    """Menu for a circle."""
    return menu(
        "CIRCLE", [
            'Enter the length of the radius',
            'Area',
            'Circumference',
            'Back to menu menu'
        ]
    )

A very low-hanging example is this block of code, which you have repeated twice:

            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')

You could turn this into a function:

def circle_menu() -> str:
    """Show the menu for a circle, return selection."""
    print('')
    print('================')
    print('     CIRCLE     ')
    print('================')
    print('[1] Enter the length of the radius')
    print('[2] Area')
    print('[3] Circumference')
    print('[4] Back to main menu')
            
    return input('Option: ')

and then replace the two places where you've copied and pasted the above code with:

    optionRadius = circle_menu()

Taking it a step further -- suppose you have a lot of menus like this and they all do sort of the same thing? You could define a generic menu function and define all your other menus in terms of that function:

def menu(title: str, options: list[str]) -> str:
    """Display a menu, return selection."""
    # Show the title with marquee around it.
    title_width = max(16, len(title))
    print('=' * title_width)
    print(title.center(title_width))
    print('=' * title_width)

    # Show all the options, numbered starting at 1.
    for i, option in enumerate(options, 1):
        print(f'[{i}] {option}')

    return input('Option: ')


def circle_menu() -> str:
    """Menu for a circle."""
    return menu(
        "CIRCLE", [
            'Enter the length of the radius',
            'Area',
            'Circumference',
            'Back to menu menu'
        ]
    )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文