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")
相关推荐
孟健4 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞6 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽8 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程13 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪13 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook13 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python