In my current Python project I utilize a loop via a while loop and have an input function inside of it. Thus far I've defined three different things that happen based on the use input using IF, and I've managed to use an ELSE to print a message when said input doesn't do anything.
However, when the input remains empty and is entered the loop breaks and I get an IndexError based on the if action[0] == "go": line. Here's the code I'm using:
while True:
action = input("? ").lower().split()
#user puts in one of the words below plus a direction
if action[0] == "go":
#stuff happens
if action[0] == "get" :
#stuff happens
if action[0] == "exit":
break
else:
print("Please try again.")
This code works, but as above if I just press enter or input nothing but spaces the loop breaks and I get an IndexError. How can I fix this?
If you input nothing, split is giving you an empty list, so it throws an index error when you try to index it. The solution is just to check if the input is empty, and if so, skip the other conditions and continue iterating. if action == []: break accomplishes this task.
while True:
action = input("? ").lower().split()
#user puts in one of the words below plus a direction
if action == []:
continue
if action[0] == "go":
#stuff happens
if action[0] == "get" :
#stuff happens
if action[0] == "exit":
break
else:
print("Please try again.")
Try to use this condition at the beginning of your loop:
if not action:
print("Please try again.")
continue
Related
Here is the problem, it's just a simple program that rolls the dice, but when I write "no" in (want), the loop continues.
import random
play_continue = True
want = ""
want_play = False
while play_continue:
while not want_play:
try:
want = input("Do you want to play?: ")
except:
print("I don't understand what you said")
else:
if want == "no":
play_continue = False
elif want == "yes":
want_play = True
else:
print("I don't understand")
the reason is that you are still on the first step of the toplevel while loop, since the inner one is ongoing, even though you changed the value of play_continue the check never happens because the program never gets back around to it as the inner loop has yet to finish.
you can think of the whole inner loop as a single instruction such as
while play_continue:
do_stuff()
the play_continue condition is only checked once do_stuff() is completed, which in your case it is not
I need this program to do one of two things from my repeat function, but it should be able to do both and I can't work out why.
It must do 2 things
make it rerun my main() subprogram,
or say "Goodbye." and close the entire program,
whichever one comes first.
I have tried making it just an if-else statement rather than if-elif-else, which didn't change anything, I have also tried rearranging the code, but that only changes the single output I can get from the subprogram. This is the subprogram currently:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat == 'n' or 'N':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat == 'y' or 'Y':
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
It should be able to repeat the program (based on the y or Y input), terminate the program and display "Goodbye." based on the n or N input or it should display the "Error. Program will shut down." message before closing if an invalid input is entered.
Many thanks to whoever can help me!
You may use in () for the comparison with a list. It compares the value of the variable with the list.
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat in ('n','N'):
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ('y','Y'):
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
if repeat == 'n' or 'N' doesn't work, since you are checking bool('N') which is always true, the same holds true for repeat == 'y' or 'Y', since
bool('Y') is always true.
You start by checking if repeat is in the list ['n','N'], or is not in the list ['y','Y'], then you exit the program, else you call the same function repeatloop
import time, sys
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/Y/n/N): ")
if repeat in ['n', 'N']:
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ['y', 'Y']:
repeatloop()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
repeatloop()
Hello and welcome to Stackoverflow.
Your problem is that your if statements are not exactly correct; and also your whole function is not correctly indented.
if repeat == 'n' or 'N' is different from if repeat == 'n' or repeat == 'N'.
In the second case, you test two different statements on the repeat keyword, where on the first one you're seeing whether:
repeat is equal to n, and also
'N' is not None; which isn't & this case always returns true.
Another way to do it could be if repeat in ["n", "N"] or even better: if repeat.lower() == 'n'
So put it all together, your code should be refined to:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n):")
if repeat.lower() == 'n':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat.lower() == 'y':
main()
else:
print("Error. Program will shuts down.")
time.sleep(2)
sys.exit()
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
else:
print("Try again...")
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
The code functions correctly but when I input the correct username the string 'Welcome!' repeats forever which crashes my browser. How do I stop it from repeating and only print once?
It looks like you have misunderstood what a while loop does. It checks the condition you give it and keeps on repeating the body of the loop for as long as the condition is true. The infinite loop you describe is exactly what you're asking for with your code.
What I think you want is a loop that stops when the user enters the correct username:
a = input('Enter your username...')
while a != 'SuperGiraffe007&': # stop looping when the name matches
print("Try again...")
a = input('Enter your username...') # ask for a new input on each loop
print('Welcome!')
I think you need to use if instead of while. Also, you don't need the parenthesis when using a conditional in python.
Use this:
a = input('Enter your username...')
if a == 'SuperGiraffe007&':
print('Welcome!')
else:
print("Try again...")
a = input('Enter your username...')
if (a == 'SuperGiraffe007&'):
print('Welcome!')
This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Closed 5 years ago.
Here's a piece of code from my project software:
def fun_1(self, i):
print("")
print("Welcome to Option 1: View Passwords")
while True:
print("")
which_o1 = input("1: Input a New Account details \n2: Exit \nPlease Input the option number: ")
if which_o1 == str(1):
with open(str(i)+'.txt', 'a+') as file:
while True:
print("")
web_n = input("Please Input Website name: ")
print("")
e_u = input("Please input email/username: ")
print("")
pass_w = input("Please input password: ")
while True:
print("")
sure = input("Website- " +web_n+"\nEmail/Username- "+e_u+"\nPassword- "+pass_w+"\nAre You sure about these details? Yes/No: ")
if (sure.lower()[0]) != 'y' and (sure.lower()[0]) != 'n':
print("")
print("Please input a valid response Yes/No!")
continue
elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n':
list_log = [web_n, e_u, pass_w]
file.write(str(list_log) + '\n')
break
break
continue
elif (sure.lower()[0]) == 'n' and (sure.lower()[0]) != 'y':
break
continue
elif which_o1 == str(2):
return (i)
else:
print("")
print("Please Enter a Valid Response!")
continue
So has you can see that it has 3 while True loop. The problem is occurring while breaking and looping the loop. If you see the latest While True under "pass_w" in the middle elif, where it says elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n':, in it I have 2 break and 1 continue because what I wanted to do is that when that elif executes it just break middle 3rd while true, 2nd while true and continue means loop the first while true at the start of the code, but it just keep looping 3rd While True in the middle of the code instead of breaking it.
Is there a way I can make it possible?
Firstly, understand that no lines can be executed after a break statement inside of a while loop. So putting multiple breaks and a continue won't work. You need to restructure your code. Personally, I would recommend either implementing try except statements, or putting some of the code inside of functions so that you can return when you want to stop looping and pass variables as indications to the outer loops where the function was called.
Another option could be instead of using breaks and continues, use a variable or set of variables that your while loops check for to decide if they should continue. So inside your ifs and elifs you could set exitfirstloop = True, etc. and in the while loops you check while not exitfirstloop
I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop