Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What went wrong in my simple code?

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 370
    Answer it

    # A very simple python program to compare two numbers using functions 

    from sys import exit
    
    def main():
        check()
        compare(x, y)
    
    def check():
        # prompt user for two numbers
        x = input("x: ")
        y = input("y: ")
    
        # apply sanity check
        if x.isnumeric() == False and y.isnumeric() == False:
            print("Usage: only real numbers are accepted.")
            exit(1)
        else:
            return x, y
    
    def compare(x, y):
        # TODO
        if x < y:
            return print("x is smaller than y")
        elif x > y:
            return print("x is greater than y")
        else:
            return print("They are the same!")
    
    main()

     

 1 Answer(s)

  • I modified your code.
    First Modification is receive values with in the local variables and second modification is modify return values to int(..) otherwise it will take values in string form and while comparing 11 and 2 it will compare the values according to ASCII CODE and give 11 is less than 2.
    Here is the new code modified code .

    from sys import exit
    def main():
        a,b = check()
        compare(a,b)
    def check():
        # prompt user for two numbers
        x = input("x: ")
        y = input("y: ")
        # apply sanity check
        if x.isnumeric() == False and y.isnumeric() == False:
            print("Usage: only real numbers are accepted.")
            exit(1)
        else:
            return int(x), int(y)
    def compare(x, y):
        # TODO
        if x < y:
            return print("x is smaller than y")
        elif x > y:
            return print("x is greater than y")
        else:
            return print("They are the same!")
    main()
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: