Python program, how to make an atm program loop - python

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!

Related

What command do I do to make someone loop back to a specific place in my code? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I am making a text based game. I am moving along, but I am stumped on how to make specific choices bring you back to where you need to make the choice. Currently, the current plan I am doing is to make the right answers bring you to the rest of the game, while the incorrect questions bring you nowhere, and you have to restart the program entirely, but it isn't very fun to have to slog through the parts I have already done every single time I get a wrong choice.
ruintalk = input ()
if ruintalk == '1':
print ('"Rude!" the old man shouts, "I knew you were just like the rest of them." The old man storms out as fast as his frail legs can take him. You never hear from him again and later die of lumbago and are buried in a paupers grave. Dont insult the old man or ask stupid questions. Hes kind of a dick so just roll with it and restart the game.')
What command should I put to bring me back to input()?
Loops are what can you help you with that. "while" loops particularly in this case. "while" loops keep iterating through a block of code till the condition is true.
Here is an example demonstrating their use -
while True:
ruintalk = input()
if ruintalk == correct_answer:
break # This will break the iteration
This block of code will keep iterating until break statement is called. Alternatively, what you can do is have a variable set as True and set it to false once the correct answer is entered. Here is an example showing this -
run = True
while run:
ruintalk = input()
if ruintalk == correct_answer:
run = False
If I understand what you're trying to build, you might want to make your input a function to be called. You can then build loops for different scenarios and your input will happen in a statement:
def userInput():
r = input()
r = r.lower() #I like doing this to simplify how I handle user input in the code
return(r)
while sceneComplete is False:
print("Something to setup the scene. What do you want to do, user??? (X/Y/Z)?")
action = userInput()
if action == "x":
do the x thing
elif action == "y":
do the y thing
elif action == "z":
sceneComplete = True
else:
print("You broke the rules and an ogre kills you ....")

Why is this script repeating itself?

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!"

Code that consistently asks a question until proper input that can be repeated many times + the ability to accept multiple inputs? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Firstly, sorry for the long title.
So... I am making a text adventure game in Python for learning purposes. I spent most of last night trying to squash a bug in my game where no matter what you typed it would take you 'north'. I could input "sadjbfl" and it would just take me "north" instead of giving an error. (But I could also put "south" and it would take me south...)
I figured out a "while True" loop by searching for how to do this online but then I ran into another couple of problems with it, the first being that I could not make it accept multiple inputs. I could not allow it to accept "'north' OR 'n'"; it would then just accept literally anything as the first choice. The second problem is that I believe I would need a "while True" loop for every choice in the game.
The other way I have tried to accomplish this is a simple "ask for 'north' or 'n' and if it's none of that then print 'error'" but when it prints an error the program stops running when I need it to re-ask the question.
"Solution" 1:
# this code works perfectly fine
# if you don't type what it wants
# it keeps asking the question again
while True:
user_input = input("Enter 'test': ")
if user_input.lower() == "test":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 1b (problem):
while True:
user_input = input("Enter 'test': ")
# With '"test" or "t"', it allows ANY input;
# it does not give an error and just prints
# 'Correct!'.
if user_input.lower() == "test" or "t":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 2:
# "ch" means "choice".
# (naming scheme for less space)
ch_1 = input("\nGo north or south? ")
if ch_1.lower() in ["north", "n"]:
print("\nYou went north!")
elif ch_1.lower() in ["south", "s"]:
print("\nYou went south!")
# if this 'else' prints it ends the program instead of re-asking
# the question of 'which way to go?'
else:
print("I don't know what that means.")
EDIT: Nothing I've read on this site has actually helped me concerning this problem, not even the "duplicate" of this one (which I read before posting this).
My problem:
When I use the "while True" loop, my code becomes incredibly restrictive.
Every single choice using this method needs to be wrapped in an "while True" statement and it limits my options severely. It works perfectly if I only have one choice/path in that block BUT as soon as I add another choice/path, the new path experiences the same exact problem that I made this post for to begin with.
If there's some way to just always spit out a predefined message saying "ERROR! Check for misspellings!" or whatever every time the user does not put in what I want them to then that would be fantastic. (The "duplicate" of this post had something like this (I think) but it didn't work. /shrug)
But in the meantime I just cannot figure this out. Maybe I should just go back to the basics for a while.
In solution 2 only the loop is missing:
while True:
# name your variables correctly and no comment is needed.
choice = input("\nGo north or south? ")
if choice.lower() in ["north", "n"]:
print("\nYou went north!")
break
elif choice.lower() in ["south", "s"]:
print("\nYou went south!")
break
else:
print("I don't know what that means.")
You can write a function to reuse the loop:
def ask(question, answers):
while True:
choice = input(question).lower()
if choice in answers:
break
print("I don't know what that means.")
return choice
choice = ask("\nGo north or south? ", ["north", "n", "south", "s"])
if choice[0] == "n":
print("\nYou went north!")
else: # the only other choice is "south"
print("\nYou went south!")

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

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...

Categories