I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
break
if position>4:
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
Everything is fine now, but when I run the program and search for an account. For example, when I search an account the output shows ('name', 'account has the balance of: ', 312) instead of name account has the balance of: 312 How do I fix this?
In the line
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
you should use string concatenation to add the different strings. One way to do this would be like this:
print(NamesArray[position] + " account has the balance of: " + str(BalanceArray[position]))
u are using old python version,
replace your line with this :
print(NamesArray[position] + "account has the balance of: " + (BalanceArray[position]))
use ' + ' instead of comma
Related
I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line by line but have had no luck. Would greatly appreciate a push in the right direction to get this code fixed.
from array import array
students=array()
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(promp, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def Main():
keepGoing=true
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__BC02.py__":
main()
I'm stuck trying to define the array. I know there is also additional errors, but I can't get pass this part.
Here is a version of your code that compiles and seems to run correctly:
students=[]
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(prompt, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def main():
keepGoing=True
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__main__":
main()
Most of the errors were basic typos. For the first error on line 3, I think it's best to use a standard Python list to store the data for each student. A list is created using [].
Trying to create a simple transaction simulation just for practice using if statements, but when input is requested it defaults to the same if and doesn't change even when string literal variables are set in place.
I've tired moving things around, but everytime I run the code and it prompts me with Type "Deposit or "Withdraw" it will skip over proceed1 variable, and default to the amount1 variable input by prompting the user to "how much would you like to deposit."
import time
checking = 0
savings = 0
proceed1 = "Checking" or "checking"
proceed2 = "Savings" or "savings"
deposit = "Deposit" or "deposit"
withdraw = "Withdraw" or "withdraw"
time.sleep(1)
print("Thank you for choosing the Bank of Kegan")
time.sleep(1)
choice = str(input("Type \"Deposit\" or \"Withdraw\" \n "))
if choice == deposit:
print("Deposit Transaction Initiated: Checking ")
time.sleep(.5)
print("Please choose an account you would like to Deposit into. ")
account_choice = str(input("Type \"Checking\" or \"Savings\" \n "))
if account_choice == proceed1:
print("Checking Account Loading... \n")
time.sleep(2)
print("Checking: $", checking, "\n")
time.sleep(2)
amount1 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount1, "Transaction Pending...")
time.sleep(2)
checking = (checking + amount1)
print("Your new balance is: ")
print("$", checking)
exit()
elif account_choice == proceed2:
print("Savings Account Loading... ")
time.sleep(2)
print("Savings: $", savings)
time.sleep(2)
amount2 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount2, "Transaction Pending... ")
time.sleep(2)
savings = (savings + amount2)
print("Your new balance is: ")
print("$", savings)
exit()
else:
print("Please choose a valid argument ")
elif choice == withdraw:
print("Withdraw Transaction Initiated: Checking ")
print("Type what account you would like to withdraw from. ")
choice2 = str(input("Checking or Savings"))
if choice2 == proceed1:
print("Withdraw Transaction Initiated: Checking ")
print("Checking Account Loading... ")
time.sleep(2)
print("Checking \n Balance: ", checking)
withdraw1 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw1, "withdraw transaction pending... ")
time.sleep(2)
if checking == 0:
print("You broke broke, make some money and come back later.")
else:
checking = withdraw1 - checking
print("your new balance is: $", checking)
elif choice2 == proceed2:
time.sleep(.5)
print("Savings Account Loading... ")
time.sleep(2)
print("Savings \n Balance: ", savings)
withdraw2 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw2, "withdraw transaction pending... ")
time.sleep(2)
if savings == 0:
print("You broke broke, make some money and come back later.")
else:
savings = withdraw2 - savings
print("your new balance is: $", savings)
else:
print("Please choose a valid argument.")
This is my atm, it has a pin code protection thing and can basically run like a normal atm, however i need to make it so it remembers you and your balance everytime you log out and in etc. ive tried doing this with a blank text file(nothing is in the text file) and linked it into my code (as you can see) but it doesnt work, im not sure what i have to add etc. any help?
balance = float(0)
userInput = None
path = 'N:\ATM.txt'
username = 'some_username'
with open(path, 'r') as file:
for user in file.readlines():
if user == username:
print("welcome back")
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
totalTrails = 3;
currentTrail = 0;
status = 1;
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"
You are opening the file in 'r' mode, which means read only, you should use 'r+' if you want to read and write in it.
You are not writing anything to the file - that's done by write() method - in your case
file.write("string I want to write to the file");
After you are done writing to the file, close it - file.close()
I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!
So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N