0

This seems kind of simple but for the life of me I have no idea on how to even approach this

At the end of my code, I have a

if(__name__ == "__main__"):

block

And after that line I ask for the users input for something and I execute my function kind of like so

b = input("enter something")
run_my_func(b)

And right now it just ends right there.

How can I make it so that it will again ask for an input or exit of the user inputs nothing and presses enter

My initial idea was to put it in a while loop? But I'm not sure if that'd work/how to implement it

Hello Mellow
  • 169
  • 2
  • 15

4 Answers4

3

Yes, you can use a while loop. Because you need to check a condition (empty user input) right in the middle of the loop to decide when to stop, there's a standard trick for this. You write a while True loop which runs forever by default, and then you use break statement when the condition is met to end the loop early:

while True:
    b = input("enter something: ")
    if b == "":
        break
    run_my_func(b)
K. A. Buhr
  • 45,621
  • 3
  • 45
  • 71
1

A while loop would be a great way to implement what you are trying to do. Below is an example:

functional = True
while functional:
    userInput = input("enter something")
    if userInput == "":
        functional = False
    else:
        print(userInput)

Basically, for every iteration in which the while loop condition evaluates to True, it will run the code inside of the while loop. So when the user enters "" (nothing) we want the while loop condition to evaluate to False for the next iteration -- so you can implement this a variety of ways, my approach was to set a variable called functional to False.

fiddlegig
  • 36
  • 4
0

You're right! Wrap your function in a while loop and it will keep asking until it gets something none empty!

b = ''
while b == '':
    b = input("enter something")
run_my_func(b)

This works in python3

Grant Powell
  • 100
  • 7
0

A good Pythonic while loop would look like this:

b = input("enter something")
while not b:
    b = input("enter something")
run_my_func(b)
DYZ
  • 55,249
  • 10
  • 64
  • 93