Python 初识基础
发布人:shili8
发布时间:2023-05-25 17:34
阅读次数:38
Python 是一种高级编程语言,它的语法简单易懂,适合初学者入门。本文将介绍 Python 的基础知识,包括变量、数据类型、运算符、条件语句、循环语句等。
1. 变量
在 Python 中,变量是用来存储数据的容器。变量名可以是任何有效的标识符,但不能以数字开头。变量的赋值使用等号(=)操作符。
示例代码:
# 定义变量 x = 5 y = Hello World! # 输出变量 print(x) print(y)
输出结果:
5 Hello World!
2. 数据类型
Python 中有多种数据类型,包括整数、浮点数、字符串、布尔值、列表、元组、字典等。可以使用 type() 函数来查看变量的数据类型。
示例代码:
# 整数 x = 5 print(type(x)) # 浮点数 y = 3.14 print(type(y)) # 字符串 z = Hello World! print(type(z)) # 布尔值 a = True print(type(a)) # 列表 b = [1 2 3 4 5] print(type(b)) # 元组 c = (1 2 3 4 5) print(type(c)) # 字典 d = { ame: Tom age: 18} print(type(d))
输出结果:
3. 运算符
Python 中有多种运算符,包括算术运算符、比较运算符、逻辑运算符等。下面是一些常用的运算符示例代码:
# 算术运算符 x = 5 y = 3 print(x + y) # 加法 print(x - y) # 减法 print(x * y) # 乘法 print(x / y) # 除法 print(x % y) # 取模 print(x ** y) # 幂运算 # 比较运算符 a = 5 b = 3 print(a == b) # 等于 print(a != b) # 不等于 print(a > b) # 大于 print(a < b) # 小于 print(a >= b) # 大于等于 print(a <= b) # 小于等于 # 逻辑运算符 m = True n = False print(m and n) # 与运算 print(m or n) # 或运算 print(not m) # 非运算
输出结果:
8 2 15 1.6666666666666667 2 125 False True True False True False False True False
4. 条件语句
条件语句用于根据条件执行不同的代码块。Python 中的条件语句包括 if 语句、if-else 语句、if-elif-else 语句等。
示例代码:
# if 语句 x = 5 if x > 0: print(x is positive) # if-else 语句 y = -3 if y > 0: print(y is positive) else: print(y is negative) # if-elif-else 语句 z = 0 if z > 0: print(z is positive) elif z < 0: print(z is negative) else: print(z is zero)
输出结果:
x is positive y is negative z is zero
5. 循环语句
循环语句用于重复执行一段代码。Python 中的循环语句包括 for 循环和 while 循环。
示例代码:
# for 循环 fruits = [apple banana cherry] for fruit in fruits: print(fruit) # while 循环 i = 1 while i <= 5: print(i) i += 1
输出结果:
apple banana cherry 1 2 3 4 5
以上就是 Python 的基础知识介绍,希望对初学者有所帮助。