提供字符串值时遇到问题(Python)

时间:2017-11-20 09:30:32

标签: python

对于学校我打算创建一个程序来识别你的心情然后告诉你它到底是什么。无论如何我的代码我一直在弄错我为字符串赋值的方式。目前我的代码如下所示:

import random
smiles = ['XD',';)',':)',':()',':(']
history = []
reality = random.choice(smiles)

('XD')= 5
(':)') = 4
(':|') = 3
(':T') = 2
(':(') = 1

def menu():
    print (smiles)
    int(input("Which emoticon do you relate to?"))
     if 1:
         print("You are Fealing like XD")
         print("but in reality you are feeling like", reality)
     etc

感谢。

2 个答案:

答案 0 :(得分:0)

如评论中所述,您无法为字符串分配值,您需要将它们存储在集合,字典或列表等类型中。

鉴于您要求用户输入一个数字,您只需将用户输入分配给变量,然后将其与数组中的索引进行比较。对于超出数组长度的输入,请随意添加错误处理。

int(input("Which emoticon do you relate to?"))
 if 1:

可能是

user_input = int(input("Which emoticon do you relate to?"))
if user_input - 1 == 0:  # -1 since lists are 0 indexed.

你也可以使这个通用并删除if语句,然后使用

users_smile = smiles[user_input - 1]
print("You are Fealing like {}".format(users_smile))

答案 1 :(得分:0)

你不能为@juanpa.arrivillaga所说的字符串赋值,所以你应该使用字典

smiles_dict = { 5: 'XD', 4: ':)', 3: ':|', 2: ':T', 1: ':(' }

然后使用

smiles_dict.get(reality)

希望这可以帮到你