簡體   English   中英

Python - 將字符串與列表中的隨機項進行比較

[英]Python - Compare string to random item from list

查看很多現有問題,而不是看到完全相同的情況。 我正在研究Python的基礎知識,並嘗試創建無處不在的Rock,Paper,Scissors游戲。 但是,我有一個等於用戶猜測的變量,我無法成功地與代表計算機猜測的隨機選擇項進行比較。 一切都評價為“你贏了!:)”,即使它不應該表明兩個變量永遠不會相等。 我已經嘗試過使用str(computer_choice)而沒有任何運氣。

這是完整的代碼:

import time
import random

rps = ['Rock', 'Paper', 'Scissors']

computer_choice = random.sample(rps, 1)

print("Let's play some Rock, Paper, Scissors")
print("Hit enter when ready:")
input("")

print("Rock...")
time.sleep(1)
print("Paper...")
time.sleep(1)
print("Scissors...")
time.sleep(.75)
print("SHOOT!")

print("Which is it?")
user_choice = input(">>>")



while True:
    valid_check = user_choice in rps
    if valid_check == True:
        break
    else:
        print('Bad input, try again:')
        user_choice = input(">>>")

print("The computer picked: %s" % computer_choice)

if user_choice == computer_choice:
    print("It's a draw!")

elif user_choice == 'Rock':
    if computer_choice == 'Paper':
        print("You lose :(")

    else:
        print("You win! :)")

elif user_choice == 'Paper':
    if computer_choice == 'Scissors':
        print("You lose :(")

    else:
        print("You win! :)")

elif user_choice == 'Scissors':
    if computer_choice == 'Rock':
        print("You lose :(")

    else:
        print("You win! :)")

您需要使用random.choice(rps)返回原始列表的元素而不是random.sample(rps,1) ,它返回原始列表中大小為1的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM