具有多种功能的python编程

标签 python python-3.x

我正在尝试编写一个程序,要求用户输入两种颜色,然后显示结果颜色。这是我目前所拥有的:

#Define function that prompts user to enter data
def ask():
    color1=input('Enter name of first primary color:')
    color2=input('Enter name of second primary color:')
    mixColors(color1,color2)
#Write function that displays the different color combinations
def mixColors(color1,color2):
    if color1==red and color2==blue:
        print('Mixing red and blue, you get purple.')
    elif color1==blue and color2==red:
        print('Mixing blue andred, you get purple.')
    elif color1==red and color2==yellow:
        print('Mixing red and yellow, you get orange.')
    elif color1==yellow and color2==red:
        print('Mixing yellow and red, you get orange.')
    elif color1==blue and color2==yellow:
        print('Mixing blue and yellow you get green.')
    elif color1==yellow and color2==blue:
        print('Mixing yellow and blue, you get green.')
    else:
        print("I don't know what you get by mixing", color1,'and',color2,'.')
ask()

当我运行该程序时,出现此错误消息:

Traceback (most recent call last):
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 23, in <module>
    ask()
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 6, in ask
    mixColors(color1,color2)
  File "/Users/Lin/Documents/Spring Semester 2013/Computer Programming/yuan_linCh0405", line 9, in mixColors
    if color1==red and color2==blue:
NameError: global name 'red' is not defined

最佳答案

在 Python 中,字符串必须用单引号或双引号括起来('")。否则它们将被视为变量。

在这种情况下,red 既不是变量也不是字符串。由于 red 不是字符串,Python 在当前命名空间、父命名空间和全局命名空间中搜索 red。但是在其中任何一个中都找不到变量 red 。因此,它放弃并抛出该错误消息。

所以,所有的if条件都应该是

if color1=="red" and color2=="blue":
...
elif color1=="blue" and color2=="red":
...
elif color1=="red" and color2=="yellow":
...
elif color1=="yellow" and color2=="red":
...
elif color1=="blue" and color2=="yellow":
...
elif color1=="yellow" and color2=="blue":
...

关于具有多种功能的python编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815070/

相关文章:

python - 在 python 中的两个对象之间的操作中,其操作重载为优先级?

python - 尝试拆分字符串,但我不断收到此错误 : "Type Error: must be str or None, not list"

python - 如何让你的主窗口在 Tkinter 成功登录后出现(PYTHON 3.6

Python:从名称为变量的文件导入函数

python - Tensorboard 未在 Windows 上填充图形

python - Wapiti 安全工具 : Getting "Invalid Syntax Error "

python - 将标记器添加到空白英语 spacy 管道

python - 将 '?' 添加到列表中每个字符串的末尾

python - Qt Designer实时显示python脚本的输出

python-3.x - 如何在离线绘图中绘制垂直线?