Here is a little bit of code suposed to create a list of expenses with name and amount:
def make_list():
expense_list = []
for count in range(1, 5):
print "expense number" + str(count) + ":"
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
return expense_list
make_list()
What am I doing wrong? Even in interactive mode I can't seem to figure out how to get my item.
Your indentation is wrong, you never actually add anything to your list and you don't assign the returned list to anything. Also, the "magic number" (5) isn't ideal. Try:
def make_list(n):
expense_list = []
for count in range(1, n+1):
print "expense number {0}:".format(count)
name = raw_input(' enter expense name: ')
amount = raw_input(' enter expense amount: ')
expense_list.append((name, amount))
return expense_list
l = make_list(4)
print l
Related
Today I tried the code below to add users into bank and deposit or withdraw funds:
class BankAccount:
owner: str
amount: int
min_amount: int
id: int
def deposit(self, x):
self.amount += int(self.amount) + x
test = [
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
BankAccount(),
]
while True:
try:
print(
'Press enter: \nW) to withdraw. \nD) to deposit and \nT) to do transactions and \nA) to add users \nL) to check '
'the user information')
response = input('>>> ')
if response == 'A':
test.append(BankAccount)
user_id = int(input('Enter ID (0 to 10): '))
test[user_id].owner = input('Enter name: ')
test[user_id].amount = input('Enter the balance: ')
dummy = int(input('Press enter to return.'))
elif response == 'D':
user_id = int(input('Enter user ID: '))
a = int(input('Enter amount: '))
test[user_id].deposit(a)
dummy = int(input('Press enter to return.'))
elif response == 'L':
user_id = int(input('Enter user ID: '))
print('Name: ', test[user_id].owner.capitalize())
print('Balance: ', test[user_id].amount)
dummy = int(input('Press enter to return.'))
else:
print('Invalid input!')
except ValueError:
print('Invalid input!')
Whenever I create a user and try to user the deposit option add some funds I get this type error:
self.amount += int(self.amount) + x
TypeError: can only concatenate str (not "int") to str
So, it's complaining that you can't perform "string + int". This is happening because your code for making a user account takes the amount property as a string:
if response == 'A':
test.append(BankAccount)
user_id = int(input('Enter ID (0 to 10): '))
test[user_id].owner = input('Enter name: ')
test[user_id].amount = input('Enter the balance: ') # <--- amount becomes string
dummy = int(input('Press enter to return.'))
To fix this, replace this with:
if response == 'A':
test.append(BankAccount)
user_id = int(input('Enter ID (0 to 10): '))
test[user_id].owner = input('Enter name: ')
test[user_id].amount = int(input('Enter the balance: ')) # <--- int() makes this an integer
dummy = int(input('Press enter to return.'))
Now, upon depositing, you're doing int + int, and it works! Output:
Press enter:
W) to withdraw.
D) to deposit and
T) to do transactions and
A) to add users
L) to check the user information
>>> A
Enter ID (0 to 10): 1
Enter name: Yeet
Enter the balance: 10
Press enter to return.
Invalid input!
Press enter:
W) to withdraw.
D) to deposit and
T) to do transactions and
A) to add users
L) to check the user information
>>> D
Enter user ID: 1
Enter amount: 2
Press enter to return.
One more tip. In your class, the deposit function is not behaving the way you would expect. You want to add x (deposit amount) to the existing amount. Instead of:
class BankAccount:
def deposit(self, x):
self.amount += int(self.amount) + x # <--- Amount = amount + amount + x, this is probably not what you want
You probably want:
def deposit(self, x):
self.amount += x # <--- Amount = amount + x
that's because input function return is a string by default, you must cast it into int for your "amount".
While creating the bankaccount ( when response == 'A' ) You meant to make test[user_id] = int( input( ... ) ).
You missed the int.
Also, What is the purpose of adding the class to the list everytime an account is created?
If you meant to create an instance of the class you forgot the BankAccount () .
I'm guessing you reproduce this error after adding a new user, then depositing funds?
If so, this is your issue:
test[user_id].amount = input('Enter the balance: ')
You need to convert the user input to an int before setting amount. Here is the correct code:
test[user_id].amount = int(input('Enter the balance: '))
If you want to guard against this condition in general, I would suggest you check out properties as this will allow you to ensure you're always dealing with an int when you're adding to amount, regardless of source.
I am not sure if you chose not to include it, but be sure you have an init() function to create instances of your class. Here's the Python docs on classes: https://docs.python.org/3/tutorial/classes.html
I want to write a program that accept input from users multiple times. Calculate and print the average age as well as the number of males and females. Every time I run the script I get ZeroDivisionError: integer division or modulo by zero Also when I use the sum(ages) it returns 0. I need help please
print('Enter the required lines of text.')
print('Enter an empty line to quit.')
print('For sex enter M for male and F for female.')
print ('_____________________________________________________________')
# Start with a list containing several names.
names = list()
genders = list()
ages = list()
total = sum(ages)
average = total / len(ages)
# variables to append
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = raw_input('Enter Age: ')
# while NOT the termination condition
while new_name != '':
names.append(new_name)
genders.append(new_sex)
ages.append(new_age)
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = raw_input('Enter Age: ') # !! reset value at end of loop!
print('The sum of age is:', total)
for new_name in names:
for new_age in ages:
for new_sex in genders:
print(names)
print(genders)
print(ages)
print(average)
Here is the problem:
average = total / len(ages)
there is only one division in the code... so that is not big surprise, where division by zero happens.
If you have a list o users - keep it like that:
users = list()
name = raw_input('Enter Name: ')
sex = raw_input('Enter Sex: ')
age = raw_input('Enter Age: ')
user = {'name': name, 'age': age, 'sex': sex}
users.append(user)
You can do raw_input inside while loop, without that initial part. Just query, and append.
To avoid error - calculate information after input. Right now - average is calculated with zero input...
Final for loops - for every name you call another loop, where for every age, you call another loop where for every sex... I don't think it is what is needed. With your design - assume that all list has same length, create iterator, and get elements by index. Then be sure lists are with same length. Or... use users.
I was able to figure it out. Thanks to everyone for the help and support
genders = list()
ages = list()
# holds the gender ages
genderm = list()
genderf = list()
countm = list()
countf = list()
# while loop for termination condition
while True:
new_name = raw_input('Enter Name: ')
new_sex = raw_input('Enter Sex: ')
new_age = int(raw_input('Enter Age: '))
# Append the input to the list
names.append(new_name)
genders.append(new_sex)
ages.append(new_age)
# Male age count
if new_sex == 'M':
countm.append(new_age)
genderm.append(new_sex)
# Female age count
elif new_sex == 'F':
countf.append(new_age)
genderf.append(new_sex)
# !! reset value at end of loop!
testanswer = raw_input('Press y to make another entry')
if testanswer.upper() == 'Y':
continue
# result of the input
print('Number of Females (F): ', genders.count('F'))
print('Number of Males (M): ', genders.count('M'))
print('Average Male Age: ', sum(countm) / len(genderm))
print('Average Female Age: ', sum(countf) / len(genderf))
break # exit```
Hi im pretty new to Python so I'm guessing im making a pretty obvious mistake here but basically what i'm trying to get my code to do here is to take in 5 products and their prices from the user, the products are working however when the user enters a price that is above 0 the message saying "Please enter a price above 0" is displayed, this is my code below, any help for a newbie is much appreciated thanks.
#Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
valid = True
price.append(tempCost)
Well the main key here is to loop if the condition didn't occur
products = []
price = [] #declare lists
def inputPrice():
for counter in range(1,6):
print ("Enter Product {} out of 5".format(counter))
tempItems = input() #declare temp variable to hold input value
while tempItems == '': #validate input
print ("Incorrect Product ...")
print ("Please enter a valid product")
tempItems = input()
#when reading in price if statement is added for validation
print ("Enter the price of Product {} out of 5".format(counter))
tempCost = int(input())
while tempCost <=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
tempCost = int(input())
products.append(tempItems)
price.append(tempCost)
print('products' , products)
print('price' , price)
inputPrice()
Update Your Code add while loop to take prices from user
Lists of products and prices
products = []
price = [] #declare lists
total = 0 #declare variable to hold total of prices
#function which is used to read in values to each list in turn
#range has been set to read in 5 values
def inputPrice():
for counter in range(0,5):
valid = False
print (counter+1, "Enter 5 Products:")
tempItems = input() #declare temp variable to hold input value
products.append(tempItems) #add this value into our list
#when reading in price if statement is added for validation
while True:
print (counter+1, "Enter their prices:")
tempCost = int(input())
if tempCost<=0: #validate input
print ("Incorrect price....")
print ("Please enter a price above 0")
else:
break
else:
valid = True
price.append(tempCost)
inputPrice()
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.
trying to make a program that prompts user to enter a famous peoples names and continues asking until they type "done" and prints out the list with the names and the number of names. could anyone give me a little help?
def main():
cList = []
cName = []
while cName != ("done"):
cList.append(cName)
cName = input("Enter another name: ")
print("# of names entered: "), [cList]
i = 0
while i < len(cList):
print myList[i]
i += 1
return
main()
Like this?
names = []
while True:
names.append(raw_input('Enter name: '))
if names[-1] == 'done':
names.pop()
break
print("# of names %i" % len(names))
for name in names:
print(name)