Home > OS >  How to reassign variable from None in Python
How to reassign variable from None in Python

Time:10-21

My task here is to have the user enter a series of numbers until they enter "done". Then display which among entered numbers was the largest, and which was the smallest.

I'm having trouble reassigning the variables "largest" and "smallest" from None.

When I run this code, it tells me that we cant use the > function between None and int types.

I tried using an if and while statements to change None to n(input) to no avail. What am I doing wrong here?

n = input("Enter a whole number or 'done' ")
largest = None
smallest = None

if largest := None:
    largest = int(n)

if smallest := None:
    smallest = int(n)


while n.upper() != "DONE":

    n = input("Enter a whole number or 'done' ")

    if n == "done":
        break

    if int(n) > largest:
        largest = int(n)

    if int(n) < smallest:
        smallest = int(n)

if largest <= -99999999999999999999999999999999999999999999999999999999999999999999999:
    print("Not enough data")
else:
    print("Largest number: "   str(largest))

if smallest >= 99999999999999999999999999999999999999999999999999999999999999999999999:
    print("Not enough data")
else:
    print("Smallest number: "   str(smallest))

CodePudding user response:

You've already established your limits. Instead of assigning None to largest and smallest assign those limits. Something like this should work:

largest = -9999999999999999999999999999999999999999999999999999999999999999999
smallest =  9999999999999999999999999999999999999999999999999999999999999999999
n = ""
while n.upper() != "DONE":

    n = input("Enter a whole number or 'done' ")

    if n.upper() == "DONE":
        continue

    if int(n) > largest:
        largest = int(n)

    if int(n) < smallest:
        smallest = int(n)

if largest <= -99999999999999999999999999999999999999999999999999999999999999999999999:
    print("Not enough data")
else:
    print("Largest number: "   str(largest))

if smallest >= 99999999999999999999999999999999999999999999999999999999999999999999999:
    print("Not enough data")
else:
    print("Smallest number: "   str(smallest)

CodePudding user response:

The := is a walrus operator. It is similar to the = operator which is also used to assign values to the variable.

Advantages with the := operator := can be used to assign variables while another expression is being evaluated.

Problems with the above code:

Line 5> if largest := None: Here python is first assigning the largest variable to None, and then it is again checking for the largest variable. Since bool(None) returns False, the if block code is never executed.

The same goes for line 8.

Solution: You can use the is operator or == operator instead of using the := operator.

Correct Code:

Option 1: if largest is None: largest = None

Option2 2: If largest == None: largest = None

Both will work.

  • Related