Home >Backend Development >Python Tutorial >Detailed explanation of Python's basic syntax and data types
When learning the Python programming language, mastering the basic syntax and data types is essential. Here, we will explain Python's variables and constants, data types such as strings, numbers, lists, tuples, and dictionaries, as well as the use of conditional statements, loop statements, and functions.
In Python, variables are identifiers used to store data, and their values can change at any time. Constants in Python refer to data whose values do not change and are usually represented by uppercase letters.
In Python, variable assignment can be performed using the equal sign (=), for example:
a = 10
The above code assigns the number 10 Give variable a. You can use the print() function to output the value of a variable:
print(a) # 输出 10
Strings are one of the most commonly used data types in Python. They are composed of a series of composed of characters. Strings can be created using single, double or triple quotes, for example:
str1 = 'Hello World' str2 = "Python Programming" str3 = """This is a multiline string that spans multiple lines"""
Strings support many operations such as string concatenation, string formatting, and string splitting, etc. . Here are some common string operations:
# 字符串连接 str1 = 'Hello' str2 = 'World' print(str1 + ' ' + str2) # 输出 'Hello World' # 字符串格式化 name = 'John' age = 20 print('My name is %s and I am %d years old' % (name, age)) # 输出 'My name is John and I am 20 years old' # 字符串分割 str1 = 'one,two,three' print(str1.split(',')) # 输出 ['one', 'two', 'three']
Numbers in Python include integers, floating point numbers, and complex numbers. Integers can be positive, negative, or zero, floating point numbers are numbers with a decimal part, and complex numbers consist of a real part and an imaginary part.
You can use basic arithmetic operators ( , -, *, /, % and **) to perform numerical calculations. Here are some common number operations:
# 整数和浮点数运算 a = 10 b = 3 print(a + b) # 输出 13 print(a - b) # 输出 7 print(a * b) # 输出 30 print(a / b) # 输出 3.3333333333333335 print(a % b) # 输出 1 print(a ** b)# 输出 1000 # 复数运算 c = 3 + 4j d = 1 - 2j print(c + d) # 输出 (4+2j) print(c - d) # 输出 (2+6j) print(c * d) # 输出 (11+2j) print(c / d) # 输出 (-1-2j)
Lists are one of the most commonly used data types in Python. They consist of a sequence of elements that can Is any type of data, including numbers, strings, lists, etc. Lists are created using square brackets ([]), for example:
list1 = [1, 2, 3, 4, 5] list2 = ['apple', 'banana', 'orange'] list3 = [1, 'hello', 3.14, [1, 2, 3]]
Lists support many operations, such as element access, element addition, element deletion, and list slicing. The following are some common list operations:
# 元素访问 list1 = [1, 2, 3, 4, 5] print(list1[0]) # 输出 1 print(list1[3]) # 输出 4 # 元素添加 list2 = ['apple', 'banana', 'orange'] list2.append('grape') # 添加一个元素 print(list2)# 输出 ['apple', 'banana', 'orange', 'grape'] # 元素删除 list3 = [1, 'hello', 3.14, [1, 2, 3]] del list3[1] # 删除第二个元素 print(list3) # 输出 [1, 3.14, [1, 2, 3]] # 列表切片 list4 = [1, 2, 3, 4, 5] print(list4[1:3]) # 输出 [2, 3] print(list4[:3])# 输出 [1, 2, 3] print(list4[3:])# 输出 [4, 5]
Tuples are similar to lists and are also composed of a series of elements. The difference is that once a tuple is created It cannot be modified. Tuples are created using parentheses (()), for example:
tuple1 = (1, 2, 3, 4, 5) tuple2 = ('apple', 'banana', 'orange') tuple3 = (1, 'hello', 3.14, [1, 2, 3])
The access of tuples is similar to that of lists, and elements can be accessed using subscripts. The following are some common tuple operations:
# 元素访问 tuple1 = (1, 2, 3, 4, 5) print(tuple1[0]) # 输出 1 print(tuple1[3]) # 输出 4 # 元组连接 tuple2 = ('apple', 'banana', 'orange') tuple3 = (1, 'hello', 3.14, [1, 2, 3]) tuple4 = tuple2 + tuple3 print(tuple4) # 输出 ('apple', 'banana', 'orange', 1, 'hello', 3.14, [1, 2, 3])
Dictionary is another commonly used data type in Python. They consist of a series of key-value pairs, each Use commas (,) to separate key-value pairs, and use curly braces ({}) to create the entire dictionary. For example:
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
Dictionary access can be achieved through keys, as follows Are some common dictionary operations:
# 访问字典中的值 dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1['name'])# 输出 Tom print(dict1['age']) # 输出 20 # 添加/修改字典中的元素 dict2 = {'name': 'Jerry', 'age': 25, 'gender': 'male'} dict2['height'] = 175# 添加一个键值对 dict2['age'] = 30# 修改一个键对应的值 print(dict2) # 输出 {'name': 'Jerry', 'age': 30, 'gender': 'male', 'height': 175} # 删除字典中的元素 dict3 = {'name': 'Lucy', 'age': 18, 'gender': 'female'} del dict3['age']# 删除一个键值对 print(dict3)# 输出 {'name': 'Lucy', 'gender': 'female'}
In Python, conditional statements mainly include if statements and if-else statements. The if statement is used to determine whether a condition is true. If the condition is true, the following code block is executed, otherwise the code block is skipped. The if-else statement adds an else statement based on if, which is used to execute the corresponding code block when the condition is not true. Here is an example of a simple if statement:
age = 20 if age >= 18: print('你已经成年了')
Here is an example of an if-else statement:
age = 16 if age >= 18: print('你已经成年了') else: print('你还未成年')
In addition to if and if-else statement, Python also provides if-elif-else statements for judging multiple conditions. The following is an example of an if-elif-else statement:
score = 85 if score >= 90: print('优秀') elif score >= 80: print('良好') elif score >= 60: print('及格') else: print('不及格')
The loop statements in Python mainly include for loops and while loops. The for loop is used to traverse a sequence, such as a list, tuple, string, etc. It will take out an element in the sequence in each loop and execute the corresponding code block. The following is a simple for loop example:
fruits = ['apple', 'banana', 'orange'] for fruit in fruits: print(fruit)
The while loop executes the code block if the condition is met until the condition is not true. Here is a simple while loop example:
count = 0 while count < 5: print(count) count += 1
在 Python 中,函数是一种重要的代码组织方式,可以将一段逻辑相近的代码块封装起来,以便复用和维护。Python 内置了很多常用的函数,例如 print、len、range 等,同时也可以自定义函数。下面是一个简单的函数定义示例:
def add(a, b): """ 求两个数的和 """ return a + b
上述代码定义了一个名为 add 的函数,它接受两个参数 a 和 b,并返回它们的和。函数定义以 def 关键字开头,后面是函数名和参数列表。参数列表用圆括号括起来,多个参数之间用逗号分隔。函数体通常包含多个语句,可以使用 return 语句返回函数结果。
调用函数时,需要指定相应的参数。下面是一个简单的函数调用示例:
result = add(2, 3) print(result) # 输出 5
在 Python 中,函数可以有默认参数和可变参数。默认参数是指在函数定义时指定的参数默认值,调用函数时可以不指定该参数的值,如果没有指定,则使用默认值。可变参数是指函数接受任意个参数,包括 0 个或多个参数,这些参数被封装为一个元组或字典,并传递给函数。下面是一个带有默认参数和可变参数的函数示例:
def greeting(name, message='Hello', **kwargs): """ 打印问候语 """ print(f"{message}, {name}!") if kwargs: print("附加信息:") for key, value in kwargs.items(): print(f"{key}: {value}") greeting('Tom')# 输出 Hello, Tom! greeting('Jerry', 'Hi')# 输出 Hi, Jerry! greeting('Lucy', 'Good morning', age=18) # 输出 Good morning, Lucy! 附加信息: age: 18
上述代码定义了一个名为 greeting 的函数,它接受一个必需参数 name 和一个可选参数 message,默认值为 'Hello'。函数体首先打印问候语,然后如果有额外信息,则打印出来。
在调用 greeting 函数时,可以指定不同的参数。例如,第一个调用只指定了必需参数 name,第二个调用指定了必需参数 name 和可选参数 message,第三个调用指定了必需参数 name、可选参数 message,以及关键字参数 age。
本文对 Python 基本语法和数据类型、条件语句、循环语句和函数的使用进行了简单介绍,这些都是 Python 编程的基础知识。在实际编程中,还需要掌握更多的知识,例如文件操作、异常处理、面向对象编程等。希望读者能够在实践中不断深入学习 Python,成为一名优秀的Python 开发者。在学习过程中,建议读者多写代码,参考开源项目,多与社区成员交流,不断提高自己的编程技能和水平。
最后,祝小伙伴们学习愉快,愿你成为一名优秀的 Python 开发者!
The above is the detailed content of Detailed explanation of Python's basic syntax and data types. For more information, please follow other related articles on the PHP Chinese website!