loop through multiple questions each with a condition in Python - 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

Related

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)

Question regarding my program being tedious

I just started learning python 3 recently and i have a problem of my code being too repetitive and lengthy.
i wrote a code to calculate the interest earned.
I have read about using functions to simplify my code but i am not sure how to go about doing this.
Thanks for anyone who is willing to help me out! The code i have written is as follows:
print("Welcome to the monthly interest rate calculator")
original_interest = 0.0005/12
additional_food_interest_1 = 0.0055/12
additional_food_interest_2 = 0.0085/12
additional_interest_3 = 0.0090/12
additional_interest_4 = 0.0015/12
additional_interest_5 = 0.0095/12
additional_interest_6 = 0.0035/12
interest = [original_interest]
#asks user for the amount of money they have in the bank
while True:
try:
account = float(input("Enter your account balance: "))
except ValueError:
print("Try Again.")
continue
else:
break
# checks if condition 1 is met before adding either food_interest_1 or food_interest_2 variable to the list
while True:
try:
food_spending = float(input("How much did you spend on food?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if food_spending >= 100 and food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
else:
pass
# checks if condition 2 is and if so adds additional_interest_3 to the list
while True:
try:
drinks_spending = float(input("How much did you spend on drinks?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if drinks_spending >= 100:
interest.append(additional_interest_3)
else:
pass
# checks if condition 3 is met and if so adds additional_interest_4 to the list
while True:
try:
insurance_spending = float(input("How much did you spend on insurance?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if insurance_spending >= 100:
interest.append(additional_interest_4)
else:
pass
# checks if condition 4 is met and if so adds additional_interest_5 to the list
while True:
try:
debitcard_spending = float(input("How much did you spend on your debit card??: "))
except ValueError:
print("Try Again.")
continue
else:
break
if debitcard_spending >= 100:
interest.append(additional_interest_5)
else:
pass
# This checks for 4 inputs from the user and if satisfies the condition, adds additional_interest_6 to the list
while True:
try:
first_receipt = float(input("Enter the amount on your first receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
second_receipt = float(input("Enter the amount on your second receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
third_receipt = float(input("Enter the amount on your third receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
four_receipt = float(input("Enter the amount on your fourth receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
if first_receipt > 20 and second_receipt > 20 and third_receipt >20 and four_receipt > 20:
interest.append(additional_interest_6)
#calculates the total interest earned
if account <= 20000:
print("your monthly interest earned is", round(account*(sum(interest)),2))
else:
print(20000*sum(interest) + (account-20000)*original_interest)
This is about as concise as I can make it with a quick pass.
I refactored things so all inputs are requested first, all computation done second. Should you refactor the calculation bits into a function, that'd make the function easier to test. I also refactored the computation into a function of its own.
def prompt_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Try Again.")
def prompt_receipts():
receipts = []
while True:
receipt_value = prompt_float(
f"Enter the amount on receipt {len(receipts) + 1}, or <= 0 for no more receipts."
)
if receipt_value <= 0:
break
receipts.append(receipt_value)
if len(receipts) >= 4:
break
return receipts
def compute_interest(
*,
original_interest,
receipts,
debitcard_spending,
drinks_spending,
food_spending,
insurance_spending,
):
additional_food_interest_1 = 0.0055 / 12
additional_food_interest_2 = 0.0085 / 12
additional_interest_3 = 0.0090 / 12
additional_interest_4 = 0.0015 / 12
additional_interest_5 = 0.0095 / 12
interest = [original_interest]
if 100 <= food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
if drinks_spending >= 100:
interest.append(additional_interest_3)
if insurance_spending >= 100:
interest.append(additional_interest_3)
if debitcard_spending >= 100:
interest.append(additional_interest_4)
if all(receipt_value > 20 for receipt_value in receipts):
interest.append(additional_interest_5)
return interest
def main():
print("Welcome to the monthly interest rate calculator")
# Get user inputs.
account = prompt_float("Enter your account balance: ")
food_spending = prompt_float("How much did you spend on food?: ")
drinks_spending = prompt_float("How much did you spend on drinks?: ")
insurance_spending = prompt_float("How much did you spend on insurance?: ")
debitcard_spending = prompt_float(
"How much did you spend on your debit card??: "
)
receipts = prompt_receipts()
# Compute things.
original_interest = 0.0005 / 12
interest = compute_interest(
original_interest=original_interest,
receipts=receipts,
debitcard_spending=debitcard_spending,
drinks_spending=drinks_spending,
food_spending=food_spending,
insurance_spending=insurance_spending,
)
# Output things.
if account <= 20000:
print(
"your monthly interest earned is",
round(account * (sum(interest)), 2),
)
else:
print(20000 * sum(interest) + (account - 20000) * original_interest)
if __name__ == "__main__":
main()
You can wrap you try/except approach as:
def get_input(text)
while True:
try:
return float(input(text))
except ValueError:
print("Try Again.")
account = get_input("Enter your account balance: ")
food_spending = get_input("How much did you spend on food?: ")
....

How to stop code running when if statement is not fulfilled

I am doing a school project and what i want to add is a line of code that would stop the code from running if age < 15 or if age > 100
I tried break but it would continue to the next line.
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
if age < 15:
print("sorry you are too young to enter the store!")
break
if age > 100:
print("Please come back in the next life")
break
else:
break
print("")
print("Welcome to Jim's Computer Store", name)
print("") while True:
try:
cash = int(input("How much cash do you currently have? $"))
except ValueError:
print("Please enter a valid value! ")
continue
else:
break
I would advise you to proceed step by step. The code in the question is too long for the purpose. When the first step behaves like you want, you can do another step.
Is is this working like you want ?
name = "John"
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
break
# Here, we can assume that 'age' is an integer
if age < 15:
print("sorry you are too young to enter the store!")
exit()
if age > 100:
print("Please come back in the next life")
exit()
print("")
print("Welcome to Jim's Computer Store", name)
# When the code above will be validated, the next step will be easy
The while loop is to assure that age is an integer when he breaks the loop (if age is not an integer, the program will execute the continue instruction and go back to the start of the loop).
Just adding a exit() after the if condition will do the job.
An example would be:
x = 5
if x < 2:
print "It works"
else:
exit()
Or without the else statement:
x = 5
if x < 2:
print "It works"
exit()

How do I completely break out of my nested while loop?

I'm having trouble breaking out of the nested while loop in my code completely. How do I break out of two loops? Here's my attempt:
while continue_enter == True:
while True:
try:
enter_result_selection = int(input("What test would you like to enter results for? Please enter a number - Reading Test: 1 Writing Test: 2 Numeracy Test: 3 Digital Literacy Test: 4 All Tests: 5 - "))
if enter_result_selection == 1:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 2:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 3:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 4:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
elif enter_result_selection == 5:
name = input("Please enter the name of the student you would like to enter results for: ")
result_enterer_name = input("Please enter your name: ")
while True:
try:
student_result_reading = int(input("Enter {}'s percentile for the reading test (%): ".format(name)))
student_result_writing = int(input("Enter {}'s percentile for the writing test (%): ".format(name)))
student_result_numeracy = int(input("Enter {}'s percentile for the numeracy test (%): ".format(name)))
student_result_digtialliteracy = int(input("Enter {}'s percentile for the digtial literacy test (%): ".format(name)))
break
except ValueError:
print("This input is invalid. Please enter a percentage ranging from 0 - 100%")
else:
print("Sorry, this is an invalid number. Please only enter numbers ranging from the values 1 - 5.")
break
except ValueError:
print("Sorry, your input was invalid. Please enter a number and try again.")
while continue_enter == True or continue_enter == False:
ask_continue_enter = input("Would you like to enter results for another student? ")
if ask_continue_enter.lower() == "yes" or ask_continue_enter.lower() == "y":
continue_enter == True
break
elif ask_continue_enter.lower() == "no" or ask_continue_enter.lower() == "n":
continue_enter == False
break
else:
print("Sorry, this is an invalid input. Please enter with 'Yes' or 'No'")
if continue_enter == True:
continue
elif continue_enter == False:
break
Here is an example of how to break out of nested loops using exceptions:
class MyException(Exception):
pass
x=1
y=1
try:
while x<10:
y=1
while y<10:
if x==5 and y==5:
raise MyException
y=y+1
x=x+1
except MyException:
print x
print y
Output:
$ python prog.py
5
5
You don't HAVE to define an own exception. You can just use the standard ones, or even just use raise Exception('Something happened'). However, I would STRONGLY advice not to do that. See this link for more info: https://stackoverflow.com/a/24065533/6699433
EDIT:
I just read that you can use the builtin exception StopIteration. That seems suitable.

Integers as the only valid inputs

What I'm trying to do is ask users for two inputs, if one of the inputs is less than zero or if the input is some string then ask for the inputs again. The only valid input are numbers >=0. So you can't have something like -1 or cat as inputs.
Attempt 1:
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
while int(number_of_books) < 0 or int(number_of_chairs) < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
But from this I realized that the input are always strings so it will ask for input again.
Attempt 2:
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
while number_of_books < 0 or number_of_chairs < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
But with this one I realized that you cannot do int('some string')
So I'm wondering if there is a way to do this or is this something not possible?
You should use a while loop for each input, so only the invalid one is asked again. By using while True, you ask for input once, and break once it's valid. Try to convert to int, which raises ValueError if that cannot be done. Exceptions cause the custom error to be printed, and the loop restarted.
while True:
books_input = input("What is the number of books in the game?: ")
try:
number_of_books = int(books_input)
if number_of_books < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
You'd need to do this for each input (maybe there are more than two?), so it makes sense to create a function to do the heavy lifting.
def non_negative_input(message):
while True:
input_string = input(message)
try:
input_int = int(books_input)
if input_int < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
return input_int
Calling it:
non_negative_input("What is the number of books in the game?: ")
The solution is to coerce the answer to int() and catch any exceptions, for example:
while True:
try:
number_of_books = int(raw_input('Enter number of books:'))
if number_of_books < 0:
raise ValueError('must be greater than zero')
except ValueError, exc:
print("ERROR: %s" % str(exc))
continue
break
Probably you should put this in a function, and make the prompt a variable (to allow re-use).
Use the try except method
while stringval = input("What is the number you want to enter"):
try:
intval = int(stringval)
if intval > -1:
break
except ValueError:
print 'Invalid answer, try again'
# Process intval now

Categories