2014-02-09 94 views
3

我已經設置5個任務做4列出並追加整數和字符串一定的任務,我已經做了,但5日是一個奮鬥的這些任務:我堅持用約

  1. 創建一個文本文件並在其中寫入一個10個英文單詞的列表。
  2. 開發您的程序的一部分,從該文本文件中讀取單詞並隨機選擇一個單詞。
  3. 開發程序的一部分,將單詞中的每個字母替換爲字母表中的相應數字。例如,CAT將變爲3,1,20。
  4. 開發程序的一部分,允許用戶輸入一個數字,然後輸入他們認爲它代表的字母。程序應該告訴他們它是對還是錯,然後用正確的替換顯示該單詞。例如,如果用戶輸入A代表1,那麼它應該說「是」或類似的,然後顯示3,A,20.開發繼續這個程序的部分,直到用戶已經正確猜測了整個單詞爲止。

我已經做了多達4個,但數5林我的代碼掙扎是這樣的:

#Import Section 
import random 
import csv 
import math 

#Start Variables 
Random_Words = [] 
alph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',  'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] 
word_2 = [] 

#Foundation Code (List of words) 
words = open('List_Words.txt') 
first_10 = [] 
for line in words: 
    Random_Words.append(line[:-1]) 

#Making the random word 
word = random.choice(Random_Words) 
word = list(word) 

#Making the random word into an alphabetical numeral 
for character in word: 
    i = 0 
    while i < 26: 
     if character == alph[i]: 
      word_2.append(num[i]) 
     i = i + 1 

#print word 
#print Random_word 
print word_2  

#Letting the person guess the word/ letter 
guess_number = int(raw_input("choose a number: ")) 
guess_letter = raw_input("choose a letter: ") 

i = word.index(guess_letter) 
if word_2[i] == guess_number: 
    print "Correct" 

else: 
    print "Nope" 
+1

裹猜謎邏輯成[功能](HTTP://anh.cs。 luc.edu/python/hands-on/3.1/handsonHtml/functions.html#a-first-function-definition)並調用它直到從main中猜到。 – bereal

回答

2
while(1): 
    print word_2 
    #Letting the person guess the word/ letter 
    guess_number = int(raw_input("choose a number: ")) 
    guess_letter = raw_input("choose a letter: ") 

    i = word.index(guess_letter) 
    if word_2[i] == guess_number: 
     word_2[i] = guess_letter # put guessed letter into word_2, for example "3 A 20" 
     print "Correct: ", word_2 
     if word == word_2: 
      break 
    else: 
     print "Nope" 
    print "continue guessing" 
+0

謝謝你,這太棒了。 – user3289268