Programming an atm machine - python

My assignment is to create an ATM-type program. Below is my main function (not including the deposit, withdraw, and check balance functions). When I go to run this code, the program loops the pin function repeatedly, even when I enter 0 or 1234. It repeatedly instructs the user to enter their pin. I think I have all of the indentation right, but I guess I'm messing up somewhere in the code.
def main():
pin_number = input("Please enter your pin number")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop == True
if pin_number == "1234":
stop == False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()

In your if statements, you should be using = not ==. The first is used for assigning values to variables, like you are trying to do. The second is used to compare if two values are equal and returns a boolean (true/false).

Your code
if stop != True:
will run the code inside the loop if the variable stop is False (the user has entered the wrong code). However, you want to run the code if stop is True.
Therefore, use this code:
if stop == True:
this will run the encased code when stop is True (user has entered correct code)
EDIT:
My apologies. The above answer regards the code following this code:
if pin_number == "1234":
stop = False

Related

While true loop with only one prompt

I have written a piece of code with a while loop, that I want to run until the user enters the string exit. However, I don't want the loop to be stopped for a repeat prompt after every loop cycle. How can I achieve this?
Currently the code loops correctly, however it does not respond to exit once in the while loop.
if __name__ == '__main__':
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
while name == True:
if prog_question == "exit":
name = False
break
else:
temperature_info = measure_temp()
if temperature_info[1] == "No error":
if int(temperature_info[0]) < int(check_temp):
heater("on",check_period*60)
else:
heater("off",check_period*60)
else:
measure_temp()
You are trying to let the user interrupt an infinite loop.
Your idea using input has the disadvantage that the user needs to actually input something on each iteration.
It might be more interesting to use try/except for that:
from time import sleep
try:
print("Hit Ctrl-C to stop the program")
while True:
print("still running")
sleep(1)
except KeyboardInterrupt:
print("this is the end")
Or you could also have a look at the module signal.
Just move the prompt to inside of the loop.
name = True
while name:
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
if prog_question == "exit":
name = False
break
else:
...

Can I create a function to break a while loops in python?

I am writing a program with python to simulate flipping a coin or rolling dice. The coin and dice use while loops to give the user the option to roll or flip again, an example is:
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
done = input("""would you like to roll again? Type y to roll again,
type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The problem I am having is that I would like to take every line starting from done and make it into it's own function that I can just insert into every function rather than typing the whole thing out again and again, like this.
def d4ing():
d4ing = True
while d4ing:
print(random.randint(1,4))
rerolling()
def rerolling():
done = input("""would you like to roll again? Type y to roll again, type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The error message I am getting:
SyntaxError: 'continue' not properly in loop
A break or a continue must be in a loop in its current scope. You cannot break a loop in the above scope from inside a function. Here is a general example of what raises the SyntaxError: 'break' outside loop error. The same holds for continue.
def break_up():
break # This is a syntax error
while True:
break_up()
Although, this is not a problem, since you can make the function return a value and conditionally break in the upper scope.
In your specific example though, you can also return whether or not you want to reroll by assigning the return value to d4ing.
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
d4ing = rerolling()
def rerolling():
done = input("Would you like to roll again?")
if done == "y":
return True
elif done == "d":
return False
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")

is a While True or If Statement best to execute one function before moving to the next

I am stuck on a simple issue. I am attempting to ask the user to choose a desired function from a list. This inputted user string will invoke the chosen function until it finishes running. (It is a lighting sequence). After this sequence ends, I would like to ask the user if he or she wishes to choose another function. If so, continue. If not, exit the code.
I cannot decide if a while true or if statement is the best to achieve this.
Here is my code:
# random functions
def rainbow():
print 'rainbow'
def clover():
print 'clover'
def foo():
print 'eggs'
if __name__ == '__main__':
# here are some random initializations
print 'ctr-c to quit'
user_input = input("choose from the following: ")
if user_input == 'rainbow':
print 'generating'
rainbow()
rainbow()
rainbow()
user_input = input('choose another')
if user_input == 'foo':
clover()
clover()
I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:
while True:
user_input = input('...')
if "good result"
break
else:
continue
while True:
user_input = input("choose from the following: ")
if user_input == "condition a":
do something
elif user_input == "condition b":
do something..
elif any(user_input == keyword for keyword in ["q", "quit"]):
# when meet any quit keyword, use break to terminate the loop
break
else:
# when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
continue
while True can meet your requirement. you can use if-elif-else clauses to do different works.

Unable to enter if statement after raw_input

Whenever I call a function within a while loop in my project it will do absolute nothing according to the function just being called and will just continue to refresh the loop like nothing happened.
Here is a simple example I wrote demonstrating the problem. By running the code you will be shown a menu and you will need to enter a choice from the menu. When doing so a few "if" statements will check which option you chose and call and execute the code below them if the choice doesn't belong to any of the statements the menu will just refresh:
#!/usr/bin/env python
import os
import time
def test():
x = True
while True:
if not x:
print "You need to type 1\n"
choice = raw_input("type 1 here: ")
if choice == 1:
print 'Works!\n'
time.sleep(5)
break
else:
x = False
def test2():
print "Test123\n"
try:
while True:
os.system("clear")
menu_choice = raw_input("Enter Choice: ")
if menu_choice == 1:
test()
if menu_choice == 2:
test2()
if menu_choice == 3:
os.system("python")
except:
pass
As stated in the comments, raw_input returns a string and you'll need to cast it. BUT, you'd likely need to catch a ValueError for anything typed not a number.
Instead, you could do this
if choice == '1'
Same for menu_choice

Looping error (homework)

I'm having an issue with (apparently) a loop not working as intended. Assuming that everything else works as intended, my second while loop is (according to the grader) calling raw_input more times than necessary.
The code plays a word game. You can play a hand, replay a hand, or exit. Second loop determines if you play the hand or the computer.
All the called functions work correctly, but the loop, as I said is calling raw_input too many times.
Sorry if there are lots of other issues, I'm relatively new to coding.
userInput = ''
playInput = ''
hasPlayed = False
# while still playing, e exits
while userInput != 'e':
userInput = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ").lower()
if userInput not in 'nre':
print("Invalid command.")
elif userInput == 'r' and hasPlayed == False:
print("You have not played a hand yet. Please play a new hand first!")
print
else:
while True:
#
print
playInput = raw_input("Enter u to have yourself play, c to have the computer play: ").lower()
if playInput == 'u':
print
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
hasPlayed = True
elif playInput == 'c':
print
hand = dealHand(HAND_SIZE)
compPlayHand(hand, wordList, HAND_SIZE)
hasPlayed = True
else:
print("Invalid command.")
print
Your loop is working perfectly fine; it is looping forever just like you told it to:
while True:
What is missing then, is a way to exit that loop. Either test for a different condition:
playing = True
while playing:
# game
#
# stop playing with
playing = False
or explicitly break out of the loop with the break keyword:
while True:
# game
#
# stop playing with
break

Categories