首页 > 解决方案 > 如何让我的 Python 程序根据响应重新定义变量?

问题描述

所以,我已经为选择你自己的冒险游戏编写了代码,或者至少是一个游戏的开始,我需要知道如何让我的代码根据input()响应更改变量的定义。这是我的代码:

import time
import winsound
PlayerAttributes = None
dream_item = None
print("ADVENTURE")
time.sleep(1)
print("Programmed and Developed by:")
print("Gabe 'GabeCodes' Chavez")
time.sleep(2)
print("We meet our heroes.")
print("Alice: The trained explorer doesn't give up hope.")
print("Although she isn't the strongest, she is the smartest person in the crew.")
print("")
time.sleep(6)
print("Sean: The fun loveable Irishman. He is quick on his feet, but not so much")
print("in the classroom. He has an innate sense of direction.")
print("")
time.sleep(6)
print("Mark: While he is strong, he is very ill-tempered and easy to aggravate.")
print("He tends to sleepwalk and has an inexplicable fear of elephants.")
print("")
time.sleep(6)
print("Amy: Amy is one of the kindest. Not just in the crew, but as an overall person.")
print("She is great with medicine and doesn't fear Mark's anger. They actually make a great balance, 
and a cute couple.")
print("")
time.sleep(6)
print("Choose your Character... ")
PlayerChoice = input()
if PlayerChoice == "Alice" or "alice":
    PlayerAttributes == "smart" and "fast"
    dream_item == "golden totem"
elif PlayerChoice == "Sean" or "sean":
    PlayerAttributes == "clumsy" and "fast"
    dream_item == "little green eyeball"
elif PlayerChoice == "Mark" or "mark":
    PlayerAttributes == "strong" and "smart"
    dream_item == "tiny box"
elif PlayerChoice == "Amy" or "amy":
    PlayerAttributes == "kind" and "healer"
    dream_item == "dark iced coffee"
print("You wake with a start. You see your door, window, and dresser.")
time.sleep(2)
print("'What was I dreaming?' you thought. 'There was a", dream_item, "or something.")

标签: pythoninputcustomization

解决方案


如果要将单个值与多个值进行比较,使用这种语法将失败:

if my_animal is "cat" or "horse":
    my_operation()

这有几个原因。首先是运算符优先级将语句解释为:

if (my_animal is "cat") or "horse":
    my_operation()

...并且无论(my_animal is "cat"),"horse"本身(或任何字符串、标量、非空序列)的真实性如何,都将被评估为True.

此语法失败的第二个原因是is运算符检查两个对象是否是内存中的相同对象,而不是等效值。

所以要纠正这个问题,你可以说:

if my_animal == "cat" or my_animal == "horse":
    my_operation()

如果你有很多动物要检查,这会变得很麻烦。在这种情况下,我会建议:

valid_animals = ["cat", "fish", "horse", "dog"]
if my_animal in valid_animals:
    my_operation()

如果您要检查不同的大小写,我建议将字符串转换为全部大写或小写:

if character_name.lower() == 'alice':
    character_action()

最后,在你说类似的地方PlayerAttributes == "clumsy" and "fast",你离那里很远。

首先,==是比较,而不是分配。

所以修复它并打开一个python解释器并自行评估该语句。例如,

>>> PlayerAttributes = "clumsy" and "fast"
>>> print(PlayerAttributes)

你会得到True,因为就像我们上面所说的,字符串是“真实的”并且True and True评估为True.

如果要将多个值分配给单个变量,则需要使用列表、元组或其他序列。

PlayerAttributes = ["clumsy", "fast"] # that's a list

推荐阅读