Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,我一直收到一条错误消息_Python_Python 3.x - Fatal编程技术网

Python,我一直收到一条错误消息

Python,我一直收到一条错误消息,python,python-3.x,Python,Python 3.x,在我的代码中: def get_drink_price (drink): int 0.75 == "Coke" if get_drink_price("Coke"): return Coke # This is just to see what prints print get_drink_price("Coke") 我一直收到以下错误消息: File "<stdin>", line 2 int 0.75 == "Coke"

在我的代码中:

def get_drink_price (drink):
    int 0.75 == "Coke" 
    if get_drink_price("Coke"):
        return Coke


# This is just to see what prints
print get_drink_price("Coke")
我一直收到以下错误消息:

  File "<stdin>", line 2
    int 0.75 == "Coke" 
           ^
SyntaxError: invalid syntax
文件“”,第2行
int 0.75==“焦炭”
^
SyntaxError:无效语法

那是什么?

…因为那不是有效的Python语法。您有以下问题:

  • 您应该使用
    int(n)
    n
    转换为整数
    int
    本身是无效的(因此出现了
    SyntaxError
    )-您可以定义一个名为
    int
    (例如
    int=1
    )的变量,但该变量使用一个等号,并且在对内置的
    int()
    进行阴影处理时,永远不应该这样做
  • 0.75==“Coke”
    是一种布尔比较,不是任何类型的赋值(而且永远不会是
    真的
  • 您不断递归地调用
    get_-weak\u-price
    ,无法
    返回
    ;及
  • Coke
    从未定义,因此
    返回Coke
    无论如何都会导致
    名称错误
  • 我们完全不清楚您试图通过该功能实现什么,但可能:

    def get_drink_price(drink):
        drinks = {'Coke': 0.75, 'Orange': 0.6} # dictionary maps drink to price
        return drinks[drink] # return appropriate price
    
    现在

    也许更接近你想要做的事情:

    def get_drink_price(drink):
        Coke = 0.75 # define price for Coke
        if drink == "Coke": # test whether input was 'Coke'
            return Coke # return Coke price
    

    但是您应该能够看到基于字典的实现更好。

    我觉得您要创建的代码应该像这样做:

    def get_drink_price(drink):
        prices = { "Coke":0.75, "Pepsi":0.85}
        return prices[drink]
    
    
    print get_drink_price("Coke")
    

    函数中的prices对象只是一个dictionary,它是一个标准的python对象。您可以在此处查找有关词典的更多信息:,但如果您要做的是从名称中查找饮料的价格,那么这是一种简单、直接的方法

    那是。。。不是Python,你的代码有很多不同的问题;我担心这里有太多的错误,甚至无法开始解决它们。你的教程处于什么阶段?看起来您也在学习Python 2的教程(使用
    print
    语句而不是
    print()
    函数),但是您用Python 3标记了它。我无法确切地告诉您想要做什么。也许你应该解释一下。这应该做什么呢?我想你应该在写下更多的代码之前仔细检查一下。它会让你对语言有一个最低限度的了解。除非您有更好的解释,否则看起来您只是在试图将Python语法强制转换为运行的东西。不要这样做:)在第二点划线。是完全错误的,因为
    int
    部分看起来像是在Python中声明变量的错误尝试。除非OP有别的意思,但我真的不知道。是的,我想知道这是否应该是
    Coke=0.75
    (两者都不是
    int
    ,但是…)re-+1(你已经有了我的+1)来从OP的意图中提取一个可接受的假设。另一个虚拟+1,因为在另一个答案之前没有看到你的编辑:)不用担心,我只是有点冒犯了!
    def get_drink_price(drink):
        prices = { "Coke":0.75, "Pepsi":0.85}
        return prices[drink]
    
    
    print get_drink_price("Coke")