How to update an variable in loop, python

Question:

How can I update a variable so the program don’t print the same number everytime. For example if I write "smart" then the program will print 37 letters left, but if I write a new adjective it will still print that I have 37 letters left.

letter = 42

if letter >= 42:
    print("You have", letter, "letters left")

adj = input("Describe yourself with an adjective")
adjletter = len(adj)
letterleft = letter-adjletter

while letterleft > 0:
    print("You have", letter-adjletter, "letters left")
    adj2 = input("Describe yourself with an adjective")
    if letter < 0:
        break
print("Thanks for now!")

Asked By: Sebastian

||

Answers:

You already have it in your code, outside the loop. Note there is some redundant code in your snippet.

letter = 42

while letter > 0:
    print(f"You have {letter} letters left")
    adj = input("Describe yourself with an adjective: ")
    letter -= len(adj.strip(()) # add strip to remove any whitespace
print("Thanks for now!")
Answered By: buran

Have updated some part of your code, please refer to below code which gives desired results:

letter = 42

if letter >= 42:
    print("You have", letter, "letters left")

letterleft = letter

while letterleft > 0:
    adj = input("Describe yourself with an adjective: ")
    letterleft = letterleft-len(adj)
    print("You have", letterleft, "letters left")
    
print("Thanks for now!")

Output:

You have 42 letters left
Describe yourself with an adjective: smart
You have 37 letters left
Describe yourself with an adjective: smart
You have 32 letters left
Describe yourself with an adjective: smart
You have 27 letters left
Describe yourself with an adjective: 

You were iterating over letterleft, however never updated it and hence will get an infinite loop. Also adjletter will always be 5 if input is smart and hence your print statement always prints 37 (42-5) for letters left. Instead the print statement should print letterleft

Answered By: Bhagyesh Dudhediya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.