how to use list function correctly - python

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)

Related

Python Not being able to restart program after input of wishing to continue

I am trying to restart the program to start over if I press Yes if I wish to continue but after quite a bit of reading could not figure out a solution. I am trying to restart the funciton buth with no success. When I press Y to continue it does completely wrong calculations not bringing me back to start all over. Any help would be appreciated.
oo_large_value = 100000
dimes = -1
quarters = -1
nickels = -1
pennies = 0
continue_execution = 'Y'
#Continue Until User doesn't want to exit
while continue_execution == 'Y':
print("Please enter the number of coins:")
#input quarters
while quarters < 0 or quarters >= too_large_value:
try:
quarters = int(input("# of quarters:"))
#if user entered negative value, give error
if quarters < 0:
print("Please Enter a positive Value:")
#if user entered too large value, give error
elif quarters >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
#if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
quarters=quarters*25
while dimes < 0 or dimes >= too_large_value:
try:
dimes = int(input("# of dimes:"))
# if user entered negative value, give error
if dimes < 0:
print("Please Enter a positive Value:")
# if user entered too large value, give error
elif dimes >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
# if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
dimes=dimes*10
while nickels < 0 or nickels >= too_large_value:
try:
nickels = int(input("# of nickels:"))
# if user entered negative value, give error
if nickels < 0:
print("Please Enter a positive Value:")
# if user entered too large value, give error
elif nickels >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
# if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
nickels=nickels*5
#calculate pennies
pennies = quarters + dimes + nickels
#print total pennies
print(f'The total is {pennies} pennies')
#Ask if user wants to Continue or not
print("Do You want to Enter another value?")
continue_execution = input("Y for Yes and N for N:")
#makes sure user enters only 'Y' or 'N'
while continue_execution != 'Y' and continue_execution != 'N':
print("Invalid Choice\nPlease Enter again")
continue_execution = input("Y for Yes and N for N: ")
print("Thank you for doing business with us!")

Input statements just keep going in a loop

Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)

How to run python loop until correct input string is entered [duplicate]

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?: ")
...

loop through multiple questions each with a condition in Python

I am creating a program where you will have to loop through multiple questions each with a condition. If user input for the question does not meet the requirement, it will print out the error and prompt user to re-enter. Else, it will continue with the next question. And not only prompting user to re-enter after all 3 questions are answered.
This it the output I am getting now:
while True:
amount = int(input("Enter amount: "))
rate = int(input("Enter rate: "))
year = float(input("Enter year: "))
if amount<4000:
print("Invalid amount")
continue
elif rate<0:
print("invalid rate")
continue
elif year<0:
print("invalid year")
break
Output:
Enter amount: 1
Enter rate: 3
Enter year: 4
Invalid amount
Enter amount:
Expected output:
Enter amount: 4
Invalid amount
Enter amount:
It's not very clear what are you trying to achieve, but I think you want this:
while True:
amount = int(input("Enter amount: "))
if amount < 4000:
print("Invalid amount")
continue
break
while True:
rate = int(input("Enter rate: "))
if rate < 0:
print("invalid rate")
continue
break
while True:
year = float(input("Enter year: "))
if year < 0:
print("invalid year")
continue
break
This will only ask to re-enter the invalid values.
Another more reusable method would be:
def loop_user_input(input_name, meets_condition):
while True:
value = int(input(f"Enter {input_name}: "))
if not meets_condition(value):
print(f"Invalid {input_name}")
else:
return value
loop_user_input('amount', lambda val: val < 4000)
loop_user_input('rate', lambda val: val < 0)
loop_user_input('year', lambda val: val < 0)
Here you have a loop that only returns when the input value meets the condition, that you pass in. I recommend you check your conditions, because a year normally shouldn't be negative (rate < 0). Also your solution throws an exception, if the user enters something else then an int. Maybe add a try-catch to your solution:
try:
value = int(input(f"Enter {input_name}: "))
except:
print(f"Invalid {input_name}")
continue

Stuck on an assignment. At least part of it. ATM Banking choices

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.

Categories