所以我很新的python和我正在做一个hang子手程序。这是我迄今为止的代码。我需要用户输入来告诉程序使用哪个列表?
import random
print('Welcome to hangman')
print('Type one of the following catagories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')
catagory=input()
randomwordindex=random.randint(1,7)
凡说category=input()
我希望用户输入的是我有上述列表中的一个。然后我可以用随机整数category
来选择一个随机单词来开始游戏。我如何获得input()
作为列表而不是字符串值?
编辑:好吧,我得到了谢谢你们。
这是我目前的代码。我可能最终会添加一个for循环,并清理我的while循环,所以它是一行。
import random
print('Welcome to hangman')
print('Type one of the following catagories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
catagory=int(input())
while catagory > 4:
print('Your input isn\'t one of the catagories. Make sure your choice is a number from 1 to 4.')
print('Try entering again')
print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
catagory=int(input())
while catagory == 0:
print('Your input isn\'t one of the catagories. Make sure your choice is a number from 1 to 4.')
print('Try entering again')
print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
catagory=int(input())
if catagory == 1: secretword=random.choice(Animal)
if catagory == 2: secretword=random.choice(Clothing)
if catagory == 3: secretword=random.choice(Weather)
if catagory == 4: secretword=random.choice(Colors)
现在变量secretword
存储从列表中随机选择的单词。
如果你的目标是让用户输入密码,在这种情况下的列表,你可以使用'的eval()'函数。然而,这是非常危险的,不应该被其他人使用的代码使用。使用eval基本上是将一个字符串转换为真正的代码。你不能用一个数字打印清单,比如''Option 1 Animal'''?它似乎更加用户友好和安全。 – Mikael
@Mikael我和''Option 1. Animal“'有什么区别?你能否详细说明一下? – Keizzerweiss