I'm learning about exception handling in Python. I have written this simple code below. If I enter a invalid value for the first number it will print out "One of your inputs are wrong!" and won't let me enter in values for num2 or num3
I want to change the code so if I enter an invalid value for the first number,it will still ask me to enter in values for num2 and num3 and then if any of the values are invalid it will print "One of your inputs are wrong"
Can someone please help me with this, I would be so grateful, thanks.
def main():
try:
num1 = int(input("Enter in Number 1: ")) # ask the user for num1
num2 = int(input("Enter in Number 2: ")) # ask the user for num2
num3 = int(input("Enter in Number 3: ")) # ask the user for num3
except ValueError:
# only run this code if any of the three numbers are invalid
print("One of your inputs are wrong!")
else:
print("The answer is ", num1 + num2 + num3)
main()
try-except blocks are like if-else blocks and hence you can nest them.
You can try this:
def main():
try:
num1 = int(input("Enter in Number 1: ")) # ask the user for num1
except ValueError:
print("Enter num2 and num3")
try:
num2 = int(input("Enter in Number 2: ")) # ask the user for num2
num3 = int(input("Enter in Number 3: ")) # ask the user for num3
except ValueError:
print("One of your inputs are wrong!")
else:
print("The answer is ", num1 + num2 + num3)
finally:
print("this block ends here!")
main()
Related
I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Recursive(Num1, Num2):
if Num1 > Num2:
return(10)
else:
if Num1 == Num2:
return(Num1)
else:
return(Num1+Recursive(Num1 * 2, Num2))
Num1=input("Enter number 1: ")
Num2=input("Enter number 2: ")
print("Final value: ", Recursive(Num1, Num2))
This is the output that comes out:
Enter number 1: 1
Enter number 2: 15
That's it. There's no output of my print statement. I'm confused as to what I'm doing wrong here and what I should do.
def Recursive(Num1, Num2):
if Num1 > Num2:
return 10
if Num1 == Num2:
return Num1
print(Num1, Num2)
return Num1 + Recursive(Num1 * 2, Num2)
Num1=int(input("Enter number 1: "))
Num2=int(input("Enter number 2: "))
print("Final value: ", Recursive(Num1, Num2))
This should be working code, the reason why your code was not working was because without the int in Num1 = int( input("") ) the program was reading the number as a string. As a result instead of getting 2 from Num1 * 2 when Num1 is 1 you got 11 as it was multiplying a string instead of an integer.
# Here is an example
a = input("Input a number: ")
b = int(input("input a number: "))
print(f"a is a:{type(a)}\n b is a:{type(b)}")
print(f"{a * 2}\n{b * 2}")
Copy the code above input the two numbers and it should give you a better understanding of what I just said.
Divisible challenge
Write a program that asks the user for two numbers. The program should output whether the two numbers are exactly divisible by each other. If not, it should return the remainder. If the user enters a 0 the program should give an error message.
so far I've done this:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
answer1 = num1/num2
answer2 = num2/num1
if num1/num2 == answer1(int) or num2/num1 == answer2(int):
print("Exactly divisible")
elif num1 == 0 or num2 == 0:
print("Error: you cannot divide by 0")
elif num1/num2 != answer1(int) or num2/num1 != answer2(int):
print("Not Exactly divisible")
please help...
I would approach this way
first check the zero case, in that case the code terminates faster
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
# answer1 = num1/num2
# answer2 = num2/num1
def divisible_by_each_other(num1, num2):
if (num1 == 0) or (num2==0):
print("Error do not enter 0")
#check divisibility
elif (num1%num2 == 0 ) or (num2%num1 == 0 ):
print("Exactly divisible")
else:
print("Not Exactly divisible")
high,low= max(num1,num2),min(num1,num2)
print("The remainder is ", high%low)
divisible_by_each_other(num1, num2)
answer1(int) is not the correct way to convert to an integer, it's int(answer1).
Since you already divided the numbers, you could use
if answer1 == int(answer1) or answer2 == int(answer2):
But you're making this much more complicated than it needs to be. Modulus is a simpler way to test divisibility.
if num1 % num2 == 0 or num2 % num1 == 0
You also should check if either of the numbers is zero before you try to use division or modulus. Otherwise, you'll get an error due to trying to divide by 0, which is what you're trying to prevent with this check.
If they're not divisible by each other, get the remainder of the larger divided by the smaller:
else:
return max(num1, num2) % min(num1, num2)
Here's the full, simplified code:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
higher = max(num1, num2)
lower = min(num1, num2)
if num1 == 0 or num2 == 0:
print("Error: you cannot divide by 0")
elif higher % lower == 0
print("Exactly divisible")
else:
print(higher % lower)
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
def max(num1,num2,num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
elif num3 > num1 and num3 > num2:
return num3
elif num1 == num2 == num3:
return num1 == num2 == num3
else:
print("something went wrong.")
print(max(4,5,8))
I am a basic python programmer learning python,i have tried to define a function which prints out maximum of a three number,but how to use the input function to get the number as input.
you can just use something like
we are using int function because input function takes the number or string and makes it a string so we need integer version of them so we can compare them
num1 = int(input("what is your first number: "))
num2 = int(input("what is your second number: "))
num3 = int(input("what is your third number: "))
but it can give errors because you did not use try except so the proper way is
while True:
try:
num1 = int(input("what is your first number: "))
num2 = int(input("what is your second number: "))
num3 = int(input("what is your second number: "))
except:
print("give me integer or number or i do not know what type of data do you want")
else:
break
you can change what is in the last print statement
you can use that
it is still impovable you should check assert
i hope it is helpful
print("1: ADDITION")
print("2: SUBTRACTION")
print("3: MULTIPLICATION")
print("4: DIVISION")
CHOICE = input("Enter the Numbers:")
if CHOICE == "1":
num1 =(input("Enter the value of num1:"))
if num1=="0": #if 0 is used
print ("Invalid Number")
if num1 =="0": #if 0 is used
input("Enter the value of num1:") #Enter number,0 used to get error
if num1 !="0":
print (num1)
num2 =(input("Enter the value of num2:"))
if num2=="0": #if 0 is used.
print ("Invalid Number")
if num2 =="0": #if 0 is used.
input ("Enter the value of num2:") #Enter number,0 used to get error
if num2 !="0":`enter code here`
print (num2)
value = float(num1) + float (num2) #this only solves for 1st input
print ("The sum of each num1 added to each num2:" + str(value))
I was trying to use this as a calculator to initially cause the error, then input the correct info on the second attempt. This never recognizes the second attempt info. It only picks up the first info for num1 and num2. How can I have this recognize the second input which is the numbers that need to get added?
A better approach is to use a while loop to collect input, and only exit the while loop after receiving valid data.
num1 = 0
while num1 == 0:
value = input(....
if ValidateInput(value):
num1 = value
num2 = 0
while num2 == 0:
value = input(....
if ValidateInput(value):
num2 = value
# do other stuff
def ValidateInput(input):
"""Common code that ensures the input is a numerical value, etc"""
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I have tried to find smallest of three numbers but for some values the answer is wrong like 10,30,4 for example and it shows smallest number to be 10.
num1 = input("Enter a number: ")
num3 = input("Enter a number: ")
num4 = input("Enter a number: ")
if (num1 < num3) and (num1 < num4):
print(num1)
elif (num3 < num4) and (num3 < num1):
print(num3)
else:
print(num4)
You are comparing text. You need to convert the input to int objects before comparing.
num1 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
num4 = int(input("Enter a number: "))
if (num1 < num3) and (num1 < num4):
print(num1)
elif (num3 < num4) and (num3 < num1):
print(num3)
else:
print(num4)
Problem: input() returns a string, and strings are compared lexicographically. So you should convert it into an integer, you can do this with int(..):
num1 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
num4 = int(input("Enter a number: "))
if (num1 < num3) and (num1 < num4):
print(num1)
elif (num3 < num4) and (num3 < num1):
print(num3)
else:
print(num4)
But nevertheless this is not a good way to calculate the minimum. What will you do if you have to calculate the minimum of 50 integers? Construct a hug amount of checks? Computer scientist Edsger W. Dijkstra once said:
"Two or more? Use a for!" - Edsger W. Dijkstra
So in case you have to do work multiple times, you better use a for loop to handle that. The skeleton of such code fragment looks like:
for i in range(3):
# ...
pass
The body of the for loop (here ...) will be repeated three times. Now what work can we put into the for loop? Of course we can query the user for input. So we can write:
for i in range(3):
number = int(input("Enter a number: "))
# ...
but now we still have to calculate the minimum. A way to handle this is by using an accumulator: a variable that is maintained through iteration, and updated accordingly. Here an accumulator can be the thus far obtained minimum. Since initially we have no minimum, we can initialize it with None:
thus_far_minimum = None
for i in range(3):
number = int(input("Enter a number: "))
# ...
Now in case thus_far_minimum is None, we can assign the number we have queried from the user. Furthermore in case thus_far_minimum is no longer None (so it is initialized), but number is less than thus_far_minimum, we can alter thus_far_minimum such that it now has the minimum. For example:
thus_far_minimum = None
for i in range(3):
number = int(input("Enter a number: "))
if thus_far_minimum is None or number < thus_far_minimum:
thus_far_minimum = number
print(thus_far_minimum)
at the end we can print the thus_far_minimum since it is the minimum over all the numbers we have seen.
With input(), you get strings, so convert the input values to integers.
num1 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
num4 = int(input("Enter a number: "))
Set a variable to num1, then reset it as you compare num1 to num3 and num4.
smallest = num1
if num3 < smallest:
smallest = num3
if num4 < smallest:
smallest = num4
if num3 < num4:
smallest = num3
print(smallest)