Python loop not working as intended - python

After selecting 2 as my choice on the menu, when I input 1 as the option, the program prints "Thanks for using.....Goodbye" and then loops back to the menu instead of stopping. I cannot figure out what the cause is, since I tried numerous times to fix it but failed. Please advise me what to do. Thanks
code: http://pastebin.com/kc0Jk9qY
Sorry I couldn't implement the code in this comment, was becoming a hassle.

All your code if in a while n!=1: loop. Set n=1 when you want to quit and that's it. So just change your code to the following and it will stop:
elif endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1
break will only terminate the innermost loop, so need to make sure all the outer ones get terminated as well.
EDIT
Changed code is:
if choice==2:
while error2:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1

What you have supplied looks correct. That break will break you out of the while error2 loop. So the problem must lie after that. I expect that if choice==2 is within another loop, and you are not breaking out of that.

OK, this is it. Your error2 value is uneccessary. Simply start an infinite loop and break out on valid responses. I would consider doing this in your other loops too.
if choice==2:
while True:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
break
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
n=1
break

Related

How do I offer the choice to run the program again or end it in Python?

I'm trying to run this program which takes a message from the user and then prints it out backwards. The while loop works but at the end I'd like to implement a decision point that carries on or exits altogether.
See here:
print("\nHi, welcome to my program that will reverse your message")
start = None
while start != " ":
var_string = input("\nSo tell me, what would you like said backwards:")
print("So your message in reverse is:", var_string[::-1])
input("Press any key to exit")
Please advise how I may include something like 'input("\nIf you want another go, tell me what:)' which would restart the loop if the user decides to. Would this be an if/or indentation?
This is early days for me.
I think your question has less to do with while loops, and more with conditional statements and continue / break statements, i.e. "control flow tools". See my suggestions in the edit to your code below:
print("\nHi, welcome to my program that will reverse your message")
# This bit is unnecessary. Why use the `start` variable if you're never going to
# reassign it later in your program?
#start = None
#while start != " ":
# Instead, use `while True`. This will create the infinite loop which you can
# 'continue` or `break` out of later.
while True:
var_string = input("\nSo tell me, what would you like said backwards:")
print("So your message in reverse is:", var_string[::-1])
# Prompt the user again and assign their response to another
# variable (here: `cont`).
cont = input("\nWould you like another try?")
# Using conditional statements, check if the user answers "yes". If they do, then
# use the `continue` keyword to leave the conditional block and go another
# round in the while loop.
if cont == "Yes":
continue
# Otherwise, if the user answers anything else, then use the `break` keyword to
# leave the loop from which this is called, i.e. your while loop.
else:
input("Press any key to exit")
break

Can I use an if statement to break a while loop in Python

Basically what I want is to have the program run and start back at the beginning until a command is typed. I have the repeat part working, but I can't get the loop to break when I want it to. I was trying to use an if statement to take the input and use it to break the loop. I've seen it done in tutorials, but I can't get it to work for me. I understand the break statement is to exit a loop, I'm wondering if it is possible to use the break statement in an if statement like so:
while True:
i == input('Type a letter:') #They type a letter
if i == quit: #If they type "quit" this executes
print('Goodbye') #The program says goodbye
break #Ends the loop
else:
print("Your letter is", i) #If they type anything else, it gets printed
With this for me it just prints,:
Type a letter: quit
Your letter is quit
Goodbye
Type a letter:
if I type it, not breaking the loop. If it's not possible, does anybody have another way that I could get the same result, having the loop end when I type something like "quit"? Any help is appreciated.
You need to set i with a single equals sign (this may have been a typo in your post).
i = input('Type a letter:')
You also need to put quit in quotes to make it a string. As you have it, you're comparing the user's input with the builtin quit function, so they'll never be equal.
if i == 'quit':

Python: How to end a while loop while it is running if the while condition changes during the loop?

I need some help with code in a text based game I am trying to make. My game uses health, and the code starts off with "while health>0:", and in another point in the game, when health eventually =0, the loop still continues. How do I make the loop end when health=0, without finishing the whole loop.
Here is an example:
health=100
while health>0:
print("You got attacked")
health=0
print("test")
Should the code not be stopping when health=0, and not print "test"? How to I get it to stop when health=0? The code I wrote deducts health based on the users actions, so the times when health=0 can vary. I want to end the code whenever health=0 Any help would be appreciated.
The condition is only evaluated at the start of each iteration. It does not get checked in the middle of an iteration (e.g. as soon as you set to health to zero).
To explicitly exit the loop, use break:
while health>0:
...
if some_condition:
break
...
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
You should use 'break' statement to come out of the loop
health=100
while health>0:
print("You got attacked")
# decrement the variable according to your requirement inside the loop
health=health-1
if health==0:
break
print("test")
Cleaner implementation
health = 100
while True:
if (health <= 0): break
print ("You got attacked!")
health = 0
print ("Testing!")
Outputs:
You got attacked!
Testing!
In a while loop, you can only get your code to stop if you specify some sort of condition. In this case, health is always greater than 0, so it keeps printing "you got attacked".
You need to make the health variable decrease till it gets to 0 in order to print "test". Hence;
` health=100
while health>0:
print("You got attacked")
health-=5
if health==0:
print("test")
break`
An alternative could be this also;
` health=100
if health>0:
print("You got attacked")
if health==0:
print("test") `

Interest Calculator looping issue Python

beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.
x=1
while x==1:
import math
loan=input("Enter Loan amount: ")
rate=input("Enter rate: ")
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
rate=rate.replace("%","")
loan=float(loan)
rate=float(rate)*0.01
amount1y=round(loan*(math.e**(rate*1)),2)
amount5y=round(loan*(math.e**(rate*5)),2)
amount10y=round(loan*(math.e**(rate*10)),2)
monthlypay=round(amount1y-loan,2)
print("Year 1 without pay: " + str(amount1y))
print("Year 5 without pay: " + str(amount5y))
print("Year 10 without pay: " + str(amount10y))
print("Amount to pay per year: " + str(monthlypay))
print("Want to do another? Y/N?")
ans=input('')
ans=ans.lower()
y=True
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
My issue is in two locations. First during the
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Finally during this part of the code:
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?
Thanks for your help!
P.S. This is python 3.4.2
You make an infinite loop, that you break out of when all is well. Simplified:
while True:
x_as_string = input("Value")
try:
x = float(x_as_string)
except ValueError:
print("I can't convert", x_as_string)
else:
break
It is easier to ask forgiveness than permission: You try to convert. If conversion fails you print a notice and continue looping else you break out of the loop.
On both of your examples, I believe your looking for Python's continue statement. From the Python Docs:
(emphasis mine)
continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. It continues with the next cycle of the nearest enclosing loop.
When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.
This basically means it will "restart" your for/while-loop.
To address your side note of breaking the loop if they get the input wrong after three tries, use a counter variable. increment the counter variable each time the user provides the wrong input, and then check and see if the counter variable is greater than 3. Example:
counter = 0
running = True:
while running:
i = input("Enter number: ")
if i.isalpha():
print("Invalid input")
counter+=1
if counter >= 3:
print("Exiting loop")
break
Unrelated notes:
Why not use a boolean value for x as well?
I usually recommend putting any imports at the module level for the structure an readability of one's program.
Your problem is straightforward. You have to use continue or break wisely. These are called control flow statements. They control the normal flow of execution of your program. So continue will jump to the top-most line in your loop and break will simply jump out of your loop completely, be it a for or while loop.
Going back to your code:
How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number.
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
continue
This way, you jump back (you continue) in your loop to the first line: import math. Doing imports inside a loop isn't useful this way the import statement is useless as your imported module is already in sys.modules list as such the import statement won't bother to import it; if you're using reload from imp in 3.X or available in __builtin__ in Python 2.x, then this might sound more reasonable here.
Ditto:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
continue
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
continue
To state this snippet in English: if ans is equal to "n" or "no" then break the loop; else if ans is equal to "y" or "yes" then continue. If nothing of that happened, then (else) continue. The nested while loop isn't needed.
Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Not sure if I understood your question, you can take input three times in different ways:
for line in range(3):
in = input("Enter text for lineno", line)
...do something...

Python program, how to make an atm program loop

How do i make it loop back to the start after doing this? After each transaction, it ends and doesn't go back to see if you can pick another option.
Thanks and it's greatly appreciated.
balance=7.52
print("Hi, Welcome to the Atm.")
print("no need for pin numbers, we already know who you are")
print("please selection one of the options given beneath")
print("""
D = Deposit
W = Withdrawal
T = Transfer
B = Balance check
Q = Quick cash of 20$
E = Exit
Please select in the next line.
""")
option=input("which option would you like?:")
if option==("D"):
print("How much would you like to deposit?")
amount=(int(input("amount:")))
total=amount+balance
elif option ==("W"):
print("How much would you like to withdrawl?")
withdrawl=int(input("how much would you like to take out:?"))
if balance<withdrawl:
print("Error, insufficent funds")
print("please try again")
elif option == "T":
print("don't worry about the technicalities, we already know who you're transferring to")
transfer =int(input("How much would you like to transfer:?"))
print("you now have", balance-transfer,"dollars in your bank")
elif option=="B":
print("you currently have",balance,"dollars.")
elif option=="Q":
print("processing transaction, please await approval")
quicky=balance-20
if balance<quicky:
print("processing transaction, please await approval")
print("Error, You're broke.:(")
elif option=="E":
print("Thanks for checking with the Atm")
print("press the enter key to exit")
It seems like you are asking about a loop with a sentinel value.
Somewhere right before you print your menu, set a sentinel value:
keep_going = True
Then, preferably on the next line (before you print the first thing you want to see when it loops), you start your loop.
while keep_going: # loop until keep_going == False
As written, this is an infinite loop. Everything in the indented block beneath the while statement will be repeated, in order, forever. That's obviously not what we want -- we have to have some way to get out so we can use our computer for other things! That's where our sentinel comes in.
Build in a new menu option to allow the user to quit. Suppose you key that to "Q", and the user picks it. Then, in that branch:
elif option == 'Q':
keep_going = False
Since that's all there is in that branch, we "fall off" the bottom of the loop, then go back to the while statement, which now fails its check. Loop terminated!
By the way, you should think about reading The Python Style Guide. It's very easy to read and gives you an idea how to make your code also very easy to read. Most every Python programmer abides by it and expects others to do the same, so you should too! If you want help learning it, or aren't sure if you're doing it right, there are tools to check your code to help you keep it clean and error-free.
Happy programming!

Categories