用String.split()策划Python

时间:2018-10-25 01:58:44

标签: python

如何使该程序使用户一次输入5位数字,而不是每次都输入单独的数字?我知道我必须使用string.split(),但是我应该在哪里放置代码并执行代码。

Heading

from random import randint

n1 = randint(1,9)
n2 = randint(1,9)
n3 = randint(1,9)
n4 = randint(1,9)
c = 1

while True:
    print (n1,n2,n3,n4)
    guess1 = input("guess the first number")
    guess2 = input("guess the second number")
    guess3 = input("guess the third number")
    guess4 = input("guess the fourth number")
    guess1 = int(guess1)
    guess2 = int(guess2)
    guess3 = int(guess3)
    guess4 = int(guess4)
    numberswrong = 0

    if guess1 != n1:
        numberswrong += 1
    if guess2 != n2:
        numberswrong += 1

    if guess3 != n3:
        numberswrong += 1

    if guess4 != n4:
        numberswrong += 1

    if numberswrong == 0:
        print('Well Done!')
        print('It took you ' + str(c) + ' ries to guess the number!')
        break
    else:
        print('You got ' + str(4-numberswrong) + ' numbers right.')
    c += 1

2 个答案:

答案 0 :(得分:1)

您只需要将数字拆分为一个输入,然后使用列表推导将它们转换为整数。您也可以使用类似的方法来创建random_n

from random import randint

random_n = [randint(1,9) for i in range(4)]
c = 1

while True:
    print(random_n)
    user_input = [int(i) for i in input("guess the numbers: ").split()]

    numberswrong = 0

    if user_input[0] != random_n[0]:
        numberswrong += 1
    if user_input[1] != random_n[1]:
        numberswrong += 1
    if user_input[2] != random_n[2]:
        numberswrong += 1
    if user_input[3] != random_n[3]:
        numberswrong += 1

    if numberswrong == 0:
        print('Well Done!')
        print('It took you ' + str(c) + ' tries to guess the number!')
        break
    else:
        print('You got ' + str(4-numberswrong) + ' numbers right.')

    c += 1

    if c > 10:
        print('More than 10 failed attempts. End.')
        break

>>
[3, 9, 1, 6]
guess the numbers: 1 2 1 6
You got 2 numbers right.
[3, 9, 1, 6]
guess the numbers: 3 9 1 6
Well Done!
It took you 2 tries to guess the number!

已编辑:如果尝试次数超过10,则添加中断,在这种情况下,当您的计数器c超过10时。

答案 1 :(得分:0)

您可以尝试使用raw_input

Guesses= raw_input("Guess 5 numbers (separated by comma)")
Guess_list= Guesses.split(",")