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...
Related
I'm trying to teach myself python, I recently learned how to use raw input in an if statement (yes or no). However, when I answer yes, the program asks me the same if question.
Can anyone help? I'm not really good at programming but love doing it.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
# this is where it goes wrong
# below is what is supposed to follow
word = "kaasblok"
guesses = ''
turns = 6
while turns > 0:
If you use a while true loop, your program will keep on running.
In Python, the tabs or whitespace tell the interpreter when a loop ends.
So what happens in your code is this:
While True is running,
It asks if you want to play
If you write no it works as intended
If you write yes, it sees that the loop is over so it restarts.
Also your code has several errors, like syntax from both Python 3 and Python 2 and a while loop that doesn't terminate.
I wrote some updates to make the code sort of work but it is not "good" code because I tried to keep it as similar as possible. Also I chose a syntax (python 3) so make sure to change that if you're using Python 2.
I recommend you modularize your code and look at other people's code, it'll make your code better. Avoid using a while True loop, at least at the beginning. The code I wrote sort of tries to address it, but it probably doesn't do such a great job.
Maybe try editing the code a bit and updating with an answer later? I think you meant to write input, not raw_input but it could be that's the way you do it in Python 2. You should really learn Python 3 if you're trying to pick up Python btw as Python 2 is at its end of life cycle.
Place your game in the loop and it'll run. Try something like this:
import time
name = input("what is your name? ")
word = "kaasblok"
turns = 6
print("Hello " + name)
#yes no statement with raw input
trueorfalse = True
while trueorfalse:
yesno = input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
#trueorfalse = False
break
elif yesno.lower().startswith("y"):
print("cool, let me prep...")
time.sleep(1)
# Place your code in the elif block
while turns > 0:
guess = input("what is the word")
if guess == word:
print('win')
#trueorfalse = False
break
else:
turns -=1
print("you have these many turns left", turns)
print("you lost")
break
All that's missing is a way to break out of the while loop. So, use the break command.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
break # <-- break out of of the current loop
print "made it!"
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
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':
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!
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