gpt4 book ai didi

python - 使用 String.split() 掌握 Python

转载 作者:行者123 更新时间:2023-12-01 08:53:05 25 4
gpt4 key购买 nike

如何让这个程序让用户一次输入 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

最佳答案

您只需将单个输入中的数字拆分并使用列表理解将它们转换为整数即可。您还可以使用类似的方法创建 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 时。

关于python - 使用 String.split() 掌握 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com