How to add a float to an amount in a class - python-3.x

I have a code to make a banking app. I need to make sure that the input can take in any number including decimals but not take in letters or other symbols.
Ive tried using a float instead of int
if selection == 1:
if initial_balance > 1:
print("\nAn account has already been opened. Please select another
option.")
print(menu)
else:
name = input("\nEnter the account owner's name: ")
# While loop to make sure user puts valid initial deposite
while True:
initial_balance = input("Enter your initial balanc: $")
try:
float(initial_balance)
except ValueError:
print("Sorry, Please deposit one or more dollars.")
continue
if initial_balance < 1:
print("Please deposit one or more dollars.")
continue
else:
balance += initial_balance
print("\nAccount owner: " + name)
account = BankAccount(initial_balance)
print("Initial balance: $ " + str(initial_balance))
print(menu)
break
break
expected:
enter an initial balance : 20.75
account owner: jimmy
initial balance: $20.75
actual:
enter an initial balance : $20.75
sorry please deposit one or more dollars

while True:
initial_balance = input("Enter your initial balanc: $")
try:
float(initial_balance)
You are applying float to the initial balance, but you are not updating the variable, so it remains in string format. Below is a fixed version.
while True:
initial_balance = input("Enter your initial balanc: $")
try:
initial_balance = float(initial_balance)

Related

Use a while loop for making a user answer the same qn again in python

Guys how do I make the user enter the answer again for entering less or more characters than required for their full name. for example if a user enters Alex as his full name he should enter his full name again as the amount of characters are too low. ()
while True:
usr_input = str(input("What is your full name? "))
if len(usr_input) <= 3:
print("Please Enter Full Name.")
elif len(usr_input) >= 30:
print("Input string is too long")
else:
pass
# other code goes here
There make sure to delete the pass statement and add your own code

My code isn't running after I break a while loop even though there is code after it

I tried making a rock-paper-scissors game, and to make sure that the user entered a number, I made a while loop. But after the user entered a number, the loop breaks but it won't keep running the game itself after it. How do I fix this?
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if main_choice == 1:
play_game()
I see others have placed the answer in the comments... but I'll place the full example in here. You need to convert your input into an integer to be able to compare it (or the 1 into a str).
The line that needs to change:
if main_choice == 1:
Change to:
if int(main_choice) == 1:
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if int(main_choice) == 1:
print("Game is now being played")
Gives the output:
Please enter the number that matches your choice:
1
Game is now being played

How do I calculate the total sum of my cart to my dictionary list based on user input menu?

I have created a simple menu to add things based on user input.
dictionary = {"Service A": 100, "Service B": 200}
cart = []
def main():
while(True):
print("1. List of Services")
print("2. Payment")
print("3. Exit")
print("\nServices you have added:", cart)
a = input("Please enter a choice: ")
if a=="1":
Q1()
elif a=="2":
Q2()
elif a=="3":
break
def Q1():
print('1. Service A : $100/year')
print('2. Service B : $200/year\n')
service = input("Enter the service 1-2 that you would like to add: ")
if not service.isnumeric():
print('Please enter valid choice number!')
elif service.isnumeric():
print(f'\nYou have selected choice number {service} which is: ')
if service == '1':
print ('\n''1. Service A: $100/year.''\n')
cart.append ("Service A")
if service == '2':
print ('\n''2. Service B: $200/year.''\n')
print('You will be return to main menu.')
cart.append ("Service B")
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
main()
del(cart)
print("Goodbye and have a nice day!")
I need help in def Q2():
I want the services that I have added to my cart referencing to the dictionary list to get the total sum.
I'm not sure what is the exact codes. Please go easy on me, I'm a beginner.
def Q2():
print("\nServices you have added:", cart)
#total = sum(cart)
#print('\nYour subscription will be a total of :',total)
def Q2():
print("\nServices you have added:", cart)
total = 0
for i in cart:
total = total + dictionary[i]
#total = sum(cart) #This line of code will only merge the selected strings, not the sum of the numbers we need. Because the user added to the list named cart is a string instead of a number
print('\nYour subscription will be a total of :',total)
Hello, thank you for your question.
I added my note after the line of total = sum(cart) code: Because the user added to the list named cart is a string instead of a number. So we can use the for loop to use each string element in the cart as the key value of the dictionary to correspond to its value, and sum all the corresponding values, and finally declare a regional variable named total and store the sum.

Notify user if wrong data type entered (Python 3)

How do I change this code so that the program can notify the user that he/she has entered a text instead of a number?
Enter_a_Number = int(input("Enter a Number: "))
if Enter_a_Number == str:
print("Only Numbers Allowed")
You need to explore the basics of error-handling.
See Python.org Tutorial - Handling Exceptions
while (True):
try:
Enter_a_Number = int(input("Enter a Number: "))
break
except ValueError:
print("Invalid number")
print(Enter_a_Number)
In this specific case, the int() function will 'throw' a ValueError if it can not convert the string to an integer. You can decide what to do when that happens.

how can i fix this list index issue, or is there a better way to handle a 'user account'

balance=UBal[UName.index(name)]
what's wrong with this code?
it keeps ending the program
'name' is a string input by a user, and 'name' will be in the list 'UName'
I want the index number from 'name'
using this index number I want to get an integer from the list UBal
I want this integer assigned to 'balance'
this doesn't happen, the program just stops and the 3 red '>>>' is shown
these are the lists
['user one', 'user two', 'user three', 'user four'] #usernames
['100', '200', '300', '400'] #money
my main goal is to be able to get a particular user's account to be accessed.
and their money to be managed
check balance
deposit/withdraw money
delete account
I thought that if i used a code like what i gave at the top, i'd be able to handle a particular account, but if there's a better method, please do tell.
EDIT:
UName=[]
UIdNo=[]
UBal=[]
UserNames=open("UserNames.txt", "r")
UserIDs=open("UserIDs.txt", "r")
UserBalances=open("UserBalances.txt", "r")
# Duplication of data from data storage into empty lists
with open("UserNames.txt") as UserNames:
UName = [line[:-1] for line in UserNames]
with open("UserIDs.txt",) as UserIDs:
UIdNo = [line[:-1] for line in UserIDs]
with open("UserBalances.txt",) as UserBalances:
UBal = [line[:-1] for line in UserBalances]
def handle_user():
name=input("Please enter the user's name again")
if name not in UName:
print("incorrect username")
handle_user()
print("Please Select an action to perform:\n")
print("[ <1> Check Balance ]")
print("[ <2> Deposit cash ]")
print("[ <3> Withdraw cash ]")
print("")
print("[ <97>Remove account ]")
print("")
print("[ <98>Main Menu ]")
ans=input(">> ")
balance=UBal[UName.index(name)]
if ans==1:
print("Account Balance of", name, "is", balance)
print ("Your account balance is" )
menu_actions['handle_user']()
elif ans==2:
print("Please enter a deposit amount:\n")
dep=input(">> ")
elif ans==3:
print("Please enter a withdrawal amount:\n")
wit=input(">> ")
elif ans==97:
del1=input("Are you sure you want to delete this account?")
print("1.YES")
print("2.NO")
if del1==1:
del2=input("CONFIRM ACCOUNT DELETION")
print("[ <1> YES ]")
print("[ <2> NO ]")
if del2==1:
print ("The account of accountholder NAME is being deleted")
filestore.deleteaccount(self.username)
print ("The account has been successfuly deleted")
menu_actions['main_menu']()
elif del2==2:
print("Please Select an action to perform:\n")
menu_actions['handle_user']()
elif choice !='1' and choice!='2':
menu_actions['handle_user']()
elif ans !='1' and ans!='2':
menu_actions['handle_user']()
elif ans !='1' and ans!='2' and ans!='3' and ans!='97' and ans!='98':
print("Please select a valid option:\n")
menu_actions['handle_user']()
return
The problem why nothing happens after you enter 1 is that you're comparing the variable ans of type string with integers 1, 2, 3 and 97. Change it to:
if ans == "1":
# your code
elif ans == "2":
# your code
elif ans == "3":
#your code
etc
At least it will fix your current problem. I could not run your further code since I don't have this method menu_actions.

Resources