Python快速入门(6)------for/if/while语句
Python的运算
基本运算符
除了数字支持基本运算符外,python支持幂乘(**),python的字符串、列表、元组都支持加法 与乘法。加法为添加元素,乘法为重复。
python
# 2^3次方=8
print(2**3)
str_content = "This is a string"
# 加法 This is a string.
print(str_content + ".")
# 乘法 This is a stringThis is a string
print(str_content * 2)
triple = (1, 2, 3, 4, 5)
# 加法 (1, 2, 3, 4, 5, 6, 7)
print(triple + (6, 7))
# 乘法 (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
print(triple * 2)
list_str = [1, 2, 3, 4, 5]
# 加法 [1, 2, 3, 4, 5, 6, 7]
print(list_str + [6, 7])
# 乘法 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
print(list_str * 2)
常用数学运算
python支持range()生成数值列表,并支持min、max、sum等常见操作
python
# 生成有序数值列表 1, 3, 5, 7, 9
nums = range(1,10,2)
# 最大值9,最小值1
print(min(nums))
print(max(nums))
# 求和 25
print(sum(nums))
For循环
python的for循环语法如下:
-
遍历数值列表并打印
pythonfor i in range(10): print(i) -
遍历字符串列表并打印
pythonstrs = ["flower","flow","flight"] for s in strs: print(s) -
遍历字符串列表与索引值,使用enumrate,可以指定start起始值
pythonstrs = ["flower","flow","flight"] for i, s in enumerate(strs): print(i, s) for i, s in enumerate(strs, start=1): print(i, s) -
使用切片选择数据
pythonstrs = ["flower","flow","flight", "for"] for s in strs[::2]: print(s)
If条件
if语言使用if...elif...else
python
strs = ["flower","flow","flight", "for"]
for s in strs :
if s == "flight":
print("flight")
elif s == "for":
print("for")
else:
print("")
python中使用True和False代表真和假,与常见的c/c++/java不同。Python 为了和自身的空值None(首字母大写)保持风格统一,选择了首字母大写的True/False
print(True)
print(False)
print(None)
常用的条件判断符
- 是否相等
== - 是否不相等
!= - 数值比较
<、> - 逻辑与:
and,区别于java的&& - 逻辑或:
or,区别于java的|| - 是否包含/不包含,
in,not in,类似于java中的List.contains()
python
print(1 == 1)
print(1 != 2)
print(1 < 2)
print(1 > -1)
print(1 > -1 and 1 < 2)
print(1 < -1 or 1 > 2)
print(1 in range(5))
print(-1 in range(5))
print(-1 not in range(5))
列表元素判空
python
if [] :
print("not empty list")
else:
print("empty list")
While循环
while循环的语法为
python
while True:
print("1")
使用while循环配合in删除指定元素
python
strs = ["flower","flow","flight", "for"]
while "flight" in strs:
strs.remove("flight")