Python快速入门(6)——for/if/while语句

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循环语法如下:

  1. 遍历数值列表并打印

    python 复制代码
    for i in range(10):
        print(i)
  2. 遍历字符串列表并打印

    python 复制代码
    strs = ["flower","flow","flight"]
    for s in strs:
        print(s)
  3. 遍历字符串列表与索引值,使用enumrate,可以指定start起始值

    python 复制代码
    strs = ["flower","flow","flight"]
    
    for i, s in enumerate(strs):
        print(i, s)
    
    for i, s in enumerate(strs, start=1):
        print(i, s)
  4. 使用切片选择数据

    python 复制代码
    strs = ["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中使用TrueFalse代表真和假,与常见的c/c++/java不同。Python 为了和自身的空值None(首字母大写)保持风格统一,选择了首字母大写的True/False

复制代码
print(True)
print(False)
print(None)

常用的条件判断符

  • 是否相等==
  • 是否不相等!=
  • 数值比较<>
  • 逻辑与:and,区别于java的&&
  • 逻辑或:or,区别于java的||
  • 是否包含/不包含,innot 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")
相关推荐
2301_7644413317 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
014-code17 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly20240617 小时前
组合模式(Composite Pattern)
开发语言
游乐码18 小时前
c#泛型约束
开发语言·c#
大连好光景18 小时前
PYG从入门到放弃
笔记·学习
Dontla18 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen18 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA18 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
铁东博客18 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui18 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip