简体   繁体   中英

what is the matter about this python code?

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

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, eg:

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()) == '-':

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM