本文概述
的用户自定义给函数或变量指定的名称称为标识符。它有助于将一个实体与另一个实体区分开, 并且有时还用作该实体使用的定义。与每种编程语言一样, 标识符也有一些限制/限制。因此, 在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 ))
输出如下:
File "/home/9efd6943df820475cf5bc74fc4fcc3aa.py", line 15
def = 12
^
SyntaxError: invalid syntax
- Python中的标识符不能使用任何特殊符号, 如!, @, #, $, %等。
Python3
# Python code to demostrate
# 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 demostrate
# 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
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/69613.html