0
Guys need help! crct this python code
# To find largest even and odd number from the input taken from the user b=0 c=0 while True: a=int(input("enter number:")) if a%2==0 and a>b: b=a elif a%2==1 and a>c: c=a elif a==0:break print("Largest even number is",b) print("Largest odd number is",c) Code works fine for positive numbers.But gives wrong answer for negative numbers
23 ответов
0
That is because b, c are initially set to 0, you can try
b=float("-inf")
c=float("-inf")
+ 1
When input is negative all conditions will be false
+ 1
Try this. This will work
# To find largest even and odd number from the input taken from the user
b=0
c=0
while True:
a=int(input("enter number:"))
if a%2==0 and abs(a) >b:
b=a
elif a%2==1 and abs(a) >c:
c=a
elif a==0:break
print("Largest even number is",b)
print("Largest odd number is",c)
0
Try abs(). It's a function that can gets the absolute value of a integer. So the line where you take input would become:
a = abs(int(input("enter number: ")))
0
Can you plz explain the purpose.
What do you mean by largest
0
The code actually gives the output even when input is negative.But the answers are always 0 when inputs are negative
0
Yes ,So I want to find a way so that the code also works for negative inputs
0
What kind of output you are expecting for negative number
and change the condition in elif to a%2!=0
0
Say if my inputs are -1,-2,-3,-4 ,I want -1 as the largest odd number and -2 as the largest even number
0
Acc to code, it will just tell you whether the number is odd or even
0
What i think is you want to take multiple inputs and then tell which number is largest odd or even in comparison to other numbers
0
Yes exactly
0
Then you have to store those input somewhere.
Acc to your code it takes one input and applies the conditions
0
I have wrote a code in which I have stored these values in a list and found largest number using max() function.But I wanted to find it without using a list .
0
It's working fine now.I have tried something mentioned in an above comment.Now it works even for negative numbers.Thnks guys😄
0
BHAVESH your code will run until the input is zero. It means it will not output anything until I input zero.
0
Sir if we use a for loop instead of a while loop and we fix the number of inputs then requirement of zero get vanish
0
If you want to fix the number of inputs, then just put a condition in the while loop
0
Sir if you don't mind can you tell me that condition
0
Conditions depend on the number of inputs. If you want three inputs
while i<=3:
(Since your input variable is inside the loop)
Hence it will run 3 times