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")
相关推荐
郝学胜-神的一滴3 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
m0_736919105 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手5 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
Gain_chance5 小时前
34-学习笔记尚硅谷数仓搭建-DWS层最近一日汇总表建表语句汇总
数据仓库·hive·笔记·学习·datagrip
helloworldandy5 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖5 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
Gain_chance6 小时前
36-学习笔记尚硅谷数仓搭建-DWS层数据装载脚本
大数据·数据仓库·笔记·学习