Find greater number of two numbers using function

Viewed 610

I try to find the greater number of the two numbers inputting by the user, using function. Please help me identify the fault I made in the code which produces a wrong result:

def func1(n1,n2):
    if (n1 > n2):
        print(n1," is greater than ",n2)
    else:
        print(n2," is greater than ",n1)

print("Find which number is greater")
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
func1(num1, num2)    

It shows a wrong result:

Find which number is greater
Enter the first number: 10
Enter the second number: 5
5  is greater than  10
4 Answers

force input to int

def func1(n1,n2):
    if (n1 > n2):
        print(n1," is greater than ",n2)
    else:
        print(n2," is greater than ",n1)

print("Find which number is greater")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
func1(num1, num2) 

for your function you can acheive that in one line

def func1(n1,n2):
        return str(n1)+" is greater than "+str(n2) if n1>n2 else str(n2)+" is greater than "+str(n1)
        

Using pydantic. You can python -m pip install --user pydantic.

Pydantic will help you perform data validation, conversation and friendly errors when data is invalid.

from pydantic import BaseModel

class InputValues(BaseModel):
    n1: int
    n2: int


def f(n1,n2):
   # let PyDantic deal with conversation 
    num = InputValues(n1=n1, n2=n2)
    if (num.n1 > num.n2):
        print(f"{n1} is greater than {n2}")
    else:
        print(f"{n2} is greater than {n1}")

# Example:

n = "10"
m = "5"

f(n,m)

Why use Pydantic over simple casting

int(input...) will fail if invalid input are passed. The different between the two is that one will tell you exactly what the problem is.

You can find more on pydantic

The reason is, the input function produces a string value. So changed the code to like:

def func1(n1,n2):
    if (n1 > n2):
        print(n1," is greater than ",n2)
    else:
        print(n2," is greater than ",n1)

print("Find which number is greater")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
func1(num1,num2)   

Output:

Find which number is greater
Enter the first number: 5
Enter the second number: 10
10  is greater than  5

via f-string -

def func1(n1,n2):
    print(f'{n1} is greater than {n2}' if (n1> n2) else f'{n1} is greater than {n2}')


print("Find which number is greater")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
func1(num1,num2)   
Related