Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop functioning with user input and commands

I need to make a program to store contacts (Name and phone number). The first step is to make the program run unless the input is 'exit'. The program should offer a set of options. My problem is that when I enter an option it offers again the set of options and I have to enter the option for a second time for it to run.

I kind of understand why the program does that so I tried it with a while True but it didn't work.

def main():
    options = input( "Select an option [add, query, list, exit]:" ) 
    while options != "exit" : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)

Select an option [add, query, list, exit]:add
Select an option [add, query, list, exit]:add
Enter the name of a new contact:
like image 612
cped Avatar asked Mar 26 '26 18:03

cped


2 Answers

It's due to your first option, do like this instead :

def main():
    options = None
    while options != "exit" : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)

like image 113
Florian Bernard Avatar answered Mar 29 '26 09:03

Florian Bernard


You don't need to set any value for 'option' before entering the loop. You can use an infinite loop (while True) to check the value of 'option' inside the loop and take an action accordingly. You can break out of the loop if the user enters "exit". Try this:

def main():
    #options = input( "Select an option [add, query, list, exit]:" ) 
    while True : 
        options = input( "Select an option [add, query, list, exit]:" )
        # Offrir un choix de commandes
        if options == "add":
            add_contact(name_to_phone)
        if options == "query":
            query_contact(name_to_phone)
        if options == "list":
            list_contacts(name_to_phone)
        if options == "exit":
            break
like image 29
Sultan Singh Atwal Avatar answered Mar 29 '26 07:03

Sultan Singh Atwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!