0

Hi so the question I completed involves while loops and although I finished it and got the expected outcome, I added a random line of code for "fun" to see what it would do, you could call it guessing and checking.

x = int(input())

increase = 0
while x != 0:
   increase += x
   **x = int(input())**
  
print(increase)

the line that I guessed has asterisks beside it, can someone please let me know what this simple line does.

If it helps: My question is to input as many numbers as I please, but when I input the value 0, my code should return the sum of the number I inputted before the zero

Bhavis456
  • 21
  • 2
  • Just read this 'https://stackoverflow.com/questions/400739/what-does-asterisk-mean-in-python'. And you should revise your code, programming is not just about the solution, but an understandable solution that is equally efficient and many other aspects. – Higs Jan 12 '21 at 14:19

3 Answers3

1

The while loop waits for you to enter a value. This is done with input(). Because you need an integer (input always returns a string) int() is called on the input, which returns an integer (if possible). Everytime an input is made and converted to an integer the while loop starts the next iteration and checks if the previous input was equal to 0. If so, the while loop stops and (in this case) your print statement is executed. This is exactly what you wanted to do.

Honn
  • 737
  • 2
  • 18
1

The function call input() takes user input from the console and makes it available to your code as a string. int(input()) converts the string input from the user, and tries to cast that value to an integer. That integer is then added to running count you have specified as increase.

Just to point out, you will get an error if a user specifies input that cannot be converted to an int, like typing in 'meow'. It will throw a ValueError.

1
x = int(input()) #takes user input string and try to convert to integer data type 

increase = 0  # set value to variable increase
while x != 0: # condition    
    increase += x # it add/sum the value of the variable x to the value of the variable increase
    x = int(input()) #takes user input string and try to convert to integer data type inside the while loop
print(increase) # print the value

watch this code in action on pythontutor

Avatazjoe
  • 465
  • 6
  • 13