If statement not evaluating all the conditions and executing anyway [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Ok so I am new to python and trying to learn how to code. I ran into an issue today that I don't understand. So this code executes as expected and prints the largest of the three numbers no matter what position the largest number is.
if num1 >= num2 and num3:
print(num1, 'Is the greatest number!')
elif num2 >= num3 and num1:
print(num2, 'Is the greatest number!')
else:
print(num3, 'Is the greatest number')
But if i change the elif statement to this:
elif num2 >= num1 and num3:
print(num2, 'Is the greatest number!')
Even if num3 is the largest the else statement will not execute and it will display the larger number of num1 or num2.

Your first version works purely by coincidence. You need to do
if num1 >= num2 and num1 >= num3:
print(num1, 'Is the greatest number!')
elif num2 >= num3 and num2 >= num1:
print(num2, 'Is the greatest number!')
else:
print(num3, 'Is the greatest number')
Although, this will still print wrong info if any of the numbers are equal

The problem here is a misunderstanding in the way the keyword and works.
In python, and is used to separate two complete logical statements: cond1 and cond2. It first checks cond1. If cond1 is True, it moves on to check cond2. If cond2 is also True, then the whole statement evaluates to True.
When you do if num1 >= num2 and num3, you are actually asking python if the following is True:
num1 >= num2
num3 exists and is not 0 (since it's a number)
It is not checking if num1 >= num2 and num1 >= num3.
So if num1 = 2, num2 = 1, num3 = 3, your conditional will still return True for if num1 >= num2 and num3.
The same concept applies to your problem conditional.

Related

how to use input in a function in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
The community is reviewing whether to reopen this question as of 5 months ago.
Improve this question
I just want to use input, in a function in python.
this is my code:
print("I can tell you the maximum of 3 numbers")
def max_num(num1, num2, num3, false=None):
num1 = input("enter first number")
num2 = input("enter second number")
num3 = input("enter third number")
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
elif num1.isdigit(False) and num2.isdigit(False) and num3.isdigit(False):
print("no number available")
else:
return num3
return max_num()
but when I run this code, Just first line (print), runs succesfully.
what is wrong?
I would be thankful.
When defining a function with parameters, make sure that these parameters don't come inside the definition of the function.
The code also has some indentation and logical mistakes.
This is a corrected version.
print("I can tell you the maximum of 3 numbers")
num1 = input("Enter the first number:")
num2 = input("Enter the second number:")
num3 = input("Enter the third number:")
def max_num(num1, num2, num3):
if not num1.isdigit() or not num2.isdigit() or not num3.isdigit():
return "Wrong Input"
else:
num1,num2,num3=int(num1),int(num2),int(num3)
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(num1,num2,num3))
You need to call that function like print(max_num(num1, num2, num3)), you are still create the function but not calling it.
What does return max_num() even mean? You should return a number, and a number is already returned in all possible branches.
If you want to call this function, try something like print(max_num(1, 2, 3)) at the end of the script.
Also, it is a bit confusing: are you planning to pass in the three numbers by functions arguments or user input? Because you are attempting to do both right now.
Ok, there are lots of issues with this code, but to answer your original question "Why does input never get called?", the answer is simple:
You have defined the function max_num, but you have never called it. Only once a function is called does the code inside run.
So in your script, you simply need to remove all the input parameters in your function definition (as they are never used), and add the line:
max_num()
Then you'll need to fix all the other quirks :)
Happy coding

Max and min assignment giving incorrect and inconsistent values [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
Im struggling to fix my code for a prompted assignment. Sometimes it gives the correct answers, other times it doesn't. For whatever reason, the input "12, 18, 4, 9" gives a max of 12?
def max_number(num1, num2, num3, num4):
if (num1 > (num2 and num3 and num4)):
return num1
elif (num2 > (num3 and num4)):
return num2
elif num3>num4:
return num3
else:
return num4
def min_number(num1, num2, num3, num4):
if num1<(num2 and num3 and num4):
return num1
elif num2<(num3 and num4):
return num2
elif num3<num4:
return num3
else:
return num4
if __name__ == '__main__':
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
print('Maximum is', max_number(num1, num2, num3, num4))
print('Minimum is', min_number(num1, num2, num3, num4))
I think this is the syntax you're looking for:
def min_number(num1, num2, num3, num4):
if num1 < num2 and num1 < num3 and num1 < num4:
return num1
elif num2 < num3 and num2 < num4:
return num2
elif num3<num4:
return num3
else:
return num4
and is a bool compare when used in an if statement like this, it doesn't chain if statements as I think you believe. In other words each statement in between the and needs to be complete, if that makes sense.
In addition to the answers offered which touch on the behavior of and when used with two integers, you may also wish to calculate whether a value is less than all of another set of numbers using something like:
all(num1 < n for n in [num2, num3, num4])
Or checking to see that num1 is greater than num2, num3, and num4:
all(num1 > n for n in [num2, num3, num4])

If statement error. Comparison of numbers to output max

I'm writing a simple code on python, but have come across an unusual error. The statements are to compare thre numbers and return the max value. Most of the time the program executes fine, however, if for example num3 is a 3-digit number and others are not, I get a comparison error. Any ideas?
def maxNum(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num3 and num2 >= num1:
print (num2)
return num2
else:
print (num3)
return num3
num1 = input("Please enter first number: ")
num2 = input("Please enter second number: ")
num3 = input("Please enter third number: ")
print ("Max number is:", maxNum(num1, num2, num3))
Please click on image link. I have changed the code as advised but still get error. It seems any integer that I input that is more than or equal to 100 creates this error:
enter image description here
1 def max_num(num1, num2, num3):
2 biggest = max([int(num1),int(num2), int(num3)])
3 return biggest
4
5 num1 = input("Enter First Number: ")
6 num2 = input("Enter Second Number: ")
7 num3 = input("Enter Third Number: ")
8
9
10 print(max_num(num1, num2, num3))
Are you just trying to work the function comparisons, or are you open to other methods?
This will accomplish the same task with less steps.
Although I am by no means fluent in Python, I believe the approach to distinguish all cases that can occur is hard to understand. Instead, I suggest iterating the input values as follows. The approach uses an additional varaiable to store the potential result.
def maxNum(num1, num2, num3):
result = num1
if (num2 > result)
result = num2
if (num3 > result)
result = num3
print(result)
return result

Python program not returning anything [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 5 years ago.
I'm practicing Python so I decided to recreate the max() function for 2 numbers. The code doesn't have an error, it just doesn't return anything. Please help! `
def newMax(num1, num2):
if num1 > num2:
return num1
elif num2 > num1:
return num2
elif num1 == num2:
return "They're both equal!"
else:
return "We've run into some sort of error. Make sure you entered 2 numbers."
print("This program will return the largest of 2 numbers you enter.")
number1 = input("Please enter your first number.")
number2 = input("Please enter your second number.")
newMax(number1, number2)
`
Can you not call a function with variables as the parameters, and if not then how would I write this program? FIGURED OUT, I had a print statement error, sorry.
new_max = newMax(number1, number2)
print(new_max)
Try assigning it to a variable and printing that variable.

How do I print a float as an integer?

This is for a homework assignment in my Python class that I am having an issue on. I am not allowed to import anything or use try-except.
I want to take 3 numbers and print the smallest one without using the min() function. The issue I am having is that if the number is something like 5 it gets printed as 5.000000 because I converted all the numbers to floats. I tried using rstrip('0') and it prints it as 5. which makes sense, but I need integers to be printed as an integer and floats to be printed as a float. Is there a simpler way to do this that I am missing?
My code for reference:
def min3(num1, num2, num3):
if (num1 <= num2):
if(num1 <= num3):
return num1
else:
return num3
if (num2 <= num1):
if(num2 <= num3):
return num2
else:
return num3
def main():
num1 = float(input("Please enter the first number: "))
num2 = float(input("Please enter the second number: "))
num3 = float(input("Please enter the third number: "))
smallest_num = min3(num1, num2, num3)
print("The smallest number is %f." %(smallest_num))
main()
You can do something like this
if smallest_num.is_integer():
# print as integer
print "The smallest is %d" % smallest_num
else:
# print as float
print "The smallest is %f" % smallest_num

Categories