简体   繁体   English

用 String.split() 设计 Python

[英]Mastermind Python with String.split()

How can you make this program make the user input 5 digits at once, instead of asking separate numbers each time?你怎样才能让这个程序让用户一次输入 5 位数字,而不是每次都问不同的数字? I know I have to use string.split() but where would I place the code and execute the code.我知道我必须使用 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

You just have to split the numbers in a single input and convert them into integers using a list comprehension.您只需要在单个输入中拆分数字并使用列表理解将它们转换为整数。 You can also create your random_n using a similar method.您还可以使用类似的方法创建您的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!

Edited: Added break if attempts more than 10, in this case when your counter c is more than 10.编辑:如果尝试超过 10 次,则添加中断,在这种情况下,当您的计数器c超过 10 次时。

You can try using raw_input :您可以尝试使用raw_input

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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