How can i update an 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!")
CodePudding user response:
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!")
CodePudding user response:
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