Create a function to test a value between two ranges - python-3.x

I want to create a function within this code to kick the user back if the input values are outside of the input ranges, so if the first number with the second number doesn't exceed the high range or fall below the low rang with any of the calculations, if it does it would return with an error message and prompt to try again.
while True:
try:
number1 = int(input('Enter your Lower Range:'))
if number1 < -100 or number1 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
number2 = int(input('Enter your Higher Range: '))
if number2 < -100 or number2 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
a = int(input('Enter your first number: '))
if a < -100 or a > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
b = int(input('Enter your second number: '))
if b < -100 or b > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
print('{} + {} = '.format(a, b))
print(a + b)
print('{} - {} = '.format(a, b))
print(a - b)
print('{} * {} = '.format(a, b))
print(a * b)
print('{} / {} = '.format(a, b))
print(a / b)
restart = input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
main()
if restart == "n" or restart == "no":
print ("Script terminating. Goodbye.")
print ("Thanks for using my calculator!")
main()

If you need this into a method, you can try the following:
def read_number(text, lower=-100, higher=100):
while True:
number = int(input(text))
if number < lower or number > higher:
print("Invalid integer. The number must be between {} and {}.".format(lower, higher)
pass
else:
return number
The method read_number() above get the input and returns it only on condition, so you can use it directly to a variable:
def main():
number1 = read_number('Enter your Lower Range: ')
number2 = read_number('Enter your Higher Range: ')
a = read_number('Enter your first number: ')
b = read_number('Enter your second number: ')
# do something ...
I don't know if is it you want. If not, try to explain it with more clarity.
However, I hope has helped you.

I've tried my best to design a function. I hope this helps:
def my_calculator():
while True:
try:
number1 = int(input('Enter your Lower Range:'))
if number1 < -100 or number1 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
number2 = int(input('Enter your Higher Range: '))
if number2 < -100 or number2 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
a = int(input('Enter your first number: '))
if a < -100 or a > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
b = int(input('Enter your second number: '))
if b < -100 or b > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
print('{} + {} = '.format(a, b))
addition = a + b
print(addition)
print('{} - {} = '.format(a, b))
diff = a - b
print(diff)
print('{} * {} = '.format(a, b))
prod = a * b
print(prod)
quo = None
try:
quo = a / b
except ZeroDivisionError as ze:
print("Division by zero not allowed; Please retry.")
my_calculator()
print('{} / {} = '.format(a, b))
print(quo) if quo else print()
results = [addition, diff, prod, quo]
try:
if not all(-100 < i < 100 for i in results):
raise ValueError
except ValueError as ve:
print("Some of the results of calculation exceed 100 or are less than -100."
"The results must be between -100 and 100. Please retry.")
my_calculator()
restart = input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
my_calculator()
if restart == "n" or restart == "no":
print("Script terminating. Goodbye.")
print("Thanks for using my calculator!")
if __name__ == "__main__":
my_calculator()

Related

Creating file in python for BMI and Fat Burning heart rate but receiving error when trying to save to a txt file

I'm writing a program to create a txt file and store data in the file. The program takes a persons height, weight, age, to calculate their BMI and Fat Burning Heart Rate. I have a general except statement that will be called if there is an error saving the information. Anyways the error is called and I can't figure out why the data won't write to the txt file.
choice = int(input("Select:\n1. Create a fle and add results\n2. Open a file and add results \n3. Read results from file \n4. Quit \n"))
while choice < 4:
BMICalc = []
if choice == 1:
try:
BMIcalculations = open('BMIcalculations.txt')
for n in BMIcalculations:
BMICalc.append(n.strip())
except FileNotFoundError as err:
print(err)
print('Creating file for BMI calculations')
BMIcalculations = open("BMIcalculations.txt", "x")
print("File created.")
BMIcalculations.close()
while True:
try:
age = int(input("Enter your age: "))
if age <= 0:
raise TypeError("Enter a number greater than zero")
break
except ValueError:
print("Invalid age. Must be a number.")
except TypeError as err:
print(err)
except:
print('Invalid input')
while True:
try:
height = float(input('Enter your height in inches: '))
if height <= 0:
raise TypeError("Enter a number greater than 0")
break
except ValueError:
print("Height must be a number.")
except TypeError as err:
print(err)
except:
print('Invalid input')
while True:
try:
weight = float(input("Enter your weight in pounds: "))
if weight <= 0:
raise TypeError("Enter a number greater than 0")
break
except ValueError:
print("Weight must be a number")
except TypeError as err:
print(err)
except:
print('Invalid value')
print('Age = ',age)
print('Height = ',height)
print('Weight = ',weight)
BMI = 703 * weight/pow(height,2)
heartRate = (220 - age)
heartRate1 = heartRate * .7
print("Fat Burning Heart Rate = ",round(heartRate1, 1),"bpm")
heartrate2 = round(heartRate1, 1)
print("Body Mass Index = ", round(BMI, 2))
FatBHR = "Fat Burning Heart Rate = ",round(heartRate1, 1),"bpm"
BMIList = "Body Mass Index = ", round(BMI, 2)
BMIList2 = round(BMI, 2)
BMICalc.append(BMIList2)
BMICalc.append(heartrate2)
try:
BMIcalculations = open('BMIcalculations.txt', 'w')
for n in BMICalc:
BMIcalculations.write(n + '\n')
except:
print('Error writing to file')
BMIcalculations.close()

I'm trying to get a separate outcome in this code but it constantly display both. I've tried "if statement" but it doesn't help. Help me plz

print('Welcome to Python Times Table')
wrong_answer = ''
while True:
try:
number = int(input('What number do you want to multiply by: '))
except ValueError:
print("Enter Integer Only")
continue
else:
for n in range (11):
res = number * n
print(f'{number} * {n} = ?')
while True:
try:
answer = int(input("Your Answer: "))
except ValueError:
print('Only Integer Allowed.')
else:
if number * n != answer:
print("Incorrect!")
print(f'{number} * {n} = ?')
wrong_answer += f'{number} * {n} = {res} -> Your Answer:{answer}\n'
continue
elif number * n == answer:
print('Correct')
break
print("These are the answer you missed!")
print(wrong_answer)
print('Congratulation! ALL answer are correct!')
if number * n != number:
print("\nThese are the answer you missed!\n")
print(wrong_answer)
else:
print('Congratulation! ALL answer are correct!')
choice = int(input("Learn another table? 1 for YES, 2 for NO: "))
if choice == 1:
choice == True
wrong_answer = ''
else:
print('Bye Bye')
break
I cleared the string once I wanted to redo the timetable!

Unbound local error when writing nested codes

I’m trying to tweak the subfile on my python but it keeps showing me an unboundlocalerror on the a variable (Min_Alpha) which was referenced earlier on. I am confused by this as if I run the alpha command I get no errors though when I run the beta command I get this error. Any help would be much appreciated.
def main():
print("Welcome to the Beta Distribution Software")
print(" ")
playerschoice = input("Do you want to use this software ? Yes/No : ")
if (playerschoice == "yes" or playerschoice =="Yes" or playerschoice == "YES"):
Body_function_01()
else:
end_program()
def Body_function_01():
users_choice = input("What constant would you like to vary ? Alpha/Beta: ")
if (users_choice == "Alpha" or users_choice == "alpha"):
Max_Alpha = float(input("Enter the Maximum Alpha Value: "))
Min_Alpha = float(input("Enter the Minimum Alpha Value: "))
Alpha_increment = float(input("Enter Alpha Increment Value: "))
Beta_constant = float(input("Enter constant Beta value"))
else:
Body_function_02()
if (Min_Alpha >= 0):
print("Minimum Alpha value is within an acceptable range")
elif (Min_Alpha < 0):
print("Minimum value of alpha is too low ")
print ("Try again")
if ((Max_Alpha - Min_Alpha) > Alpha_increment):
print("The Alpha Increment is within an acceptable range")
elif ((Max_Alpha - Min_Alpha) < Alpha_increment):
print("The Alpha increment is too high")
print("Try again")
if (Max_Alpha > Min_Alpha):
print("The Maximum value of alpha is within an acceptable range")
elif (Max_Alpha < Min_Alpha):
print("The maximum value of alpha is too high")
print("Try again")
def Body_function_02():
users_choice = input("What constant would you like to vary ? Alpha/Beta: ")
if (users_choice == "Beta" or users_choice == "beta"):
Max_Beta = float(input("Enter the Maximum Beta Value: "))
Min_Beta = float(input("Enter the Minimum Beta Value: "))
Beta_increment = float(input("Enter Beta Increment Value: "))
Alpha_constraint = float(input("Enter constant Alpha value: "))
else:
print("Try again")
if (Min_Beta >= 0):
print("Minimum Beta value is within an acceptable range")
elif (Min_Beta < 0):
print("Minimum value of Beta is too low ")
print ("Try again")
if ((Max_Beta - Min_Beta) > Beta_increment):
print("The Beta Increment is within an acceptable range")
elif ((Max_Beta - Min_Beta) < Beta_increment):
print("The Beta increment is too high")
print("Try again")
if (Max_Beta > Min_Beta):
print("The Maximum value of Beta is within an acceptable range")
elif (Max_Beta < Min_Beta):
print("The maximum value of Beta is too high")
print("Try again")
def end_program():
print(" ")
input("Press any key to leave")
sys.exit()
main()
Body_function_01()
Body_function_02()
end_program().
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-25-c662d0a92b77> in <module>
111
112
--> 113 main()
114 Body_function_01()
115 Body_function_02()
<ipython-input-25-c662d0a92b77> in main()
16 playerschoice = input("Do you want to use this software ? Yes/No : ")
17 if (playerschoice == "yes" or playerschoice =="Yes" or playerschoice == "YES"):
---> 18 Body_function_01()
19
20 else:
<ipython-input-25-c662d0a92b77> in Body_function_01()
33 Body_function_02()
34
---> 35 if (Min_Alpha >= 0):
36 print("Minimum Alpha value is within an acceptable range")
37 elif (Min_Alpha < 0):
UnboundLocalError: local variable 'Min_Alpha' referenced before assignment
I think the problem is that Min_Alpha is initialised in this if:
users_choice = input("What constant would you like to vary ? Alpha/Beta: ")
if (users_choice == "Alpha" or users_choice == "alpha"):
Max_Alpha = float(input("Enter the Maximum Alpha Value: "))
Min_Alpha = float(input("Enter the Minimum Alpha Value: "))
Alpha_increment = float(input("Enter Alpha Increment Value: "))
Beta_constant = float(input("Enter constant Beta value"))
Which mins it will be initialised only if user choices Alpha/alpha. For any other choice the variable will not be initialised and it will be unbounded when you compare it to 0. Not sure what is the expected behaviour but i think you should return on the else case in both Body_function_01 and Body_function_02 functions.

try & if statement in while loop

I would like to build a function in which if the entered integer is between 1 and 10, return the result.
Here is my code:
while True:
try:
num = int(input("Enter a number (1-10): "))
except ValueError:
print("Wrong input")
else:
if 1 <= num <= 10:
break
else:
print("Wrong input")
continue
When you enter an integer, the break does not function properly and it seems to go into a definite loop. Is it wrong to incorporate if statement into else?
Instead of break, print num.
isBetweenOneAndTen = True
while isBetweenOneAndTen == True:
try:
num = int(input("Enter a number (1-10): "))
except ValueError:
print("Wrong input")
else:
if 1 <= num <= 9:
print(num)
isBetweenOneAndTen = False
else:
print("Wrong input")
continue

How to show invalid input

My task is:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
I want to ignore any invalid integer and print 'Invalid Output' message after calculating the maximum and minimum number.But it always prints the invalid message right after user input. How am i supposed to solve this?
Thanks in advance.
Code:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
print('Invalid input')
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
You could store that invalid output as a boolean variable
largest = None
smallest = None
is_invalid=False
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
is_invalid=True
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
if is_invalid:
print('Invalid Input')
This can be one solution
largest = None
smallest = None
errors = False
while True:
num = input('Please type a number : ')
if num == 'done':
break
try:
number = int(num)
#your logical operations and assignments here
except ValueError:
errors = True
continue
if errors:
print('Invalid input')
else:
print('Your Results')
Hope this helps :)
If you are familiar with lists,you can use list to solve your problem effectively,
here is a modified version of your code which uses list,
num1=[]
while True:
num = input("Enter a number: ")
num1.append(num)
if num == "done":
break
for i in num1:
try:
i = int(i)
except:
print('Invalid input:',i)
num1.remove(i)
print("Maximum", max(num1))
print('Minimum', min(num1))
output:
Enter a number: 34
Enter a number: 57
Enter a number: 89
Enter a number: ds
Enter a number: 34
Enter a number: do
Enter a number: done
Invalid input: ds
Invalid input: do
Maximum 89
Minimum 34
hope this helps,let me know if anything is incorrect.
Try removing the (int) in try block. Because you want only integer input in try block so if does not satisfy the condition of integer input it will execute the except block.
Your code should look like this in try block:
try:
n = num

Resources