Python Nested Loop Enter Value and Confirm Answer - python

I'm trying to write a simple block of code that has a user enter an interest rate. The number must be 0 or greater, any other value will be rejected, the user must be polled until a valid number is input. If the number is greater than 10%, the user must be asked if he/she really expects an interest rate that high, if the user replies in the affirmative, the number is to be used, otherwise the user will be asked to input the value again and the above checks will be made. I'm having trouble understanding the nested loop aspect of this. Any help is greatly appreciated!
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
except ValueErrror:
print("Entered value is not a number! ")
except KeyboardInterrupt:
print("Command Error!")
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
main()

do it all in the try, if inp > 10, ask if the user is happy and break if they are, elif user input is within threshold just break the loop:
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
if interest_rate > 10:
confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
if confirm =="y":
break
elif 0 <= interest_rate < 10:
break
except ValueError:
print("Entered value is not a number! ")
return interest_rate
main()

Three things jump out:
1) ValueErrror should be ValueError
2) You don't handle the user input on the final test
3) You probably want to change the < 10 to be <= 10

else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
can be:
if 0 <= interest_rate <= 10:
break
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
except the last line must take the response and process it.
Your else was not related to an if
Your elif was unnecessary after break

Make the print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") an input
answer = int(input("Are you sure?"))
if answer == "y":
break

I usually prefer to break down the solution and validation into different modules. Please check the below code to see how I break them down. So it is easy when it comes to debugging and testing.
def validating_user_input(num):
"""
"""
return num > 0
def getting_user_input():
"""
"""
user_input = int(raw_input("Enter the number that is greater than 0: "))
return user_input
def confirming_choose():
"""
"""
try:
user_choose = int(raw_input("Can you confirm your input? [0|1]? "))
except ValueError:
return False
return user_choose == 1
def main():
"""
"""
initial_cond = True
while initial_cond:
user_input = getting_user_input()
if validating_user_input(user_input):
if user_input > 10:
confirmation = confirming_choose()
while not confirmation:
getting_user_input()
#do you operating here
initial_cond = False
else:
print "It is not valid input."
if __name__ == "__main__":
main()

Related

How do I make a program keep repeating until I input a specific data that stops it?

I'm trying to make a program in python so that when I input a number from 1 to 10, a specific set of program goes on and asks for another number from 1 to 10 and runs another program, until I enter 0(zero) and the program stops.
So my guess was using a while loop but it didn't quite work out.
user_input = input()
user_input = int(user_input)
while user_input != 0:
(program)
else:
quit()
Try this:
user_input = int(input())
while user_input != 0:
(program)
user_input = int(input())
quit()
With your current code you only ask for input once so the loop won't end. This way you can input a new number after every iteration.
Your current program only asks once and then the loop keeps repeating. You need to keep asking for input inside the loop.
def program():
print("Executing Task....")
user_input = int(input())
while user_input != 0:
program()
user_input = int(input())
printf("Program Terminated")
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
A different way using iter with a sentinel:
def program(number):
if number < 0 or number > 10:
print('Invalid number:', number)
else:
print('Valid number:', number)
def quit():
print('quitting')
def get_number():
return int(input('Enter a number from 1 to 10: '))
for number in iter(get_number, 0):
program(number)
else:
quit()
not_zero = True
while not_zero:
num = int(input("Enter a number: "))
if num == 0:
not_zero = False
you can stop your loop using a boolean value.

I want to print when the user fails to type a positive number it will tell them the number was not valid (eg -8.25)

def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

How can I create a 'while'-exception loop?

I am working on a small coding challenge which takes user input. This input should be checked to be a digit. I created a "try: ... except ValueError: ..." block which checks once whether the input is a digit but not multiple times. I would like it to basically checking it continuously.
Can one create a while-exception loop?
My code is the following:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than
one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
uinput = int(input("You entered not a digit. Please try again: "))
flag = True
while flag:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
flag=False
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
print('Wrong input')
Output :
(python37) C:\Users\Documents>py test.py
Please enter a number: qwqe
Wrong input
Please enter a number: -123
Number is negative. Please try again: 123
123 is a prime number!
I add flag boolean to not make it repeat even when the input is correct and deleted input in except because it would ask 2 times.
If you press Enter only, the loop terminated:
while True:
uinput = input("Please enter a number: ")
if uinput.strip()=="":
break
try:
uinput=int(uinput)
except:
print("You entered not a digit. Please try again")
continue
if uinput<=0:
print("Not a positive number. Please try again")
continue
for i in range(2, uinput):
pass; # put your code here

Crashing when improper input given more than once

I'm trying to make a simple number guesser program, it works pretty well however if I enter 'a' twice instead of a valid int it crashes out. Can someone explain what I'm doing wrong here.
import random
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
if type(guess) != int:
guess = int(input("That isn't a number, try again: "))
elif guess not in range (1,11):
guess = int(input("This is not a valid number, try again: "))
else:
break
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
input_sanitiser()
if guess > number:
print("This number is too high!")
input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")
if __name__ == "__main__":
main()
You want to check the input before trying to convert it to int:
int(input("This is not a valid number, try again: "))
I would write:
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
pass
else:
break
Side note: the code isn't working as expected:
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser() # <<<<<<<<<<
while guess != number:
Note that input_sanitiser does not modify the variable guess in main, you need some other way round, like processing the input then returning the result from input_sanitiser, like this:
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
continue # keep asking for a valid number
if guess not in range(1, 11):
print("number out of range")
continue
break
return guess
def main():
number = random.randrange(1,10)
guess = input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
guess = input_sanitiser()
if guess > number:
print("This number is too high!")
guess = input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")

Categories

Resources