below is my code that I have worked on to get this bank atm assignment going. I can't seem to add and subtract into the balance of the code. I'm pretty sure I'm doing something wrong. Below is what the part of what the assignment entails. Everything else is in working order in regards to choosing option P, S, and E. Options D, and W are where I have run into a problem. Any help would be great. Thanks!
If the user types D then:
· Ask the user for the account number.
· Search the accountnumbers() array for that account number and find its position.
· Ask the user for the amount to be deposited.
· Add the deposit amount to the balance for that account.
· If the user types W then:
· Ask the user for the account number.
· Search the accountnumbers() array for that account number and find its position.
· Ask the user for the amount to be withdrawn.
· Subtract withdrawal amount from the balance for that account.
namelist=[]
accountnumberslist=[]
balancelist=[]
def populatelist():
print ('Great! Please enter the information below')
namecount=0
#This loops collects the five names,accounts,balances, and appends them to the namelist
while(namecount< 2):
name= input('Enter a name: ')
namelist.append(name)
accountnumber = input('Please enter your Account Number: ')
accountnumberslist.append(accountnumber)
balances = input('Please enter your Balance: ')
balancelist.append(balances)
namecount = namecount + 1
return
def displayall():
print ('I am inside display function')
position =0
#This loop, prints one name at a time from the zero position to the end.
while ( position < 2):
displayone(position)
position = position + 1
return
def displayone(position):
print ('Account Holder:',namelist[position])
print ('Balance:',balancelist[position])
return
def calculatedeposit():
position = 0
while (position < 2):
depamount = int(input('Please enter the amount to deposit'))
balancelist[position] = balancelist[position] + depamount
position = position + 1
return
def calculatewithdrawal()
position = 0
while (position < 2):
withmount = int(input('Please enter the amount to deposit'))
balancelist[position] = balancelist[position] + withamount
position = position + 1
#What does it receive. Account Number to search.
#what does it do? Searches for the Account Holder.
#what does it send back. Position of the Account Holder, if not found, -1
def searchforacct(accounttosearch):
foundposition=-1 # assume that it is not going to be found.
position=0
while (position < 2):
if (accounttosearch==accountnumberslist[position]):
foundposition = position
break
position = position + 1
return foundposition
#This function will display the menu, collect the users response and send back
def displaymenu():
print ('Enter P to Populate Data')
print ('Enter S to Search for Account ')
print ('Enter D to Deposit Amount ')
print ('Enter W to Withdraw Amount ')
print ('Enter E to Exit')
choice = input('How can we help you today?:')
return choice
print("=====================================")
print(" Welcome to Liberty City Bank ATM ")
print("=====================================")
#main
response=''
while response!= 'E' and response!='e':
response = displaymenu()
if response=='P' or response=='p':
populatelist()
elif response=='S' or response=='s':
accounttosearch = input('Please enter the Account Number to search:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
displayone(foundpos)
elif response=='D' or response=='d':
accounttosearch = input('Please enter the Account Number for Deposit:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
calculatedeposit()
elif response=='W' or response=='w':
accounttosearch = input('Please enter the Account Number for Withdrawal:')
foundpos = searchforacct(accounttosearch)
if ( foundpos == -1 ):
print ('Account not found')
else:
calculatewithdrawal()
elif response=='E' or response=='e':
print ('Thank you for choosing Liberty City Bank!')
print ('Have a Nice Day!')
else:
print ('Invalid choice. Please try again')
Your code wont compile, on line 45 add a : following your def. On line 45 change withamount to withmount. Then on Line 45 change
balancelist[position] = balancelist[position] + withamount
to this
balancelist[position] = int(balancelist[position]) - withamount
You need to cast the string in your balance list to an int. You also need to subtract (-) not add (+) from the list as its a withdrawal.
There are a few other bugs in your code but thats enough to get you up and running.
Instead of looking at the 'account' you found from the users input, you loop through the first 2 balance lists and add a user given value.
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...
I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete code.
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4
USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")
def verify(playerNumbers, winningNumbers):
if playerNumbers == winningNumbers:
print("Congratulations! You Win ${}!".format(MONEY_WON))
print("Your numbers: ", playerNumbers, )
print("The winning lottery numbers were: ", winningNumbers)
else:
print("Sorry, you lose...")
print("Your numbers: ", playerNumbers)
print("The winning lottery numbers were: ", winningNumbers)
# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
def get_user_nums():
user_nums = []
while len(user_nums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
if nums not in user_nums:
user_nums.append(nums)
else:
print("Sorry, you have already inputted that number")
else:
print("Sorry, Your number was not in range")
return sorted(user_nums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def play_pick_n():
user_nums = get_user_nums()
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
# 'main', calls the other functions
def main():
# lottery_menu()
while True:
choice = input("\nPlay?: Yes or No: ")
if choice == 'Yes':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n' + len(string) * "-"
print(dotted, string, dotted)
play_pick_n()
break
elif choice == 'No':
print("Thanks for playing!\n")
break
print("Sorry, that is not a valid input. \nPlease enter either Yes or No")
if __name__ == '__main__':
main()
Thanks for any help.
if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()
for week in range(0, WEEKS_PLAYED):
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.
The deposit function and the withdraw function doesn't work. After populating the accounts, I can select D or W menu options and input any number without causing the program to crash or causing an error. The program seems it is working correctly but when you check the balances using the S option, they are not updated.
Names=[]
accountnumbers=[]
balance=[]
def populatelist():
position=0
while(position<=2):
yourname= str(input("Please enter a name: "))
Names.append(yourname)
account = int( input("Please enter an account number: " ))
accountnumbers.append(account)
totalbalance = int( input("Please enter a balance: "))
balance.append(totalbalance)
position = position + 1
##################################### DEPOSIT FUCNTION
def deposit(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
#################################### WITHDRAW FUNCTION
def withdraw(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def findingaccount(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def menuoptions():
print ("**** MENU OPTIONS ****")
print ("Type P to populate accounts")
print ( "Type S to search for account")
print ("Type E to exit")
print ("Type D to deposit Amount")
print ("Type W to withdraw Amount")
choice = str(input("Please enter your choice: "))
return choice
response=""
while response!= "E":
response = menuoptions()
if response=="P":
populatelist()
########################### Deposit OPTION
elif response=="D":
searchaccount = int(input("Please enter the account number to add deposit: "))
foundtheposition = deposit(searchaccount)
money = int(input("Please enter the amount to be deposited: "))
money + (balance[foundtheposition])
########################### WITHDRAW OPTION
elif response=="W":
searchaccount = int(input("Please enter the account number to withdraw: "))
thenumber = withdraw(searchaccount)
withdraw = int(input("how much for withdraw"))
withdraw - (balance[thenumber])
if (balance[thenumber]) < withdraw :
print("ERROR: Not enough balance")
elif response=="S":
searchaccount = int(input("Please enter the account number to search: "))
foundaposition = findingaccount(searchaccount)
if ( foundaposition == -1 ):
print ("The account number not found!")
else:
print ("Name is:" + str( Names[foundaposition]))
print (str(Names[foundaposition]) + " " + "account has the balance of :" +str(balance[foundaposition]))
elif response=="E":
print ("Thank you for using the program.")
print ("Bye")
exit
else:
print ("Invalid choice. Please try again!")
You have logic error.
Just change
money + (balance[foundtheposition])
to
balance[foundtheposition] = balance[foundtheposition] + money
or using short-hand operator like
balance[foundtheposition] += money
Same for
withdraw - (balance[thenumber])
Cheers ...
Your deposit scenario needs to add the amount into the selected account:
balance[thenumber] += money
Fair warning there are other errors in your program besides the accounts not updating.
dnlist = ["Place 1","Place 2","Place 3"]
polist = []
splist = []
dncount = 3
count = 0
def prices ():
while count <= dncount:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Please enter the details for ",dnlist[count])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#Ask for the dp
try:
sp = int(input("the dp is $"))
print(sp)
except ValueError:#Make sure they only input numbers
print("Sorry, you must put number only.")
splist.append(sp)
#Ask for the po
try:
po = int(input("the po is %"))
except:
print("Please enter a valid number.")
#This is to ensure that the customer enters a reasonable percentage
if po <=10: print("Your percentage is too low. Please enter a higher percentage.")
if po >=95: print("Your percentage is too high. Please enter a lower percentage.")
polist.append(po)
prices()
This program works for Place 1 however, it does not move on asking the dp and po of Place 2 and Place 3
when I run the program, it does not stop asking for entering details for Place 1 but I want my program to work this way..
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please enter the details for Place 1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
the dp is $21
21
the po price is %34
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please enter the details for Place 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
the dp is $98
98
the po is %24
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please enter the details for Place 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
the dp is $109
109
the po is %87
Just a minor modified version to make it work. But it is not very good to use count in this way. Assign it to a variable inside your function would be better
dnlist = ["Place 1","Place 2","Place 3"]
polist = []
splist = []
dncount = 3
count = 0
def prices():
while count <= dncount:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Please enter the details for ",dnlist[count])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#Ask for the dp
try:
sp = int(input("the dp is $"))
print(sp)
except ValueError:#Make sure they only input numbers
print("Sorry, you must put number only.")
splist.append(sp)
#Ask for the po
try:
po = int(input("the po is %"))
except:
print("Please enter a valid number.")
#This is to ensure that the customer enters a reasonable percentage
if po <=10: print("Your percentage is too low. Please enter a higher percentage.")
if po >=95: print("Your percentage is too high. Please enter a lower percentage.")
polist.append(po)
global count
count += 1
prices()
second version to avoid warning of count
dnlist = ["Place 1","Place 2","Place 3"]
polist = []
splist = []
dncount = 3
count = 0
def prices(count):
while count < dncount:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Please enter the details for ",dnlist[count])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#Ask for the dp
try:
sp = int(input("the dp is $"))
print(sp)
except ValueError:#Make sure they only input numbers
print("Sorry, you must put number only.")
splist.append(sp)
#Ask for the po
try:
po = int(input("the po is %"))
except:
print("Please enter a valid number.")
#This is to ensure that the customer enters a reasonable percentage
if po <=10: print("Your percentage is too low. Please enter a higher percentage.")
if po >=95: print("Your percentage is too high. Please enter a lower percentage.")
count += 1
prices(count)
Like many here, I'm new to Python. I'm working on a snippet that asks the user to give their ID, then checks to see if the ID is exactly 6 digits in length. Then the code will ask the user to confirm their ID and if they mistyped, allows them to reset it. If the user confirms their entry was correct, then it asks for a location ID and follows the same path. If both IDs are confirmed, the user then can move on to the rest of the project.
This is something that will have to be input at the start of every use.
The issue I'm running in three sided.
1.) I can enter the empID 101290 and sometimes it tells me it's a valid entry while others it wont (but 101256 works regardless - both are 6 digits)
2.) Entering "1," to confirm the ID, the code moves to block 2 and asks for location ID but if the user enters "2" to say the Employee ID is wrong, it moves on anyway.
Any advice on what's in need of change here?
import time
print('What is your employee ID?') #user assigned ID
empID = input()
while empID != 0:
print('Try again.')
empID = input()
# employee ID is only 6 digits in length, no letters
if len(empID) != 6:
print('Try again.')
elif len(empID) == 6:
print('Thank you. Your ID is set to ' + empID + '.')
time.sleep(.5)
print('Is this correct?'''
'[1] Yes [2] No ')
yesNo = input()
while True:
yesNo == '1'
print('Thank you. ID set.')
break
# reset ID
else:
print('ID has been reset. Please enter your employee ID.')
empID = input()
break
break
#Store Location ID
print('What is your Location ID?')
locID = input()
while locID != 0:
print('Try again.')
locID = input()
# store locations are 3-5 digits
# TODO: prepend any input with less than len 5 with 0
if len(locID) != 5:
print('Try again.')
elif len(locID) == 5:
print('Thank you. Your location is set to ' + locID + '.')
time.sleep(.5)
print('Is this correct?'''
'[1] Yes [2] No ')
yesNo = input()
while True:
yesNo == '1'
print('Thank you. Location ' + locID + 'set.')
break
else:
print('Location ID has been reset. Please enter your location code.')
empID = input()
break
break
break
#next
I see some Bugs in your code to start with.
while True:
yesNo == '1'
yesNo == '1' is a condition statement which returns true or false depending on the user input, but it is not used in as a condition anywhere
if len(empID) != 6:
print('Try again.')
elif len(empID) == 6:
`elif len(empID) == 6:` is redundant.. a simple else will do
What I would do is:
Define functions to validate the user credentials:
def isEmpID(id):
'''
Employee ID is 6 characters in Length
'''
if len(id) != 6:
return False
return True
def isStoreID(id):
'''
Store ID is 3-6 characters in Length
Note: The function when called with id, checks if the length is between (exclusive) 3 and (inclusive) 6 and returns true if condition is satisfied else false which is the default return policy
'''
if 3 < len(id) <= 6:
return True
return False
validEmpID = False
validStoreID = False
while not (validEmpID and validStoreID): # Both has to be True to exit the loop, Otherwise the condition continues to go to True.
if not validEmpID:
print('Enter Employee ID:')
empID = input()
validEmpID = isEmpID(empID)
if not validEmpID:
print('Invalid Employee ID\nTry Again...\n')
continue
print('Enter Store ID:')
strID = input()
validStoreID = isStoreID(strID)
if not validStoreID:
print("Invalid Store ID\nTry Again!...\n")
continue
Here the loop exists or in other words continue executing the code afterwards only if both the variables are True