How to use options like 1, 2, 3 etc. in Python for implementing different code?

Viewed 167

I'm new to stack overflow and Python too. I'm currently coding in Python 3.8.2 on https://www.repl.it.

I am making a math solver which solves things using certain formulas, I have print functions, input functions and variables which are also integers.

What I want to do is that the user will be greeted, then the user will be prompted to choose a certain option (ex. 1, 2, 3, etc.) and each option would be a formula/method.

I have written code for just one formula as of now, but this concept which I'm solving has multiple different formulas.

Have a look at my code below:

print("Hello, welcome to the \nA.P. SOLVER!")
    
import click
if click.confirm("Do you want to start?", default=True):
    print("Ok! Let's start!")
        
    a = input('Type the value of "a" [the first term of the A.P.] ')
    d = input('Type the value of "d" [the common difference of the A.P.] ')
    n = input('Type the value of "n" [the nth term of the A.P.] ')
    
    print(f"Finding the {n}'th/nd' term...")
    a = int(a)
    d = int(d)
    n = int(n)
    
    x = a + (n-1)*d
    
    print(x)

Please help me out, would be appreciated :)

1 Answers

what I've understood from your question is that you want to make a menu driven program that asks what you want to do. What you can do is take the value (here action) which will decide in the switch() what will happen with it.

import click

def switch(action):        
    if action==1:
        a = int(input('Type the value of "a" [the first term of the A.P.]'))
        d = int(input('Type the value of "d" [the common difference of the A.P.]'))
        n = int(input('Type the value of "n" [the nth term of the A.P.] '))
        print(f"Finding the {n}'th/nd' term...")
        x = a + (n-1)*d
        print(x)
    else:
        a=int(input("Number 1 :"))
        b=int(input("Number 2 :"))
        print("Subtraction :",a-b)


if click.confirm("Do you want to start?", default=True):
    print("Ok! Let's start!")
    print("1) AP")
    print("2) Sub")
    action=int(input(":"))
    if action not in [1,2]:
        print("Invalid")
    else:
        switch(action)

If you want it to go on until the user wants to quit you can write before the 1) AP part a while loop which will go on until the user enters lets say 3) Exit which will break that while loop.

Related