我被一个关于列表和附加整数和字符串的任务困住了

2022-10-02 01:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我被安排了5项任务,其中4项我已经完成了,但第5项是一场斗争这些任务是:

  1. 创建一个文本文件并在其中列出10个英语单词。你知道吗
  2. 开发程序中从这个文本文件中读取单词的部分,然后随机选择一个。你知道吗
  3. 开发程序的一部分,将单词中的每个字母替换为字母表中相应的数字。例如,猫会变成3,1,20。你知道吗
  4. 开发程序的一部分,允许用户输入一个数字,然后输入他们认为代表的字母。程序应该告诉他们这是对的还是错的,然后用正确的替换词来显示这个词。例如,如果用户为1输入A,那么它应该说“是”或类似的,然后显示3、A、20。你知道吗
  5. 开发程序的一部分,直到用户正确猜出整个单词为止。你知道吗

我已经做了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"

Tags: the用户import程序numberrandom单词wordwordsprint文本文件guessletter
1条回答
网友
1楼 ·
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"