简体   繁体   中英

How can i repeat a piece of code in python 3.8

I am doing a all round calculator for my first main project and i have fell into a small hiccup. There is a part of code that i want to repeat, but don't know how to. To make it more clear, i have a section called inequalities, and i want the user to be able to choose if he wants to stay in inequalities or go back to the start. I am not sure if there is a code that works like a checkpoint that you can make your code go back to. I've tried to find a code that would work like that but had no luck. Any others suggestions would be appreciated. The code:

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

The easiest way is to take the code for the inequality segment and make it a function that returns true if you want it to repeat. A function encapsulates several lines of code that the user wants to run on-demand, the syntax in python is simply def [function name]([arguments]): . Replacing the code in the branch if pick == '7': with a function named inequality looks like this:

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

I corrected a logic error in your original code resulting in the block of code prompting the user if they wanted to continue only executing in the case that they had input '4' for the previous prompt.

The python interpreter will run the block of code above when we call the function using the syntax inequality() . Now that we've separated the code that we want to repeat, we simply encapsulate it with a while loop. I recommend putting your calculator in a function and encapsulating that in a while loop as well, so modifications to your main execution look like this:

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()

If you're familiar with how a dictionary works, you may want to consider using a few to keep track of what your script will do for each choice, for example

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) 

looks much cleaner than the previous definition of inequality . Note that we only need to check the user input with 'yes' or 'no' because we converted their input to lowercase.

On an more unrelated note, if you're going to post on stack exchange, keep in mind that people are more likely to answer if you only post the code relevant to what you're asking. In this case, the only part of your code that you needed was what was below the line beginning with if pick == '7':

@Nolan Faught has given a efficient solution. I love this. It's similar to what I have done as my first good python program.First I'm going to give you some pointers, change them if you like or leave it

  1. Since you have used if choice in ('1', '2', '3', '4') it makes sense not to use if choice in ('5') and use if choice == '5' for 6 and 7 also and then get the input.
  2. Also use back.lower() to avoid comparing it with different cases of YES like back.lower() in ['yes', 'no] and back.lower() == 'yes'
  3. You can skip some if statements if you want by using print(x>y) or print(x<y) . Try these yourself first and use them after understanding.
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM