Tej-Singh-Rana
Tej-Singh-Rana

Reputation: 23

what is the concept behind None?

I am getting None when i typed wrong input but when i typed correct input. It is not appear. kindly help me out with this concepts.

def order():
    try:
        count = int(input("How many order ? "))
        return count
    except Exception as e:
        print("Kindly enter in numbers")
        print("Example :- 1, 2, 3, 4, 5 etc..")
    finally:
        print("Thanks to choose our service.")
choice = order()
print(choice, " will be ordered soon!!")

Output:

How many order ? asdd
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
Thanks to choose our service.
None  will be ordered soon!!

Upvotes: 2

Views: 56

Answers (4)

code pinguin
code pinguin

Reputation: 94

If the input can't be converted into an integer, the exception will be triggered and have no return value since it only display some messages. YOu can return 0 if the value is not a valid number.

Upvotes: 0

Gabio
Gabio

Reputation: 9494

In case of an error (if string is provided as an input for example), your code will go to the except block which has no return value (None is the default return value) and that's why your choice variable will be None.

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

Functions in Python always return something. If you don't explicitely specify a return value with return ..., your function will return, by default, None.

If you don't enter a valid input, the return statement of your function won't be executed, so order() returns None, which gets printed as the string 'None' after that.

You could test the return value:

choice = order()
if choice is not None:
    print(choice, " will be ordered soon!!")

so that this won't print in case you didn't make a valid choice.

But you probably would like the user to try again until he submits a valid choice:

def order():
    while True:
        try:
            count = int(input("How many order ? "))
            return count
        except Exception as e:
            print("Kindly enter in numbers")
            print("Example :- 1, 2, 3, 4, 5 etc..")

choice = order()
print(choice, " will be ordered soon!!")

Sample output:

How many order ? e
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
How many order ? r
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
How many order ? 4
4  will be ordered soon!!

Upvotes: 5

Sazzy
Sazzy

Reputation: 1994

On exception, call into the same function to retry:

def order():
    try:
        count = int(input("How many order ? "))
        return count
    except Exception as e:
        print("Kindly enter in numbers")
        print("Example :- 1, 2, 3, 4, 5 etc..")
        return order()
    finally:
        print("Thanks to choose our service.")

Upvotes: 0

Related Questions