[英]Mastermind Python with String.split()
你怎樣才能讓這個程序讓用戶一次輸入 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 次時。
您可以嘗試使用raw_input
:
Guesses= raw_input("Guess 5 numbers (separated by comma)")
Guess_list= Guesses.split(",")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.