okay two questions my instructor wants me to break my code after my else statement because the menu() function keeps repeating itself after "customer not found" but I don't understand what she means also for some reason my code only runs using only the first name in the "customers" list instead of all the names if anybody could point out the flaws in my code that would be great thank you.
#Program 3 BankApp
def customerind(customer):
ind = ""
for i in range(len(customers)):
if customer == customers[i]:
ind = i
if ind != "":
return ind
else:
print("customer not found")
def printbalance(index):
print("your remaining balance is", balances[index])
def menu():
print("type D to deposit money", customer)
print("type W to withdraw money", customer)
print("type B to display balance", customer)
print("type C to change user", customer)
print("type E to exit", customer)
def withdraw(index, withdrawAmt):
if withdrawAmt < balances[index]:
balances[index] = balances[index] - withdrawAmt
else:
print("you went over your balance")
def deposit(index, depositAmt):
balances[index] = balances[index] + depositAmt
global customers
customers= ["Mike", "Jane", "Steve"]
global balances
balances= [300, 300, 300]
global index
customer= input("what is your name?")
index= customerind(customer)
printbalance(index)
answer= ""
while answer != "E":
menu()
answer= input("what is your menu choice?")
if answer=="C":
customer= input("who are you?")
index= customerind(customer)
if answer== "W":
withdrawAmt = float(input("how much did you want to withdraw today?"))
withdraw(index, withdrawAmt)
printbalance(index)
if answer=="B":
printbalance(index)
if answer=="D":
depositAmt = float(input("how much did you want to deposit today?"))
deposit(index, depositAmt)
printbalance(index)
You have a few issues here.
1. "for some reason my code only runs using only the first name in the "customers" list"
In your customerind function, you are printing "customer not found" after only the first iteration. You need to move the else statement outside of the for loop so that it can iterate through all of the names.
def customerind(customer):
#Iterate through each name, and see if there is a match.
for i in range(len(customers)):
if customer == customers[i]:
return i #If we found the name, instantly return the index.
#Outside of the for loop, will get called once above finishes iterating through all names.
return -1 #Return -1 if no match, since the index can be any value 0 -> Infinity
So the way this function works now, is that if the name is found in the for loop, then it returns the index. If the name is not found after iterating through all of the names, then the function will return -1.
Now that this function is setup a bit better, let's look at your main code at the bottom...
menu() is constantly being called so long as the user does not type E. So then if you want to automatically exit if the customer is not found, you should do something like this:
answer= ""
while answer != "E":
menu()
answer= input("what is your menu choice?")
if answer=="C":
customer= input("who are you?")
index= customerind(customer)
if index == -1:
print('Customer not found. Exiting...')
break #Break out of the while loop above so the program exits.
if answer== "W":
withdrawAmt = float(input("how much did you want to withdraw today?"))
withdraw(index, withdrawAmt)
printbalance(index)
if answer=="B":
printbalance(index)
if answer=="D":
depositAmt = float(input("how much did you want to deposit today?"))
deposit(index, depositAmt)
printbalance(index)
Related
Basically I'm doing a multiple choice question president quiz on who served before the others in said multiple choice question. I've gotten it down fully looped with out the randomness but now I've incorporated arrays and random questions, basically I need to figure out how to make multiple choice questions and then define the logic so that when a person inputs 1,2, or 3 the game will look at all three listed options and know which one is the lowest on the presidents list to identify the correct answer.
lives = True
import array
import random
print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()
def answer():
if response == presidents
def lifeCount():
if livesRemaining == 0:
print("You're out of lives! Good luck trying again!")
quit()
if livesRemaining == 0:
quit()
while lives:
presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
"Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
"Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
"Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]
livesRemaining = 3
print("Nice to meet you", userName,)
print("Today you'll be taking a quiz on which U.S President served first out of three options!")
print("You'll have only three chances to mess up! Let's get started!")
print("Choose either number 1 2 or 3 on your keyboard!")
print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents))
response = input()
if response == "1":
print("Correct! 1/10!")
else:
livesRemaining -= 1
print("Incorrect!")
lifeCount() ```
Objective A mini bank simulation using only python basics list,while loop,if else.
Issues 2. Search account.
Notes I want my program to return the respective age and balance of the matching name.Thanks in advance.
print("""1. Add Account
2. Search Account"
3. Exit \n\n""")
name = []
age = []
balance = []
while True:
choice = input("What is your choice ? : ")
if choice == "1":
name.append(input("Name : "))
age.append(input("Age : "))
balance.append(input("Balance : "))
print("Account Registration Done\n\n")
if choice == "2":
y = input("What is your Account Name ? > : ")
if y in name: # i want my program to return the respective age and balance of the matching name.
print(name[0]) # Here is the issue and i don't know how to fix.Please Kindly enlighten me
print(age[0])
print(balance[0])
else:
print(
f"Your name[{y}] have't registered yet.Please register first")
if choice == "3":
break
The most recently added bank account in your code will be the bank account at the end of the lists. You can access it by name[-1], age[-1], and balance[-1]. Negative indices in Python mean searching backwards so -1 gives you the last element of a list.
To search for an account you can do:
if y in name:
found = name.index(y)
Then you can do age[found] and balance[found] to get the respective age and balance.
If you're adding new elements to the end of the list (ie .appending() them), you can list[-1] to get the last (therefore newest) element in the list.
In my computer's class we were tasked with creating a text adventure game in python. I've gotten something down already, but I could only get so far with my knowledge. I'm probably missing something super simple, but I'm just stuck right now.
It's a multiple choice deal where the character is presented with 3 options, look around, move or access inventory. I'm stumped at how to make the code go off on it's own tangent.
I have it to where the player can get a description of their surroundings, but if they do and the options come back up, it sort of bugs out and displays the options again and then the next player input stops the code all together. So if the player "Looks around" and then decides they want to "Move" the code stops.
And, in the first area, there are two directions you can go, north and east. Even if you go East and then look around you get the description of what the Northern room looks like.
Also, I need help getting an inventory system fleshed out. I have no idea how i'd do that.
And there are certain times in the game (at least I planned to have them included) where the player could make statements like "Get insert item here" how would I create those actions?
Here's the code.
import random
import time
print ("You awake in what looks like an adandoned diner with a pounding headache.")
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
while d1a != "1" and d1a != "2":
#add option 3 to the loop
d1a = input ("What would you like to do?")
if d1a == "1":
print()
print ("It looks like an old diner. Dust and grime coat the tables, chairs and counter tops. You see a door to the North and another to the East.")
print()
time.sleep(1.5)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
elif d1a == "2":
d2a = input ("""Where?
North
West
South
East""")
while d2a != "North" and d2a != "north" and d2a != "West" and d2a != "west" and d2a != "South" and d2a != "south" and d2a != "East" and d2a != "east":
d2a = input ("Where?")
if d2a == "North" or d2a == "north":
print()
print ("You go through through the door to the North")
print ("which has lead to you what looks to be the kitchen")
print()
time.sleep(1)
elif d2a == "East" or d2a == "east":
print()
print("You step through the door to the east which")
print ("takes you out to the streets. They look")
print ("musty and old, cracks ravaging the asphalt.")
print()
time.sleep(1)
elif d2a == "West" or d2a == "west":
print()
print ("I can't move there.")
print()
time.sleep(1)
elif d2a == "South" or d2a == "south":
print()
print ("I can't move there.")
print()
time.sleep(1)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
while d1a != "1" and d1a != "2":
#add option 3 to the loop
d1a = input ("What would you like to do?")
if d1a == "1":
print()
print ("Must be the kitchen area. You can see stoves, ovens, cabinets containing pots and pans. A dishwasher is open exposing a group of knives. If they're clean or not is unknown.")
print()
time.sleep(1.5)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
elif d1a == "2":
d2a = input ("""Where?:
North
west
south
East""")
Sorry, I'm relatively new to coding, my class just started delving into it but I wanted to test what I could do with this game.
I think that when you move North/east, you should assign a variable, 'location', for example, to the place you move to. then, when you look around, you should use an if statement to see what the location is and then write the correct description.
Okay so I'm very new to the programming world and have written a few really basic programs, hence why my code is a bit messy. So the problem i have been given is a teacher needs help with asigning tasks to her students. She randomly gives the students their numbers. Students then enter their number into the program and then the program tells them if they have drawn the short straw or not. The program must be able to be run depending on how many students are in the class and this is where i am stuck, I can't find a way to run the program depending on how many students are in the class. Here is my code
import random
print("Welcome to the Short Straw Game")
print("This first part is for teachers only")
print("")
numstudents = int(input("How many students are in your class: "))
task = input("What is the task: ")
num1 = random.randint(0, numstudents)
count = numstudents
print("The part is for students") #Trying to get this part to run again depending on number of students in the class
studentname = input("What is your name:")
studentnumber = int(input("What is the number your teacher gave to you: "))
if studentnumber == num1:
print("Sorry", studentname, "but you drew the short straw and you have to", task,)
else:
print("Congratulations", studentname, "You didn't draw the short straw")
count -= 1
print("There is {0} starws left to go, good luck next student".format(count))
Read up on for loops.
Simply put, wrap the rest of your code in one:
# ...
print("The part is for students")
for i in range(numstudents):
studentname = input("What is your name:")
#...
Also, welcome to the world of programming! :) Good luck and have fun!
I am attempting to create a program that has 4 functions, getStocks, searchStocks, printStocks, and then the main function that uses the other three.
My issue is that I want to make it so that if the stock you searched for is the highest stock, I want the message "There are no higher stocks" to appear as the output instead of empty space, but I am unsure what and where I would need to add to do that. I have the "noHigherStocks" variable as the message I want displayed, but where am I to implement it? I feel as though I should use an else statement in the main function, but I can't think of where it would make sense to put it. Thanks for reading! any help or tips would be greatly appreciated :-)
def getStocks():
stockNames = []
stockPrices = []
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while name != 'done':
stockNames.append(name)
stockPrices.append(price)
name = str(input("What is the name of the stock?"))
if name != 'done':
price = int(input("what is the price of that stock?"))
return (stockNames, stockPrices)
# returns a single value pertaining to the found price
def searchStocks(stockNames, stockPrices, s):
for i in range (len(stockNames)):
if stockNames[i] == s:
return stockPrices[i]
return -1
# print the names of stocks whose price is higher than p.
def printStock(stockNames, stockPrices, p):
i = 0
while i <len(stockPrices):
if p < stockPrices[i]:
print(stockNames[i])
i = i + 1
return
def main():
n,p = getStocks()
stock = str(input("what stock are you searching for?"))
price = searchStocks(n,p,stock)
printStock(n,p,price)
noStocksHigher = str('There are no stocks higher than',stock)
main()
This might be solved using the max() builtin. Since you already know the price of the stock for which you searched, you could just compare that price against the highest price in p, and if equal, print your message, otherwise search the list.
Starting where you call searchStocks:
price = searchStocks(n,p,stock)
if max(p) == price:
print('There are no stocks higher than',stock)
else:
printStock(n,p,price)
This should do the trick.