2016-12-14 28 views
2

所以我有一個班級任務,我必須做一個石頭紙剪刀遊戲,並停止作弊。我不斷收到TypeError:不可能的類型:'列表'Python新手:獲取TypeError:不可用類型:'list'

我不知道是什麼原因造成的;有人可以幫我解決這個問題嗎?

import random 
import re 

def MatchAssess(): 
    if userThrow == compThrow: 
     print("Draw") 
    elif userThrow == "r" and compThrow == "p": 
     print("Computer chose paper; you chose rock - you lose") 
    elif userThrow == "p" and compThrow == "s": 
     print("Computer chose scissors; you chose paper - you lose!") 
    elif userThrow == "r" and compThrow == "p": 
     print("Computer chose paper; you chose rock - you lose!") 
    elif userThrow == "s" and compThrow == "r": 
     print("Computer chose rock; you chose scissors - you lose!") 
    else: 
     print("you win") 



CompThrowSelection = ["r","p","s"] 
ThrowRule = "[a-z]" 

while True: 
    compThrow = random.choice(CompThrowSelection) 
    userThrow = input("Enter Rock [r] Paper [p] or Scissors [s]") 
    if not re.match(CompThrowSelection,userThrow) and len(userThrow) > 1: 
     MatchAssess() 
    else: 
     print("incorrect letter") 
     userThrow = input("Enter Rock [r] Paper [p] or Scissors [s]") 
+0

're.match(CompThrowSelection,userThrow)'是比較錯誤的東西 - 它不應該是CompThrowSelection,因爲正則表達式不是列表。相反,我認爲它應該是'ThrowRule','ThrowRule'應該是'[rps]' –

回答

2

我注意到你的代碼邏輯有些問題。

一個是re.match()將應用於模式而不是列表上。對於list我們可以使用像,

if element in list: 
    # Do something 

接下來的是,如果用戶進行了有效的輸入len(userThrow) > 1將永遠無法滿足。所以製作len(userThrow) >= 1甚至== 1

最後,我在條件分支上添加了一條continue語句來捕獲錯誤的輸入,而不是從那裏讀取輸入。


最後,這是工作代碼!

while True: 
    compThrow = random.choice(CompThrowSelection) 
    userThrow = raw_input("Enter Rock [r] Paper [p] or Scissors [s]") 
    if userThrow in CompThrowSelection and len(userThrow) >= 1: 
     MatchAssess() 
    else: 
     print("incorrect letter") 
     continue 

希望這有助於! :)

0

應該爲

if userThrow in CompThrowSelection and len(userThrow) == 1: # this checks user's input value is present in your list CompThrowSelection and check the length of input is 1 
    MatchAssess() 

予以糾正
userThrow = raw_input("Enter Rock [r] Paper [p] or Scissors [s]") # raw_input() returns a string, and input() tries to run the input as a Python expression (assumed as python 2) 
0

您可以實現這樣說:

import random 

cts = ["r","p","s"] 

def match_assess(ut): 
    ct = random.choice(cts) 
    if ut == ct: 
     print('Draw. You threw:'+ut+' and computer threw:'+ct) 
    elif (ut=="r" and ct == "p") or (ut == "p" and ct == "s") or (ut == "r" and ct == "p") or (ut == "s" and ct == "r"): 
     print ('You Loose. You threw:'+ut+' and computer threw:'+ct) 
    else: 
     print ('You Win. You threw:'+ut+' and computer threw:'+ct) 
a = 0 
while a<5: #Play the game 5 times. 
    ut = raw_input("Enter Rock [r] Paper [p] or Scissors [s]") 
    if ut in cts and len(ut) == 1: 
     match_assess(ut) 
    else: 
     print("incorrect letter") 
    a+=1 
相關問題