How would I use Try and except in this code? - python-3.x

I don't understand.
I thought TypeError was what I needed.
I looked at some examples online and I thought this was right:
def main():
x = int(input("Input a number:"))
y = int(input("Input another number:"))
result = x * y
while not result:
try:
result = x * y
except TypeError:
print('Invalid Number')
main()

Include input's in try and except statements
def main():
while True:
try:
x = int(input("Input a number:"))
y = int(input("Input another number:"))
break
except ValueError:
print('invalid Number')
result=x*y
print(result)

Related

Need to stop the code if conditional works and start again if it fails. Where did I go wrong?

The condition is simple. If sum<=20 then print sum or else loop the starting from the input. However, this is looping even if the input is valid. How should I fix this? My code is in the picture
code in the picture
You need to specify that you wish to update the global variable.
invalid_input = True
def start():
x = int(input("number1: "))
y = int(input("number2: "))
z = int(input("number3: "))
sum = x + y + z
if (sum <= 20):
global invalid_input
invalid_input = False
print(sum)
else:
print("return and give valid input")
while invalid_input:
start()
Alternatively, you could return a boolean from the function.
def start():
x = int(input("number1: "))
y = int(input("number2: "))
z = int(input("number3: "))
sum = x + y + z
if (sum <= 20):
print(sum)
return True
else:
print("return and give valid input")
while True:
if start(): break
Related post: python-function-global-variables

Display message only once if an exception occur in a function and the function being used multiple time:

I have defined a simple function and there I am raising an exception if anything unusual happens. and same function is being called multiple time, so if that exception occurs, then same message is being displayed multiple time, wherever, that function has been called, so is it possible to log this exception only once, below is the error which is coming:
def divide(x, y):
"""Divide Function"""
try:
result = x / y
except ZeroDivisionError:
print("Tried to divide by zero")
else:
return result
def multiply(x, y):
"""Multiply Function"""
try:
z = divide(x, y)
except Exception as e:
print(e)
else:
return x * y
num_1 = 10
num_2 = 0
mul_result = multiply(num_1, num_2)
Below is the error which is coming:
Tried to divide by zero
Tried to divide by zero
I don't want to do sys.exit() or raise the exception as there are other modules which needs to run fine!
I am assuming you don't want the exceptions to halt the execution of your program, but you only want an exception message printed once and only once, a quick and dirty way to do this is:
exception_logged = False
def divide(x, y):
"""Divide Function"""
try:
result = x / y
except ZeroDivisionError:
if not exception_logged:
print("Tried to divide by zero")
exception_logged = True
else:
return result
def multiply(x, y):
"""Multiply Function"""
try:
z = divide(x, y)
except Exception as e:
if not exception_logged:
print(e)
exception_logged = True
else: # <--- It is strange to have an else without an if
return x * y
num_1 = 10
num_2 = 0
mul_result = multiply(num_1, num_2)

Create a function to test a value between two ranges

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()

why does my prime number checker program always say the number is prime?

I have to make a program where the user inputs a number and it checks to see if its prime but no matter what you enter it says its prime. How do I fix this code?
def is_prime(n):
if n < 2: return False
for x in range(2, int(n**0.5) + 1):
if n % x == 0:
return False
return True
def main():
keep_going='y'
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
is_prime(n)
if True:
print("It's prime")
if False:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
main()
Do this
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
You are not assigning the return value of is_prime(n) anywhere, and you are not testing this return value. if True: is unconditional execution. if False: is unconditional non-execution.
Instead, you want to test is_prime(n):
if is_prime(n):
...
else:
...
or
prime = is_prime(n)
if prime:
...
else:
...
The good news is - your is_prime function is correct, and does return False for non-prime numbers as it should :)
Try this
def is_prime(n):
if n < 2:
return False
elif n % (n // 2) == 0:
return True
else:
return False
def main():
keep_going = 'y'
while keep_going == 'y':
n = int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going = input("would you like to see if another number is prime?(y/n):")
main()

Python IF Else and For loop workflow

I am trying to write a function that returns the number of prime numbers that exist up to and including a given number.
Initially this was my code:
def count_primes(num):
prime = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in prime:
if x%y == 0:
print('not prime')
x+=2
break
else:
prime.append(x)
x += 2
return len(prime)
How ever I realise this code will run forever because of the following line of code:
for y in prime:
if x%y == 0:
print('not prime')
x+=2
break
else:
prime.append(x)
x += 2
Can anyone help to explain to me why will this end up with an infinite loop compared to the following code?
for y in prime:
if x%y == 0:
print('not prime')
x+=2
break
else:
prime.append(x)
x += 2

Resources