Home > Blockchain >  what is the matter about this python code?
what is the matter about this python code?

Time:07-18

for i in range(30):
    if input() == '-':
        case = 0
    else:
        case = input()
    print(case)

here is my code, and result is like this: (emphasized one is input)

*-*
0
*10*
*10*
10

it works well with printing - for 0, but it prints only every second number if I input numbers in a row

CodePudding user response:

Each input() call is getting you a new value. The input() that checks for '-' returns a different value from the one you assign to case. If you want to reuse the same value, you need to assign it to a temporary variable and reuse it, e.g.:

for i in range(30):
    inp = input()
    if inp == '-':
        case = 0
    else:
        case = inp
    print(case)

With the walrus in 3.8 , you can condense two lines:

    inp = input()
    if inp == '-':

to one if you really want, but there's little benefit to be had here:

    if (inp := input()) == '-':

CodePudding user response:

Everytime you call input(), it asks for another input from the user. The correct way to do it is:

for i in range(30):
    x = input()
    if x == '-':
        case = 0
    else:
        case = x
    print(case)
  • Related