Python 3 语法错误无效语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41662612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:23:18  来源:igfitidea点击:

Python 3 syntax error invalid syntax

pythonsyntax

提问by Bbrown

With this code I am trying to generate simple multiplication tables. The program should ask for input and multiple that number in a range up to 15 and the generate the multiplication table for the number. After the if_name_ == 'main': line I end up with a syntax error after the colon. I normally program in python 2, so python 3 is a bit new to me but I'm not sure what the difference is. Below I have listed the short but full code. Any help would be much appreciated.

使用此代码,我正在尝试生成简单的乘法表。程序应要求输入并将该数字乘以最多 15 的范围,并生成该数字的乘法表。在 if_name_ == ' main': 行之后,冒号后出现语法错误。我通常在 python 2 中编程,所以 python 3 对我来说有点新,但我不确定有什么区别。下面我列出了简短但完整的代码。任何帮助将非常感激。

'''Multiplication Table'''

def multi_table(a):
    for i in range(1,16):
        print(' {0} x {1} = {2} '.format(a, i, a*i))



if_name_ == '_main_':
    a = input('Enter a number: ')
    multi_table(float(a))

回答by Inconnu

if_name_ == '_main_':
    a = input('Enter a number: ')
    multi_table(float(a))

should be :

应该 :

if __name__ == "__main__":
    a = input('Enter a number: ')
    multi_table(float(a))

Notice that both variable __name__and __main__has two underscores around them and that there must be a space between the if keyword and the start of the condition.

请注意, variable__name____main__周围有两个下划线,并且 if 关键字和条件的开头之间必须有一个空格。

回答by LMD

As @Maroun Maroun said right, it has to be if __name__ == "__main__". But you wont need it. Just write it at the bottom :

正如@Maroun Maroun 所说,它必须是if __name__ == "__main__". 但你不会需要它。直接写在底部:

'''Multiplication Table'''

def multi_table(a):
    for i in range(1,16):
        print(' {0} x {1} = {2} '.format(a, i, a*i))

a = input('Enter a number: ')
multi_table(float(a))

Should work, too.

也应该工作。

EDIT: In the official docs :

编辑:在官方文档中:

https://docs.python.org/3/library/main.html

https://docs.python.org/3/library/主要的.html

if __name__ == "__main__":

if __name__ == "__main__":