Python函数名中允许使用哪些字符?
赋予函数或变量的用户定义名称称为标识符。它有助于区分一个实体和另一个实体,有时还可以定义该实体的使用。与每种编程语言一样,标识符也有一些限制/限制。因此,对于Python来说,在使用标识符之前,我们需要注意以下几点。
编写标识符的规则:
- 第一个也是最重要的限制是标识符不能与关键字相同。每种编程语言中都有特殊的保留关键字,它们有自己的含义,这些名称不能用作Python中的标识符。
Python3
# Python program to demonstrate
# that keywords cant be used as
# identifiers
def calculate_sum(a, b):
return a + b
x = 2
y = 5
print(calculate_sum(x,y))
# def and if is a keyword, so
# this would give invalid
# syntax error
def = 12
if = 2
print(calculate_sum(def, if))
Python3
# Python code to demonstrate
# that we can't use special
# character like !,@,#,$,%.etc
# as identifier
# valid identifier
var1 = 46
var2 = 23
print(var1 * var2)
# invalid identifier,
# will give invalid syntax error
var@ = 12
$var = 55
print(var@ * $var)
# even function names can't
# have special characters
def my_function%():
print('This is a function with invalid identifier')
my_function%()
Python3
# Python program to demonstrate
# some examples of valid identifiers
var1 = 101
ABC = "This is a string"
fr12 = 20
x_y = 'GfG'
slp__72 = ' QWERTY'
print(var1 * fr12)
print(ABC + slp__72)
输出:
File "/home/9efd6943df820475cf5bc74fc4fcc3aa.py", line 15
def = 12
^
SyntaxError: invalid syntax
- Python中的标识符不能使用任何特殊符号,如 !、@、#、$、% 等。
Python3
# Python code to demonstrate
# that we can't use special
# character like !,@,#,$,%.etc
# as identifier
# valid identifier
var1 = 46
var2 = 23
print(var1 * var2)
# invalid identifier,
# will give invalid syntax error
var@ = 12
$var = 55
print(var@ * $var)
# even function names can't
# have special characters
def my_function%():
print('This is a function with invalid identifier')
my_function%()
输出:
File "/home/3ae3b1299ee9c1c04566e45e98b13791.py", line 13
var@ = 12
^
SyntaxError: invalid syntax
- 除了这些限制之外, Python还允许标识符是小写字母(a 到 z)或大写字母(A 到 Z)或数字(0 到 9)或下划线 (_) 的组合。但变量名不能以数字开头。 myClass、var_3 和 print_to_screen 等名称都是有效的示例。
Python3
# Python program to demonstrate
# some examples of valid identifiers
var1 = 101
ABC = "This is a string"
fr12 = 20
x_y = 'GfG'
slp__72 = ' QWERTY'
print(var1 * fr12)
print(ABC + slp__72)
输出:
2020
This is a string QWERTY