Python 快速入门指南
文章目录
Python 是一种易于学习和使用的编程语言,广泛应用于数据分析、人工智能、网页开发等领域。以下是一些 Python 的基础知识点和示例代码,帮助您快速上手。
1. 基本输出
使用 print()
函数可以输出文本或变量的值。
print('hello world')
2. 注释
可以使用 #
来添加单行注释,使用三重引号 '''
或 """
来添加多行注释。
# 这是一个单行注释
'''
这是一个多行注释
'''
3. 条件判断
使用 if
语句来实现条件判断。
if False:
print('true')
else:
print('false') # 输出: false
4. 用户输入
使用 input()
函数获取用户输入。
print('hello who are you?')
you = input('please input your name: ')
print('hello ' + you)
5. 字符串操作
字符串是不可变的,可以进行切片和其他操作。
string = 'hello world'
print(string[0]) # 输出第一个字符: h
print(string[1:5]) # 从1到5: ell
print(string[-1]) # 倒着输出一个字符: d
print(string[::-1]) # 倒序输出: dlrow olleh
print(string.split(' ')) # 分割字符串: ['hello', 'world']
6. 数字类型转换
可以将字符串转换为整数。
num = 1
string = '1'
string = int(string)
print(string + num) # 输出: 2
7. 集合与列表
列表是可变的,可以进行添加、删除等操作。
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # 输出: [1, 2, 4, 5]
8. 元组
元组是不可变的,可以用于存储不同类型的元素。
my_tuple = (1, 2, 3)
print(my_tuple)
demo_tuple = ['abc', 76, 'ly', 898, 5.2]
print(demo_tuple[1:3]) # 输出: [76, 'ly']
9. 字典
字典是一个无序的键值对集合。
information = {
'name': 'liming',
'age': 24
}
print(information) # 输出: {'name': 'liming', 'age': 24}
print(information['name']) # 输出: liming
print(information['age']) # 输出: 24
10. 循环
使用 for
循环遍历集合。
sum = 0
for item in range(1, 101): # 1-100的循环
sum += item
print(sum) # 输出: 5050
11. 迭代器
可以使用 for
循环遍历列表中的元素。
my_list = [1, 2, 3]
for item in my_list:
print(item) # 输出: 1, 2, 3
12. 函数
定义和调用函数。
def print_hello():
print('hello')
print_hello() # 输出: hello
def print_hello_name(name):
print('hello ' + name)
print_hello_name('rediaz') # 输出: hello rediaz
def add(a, b):
return a + b
print(add(1, 2)) # 输出: 3
13. 随机数
使用 random
模块进行随机操作。
import random
x = [1, 2, 3]
random.shuffle(x) # 随机打乱列表
print(x) # 输出: 随机排列的列表
总结
以上代码片段涵盖了 Python 的基础语法和常用数据结构。这些知识点是学习 Python 的起点,深入了解后可以更好地应用于实际项目中。希望这篇指南能够帮助您顺利入门!