本办法学python 32

for 循环

theCount = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in theCount:
    print("This is count %d" % number)
# same as above
for fruit in fruits:
    print("A fruit of type:%s" % fruit)
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
    print("I got %r" % i)
# we can also build lists,first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print("Adding %d to the list." % i)
    # append is a function that lists understand
    elements.append(i)
# now we can print them out too
for i in elements:
    print("Element was:%d" % i)

start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
range 用法

>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)  # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

打印runoob 的每个字符
注意字符也可以当做是列表

x = 'runoob'
for i in range(len(x)):
    print(x[i])
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print("Adding %d to the list." % i)
    # append is a function that lists understand
    elements.append(i)
# now we can print them out too
for i in elements:
    print("Element was:%d" % i)

译者前言 前言:笨办法更简单 习题 0: 准备工作 习题 1: 第一个程序 习题 2: 注释和井号 习题 3: 数字和数计算 习题 4: 变量(variable)和命名 习题 5: 更多的变量和打印 习题 6: 字符串(string)和文本 习题 7: 更多打印 习题 8: 打印,打印 习题 9: 打印,打印,打印 习题 10: 那是什么? 习题 11: 提问 习题 12: 提示别人 习题 13: 参数、解包、变量 习题 14: 提示和传递 习题 15: 读取文件 习题 16: 读写文件 习题 17: 更多文件操作 习题 18: 命名、变量、代码、函数 习题 19: 函数和变量 习题 20: 函数和文件 习题 21: 函数可以返回东西 习题 22: 到现在你到了哪些东西? 习题 23: 读代码 习题 24: 更多练习 习题 25: 更多更多的练习 习题 26: 恭喜你,现在可以考试了! 习题 27: 记住逻辑关系 习题 28: 布尔表达式练习 习题 29: 如果(if) 习题 30: Else 和 If 习题 31: 作出决定 习题 32: 循环和列表 习题 33: While 循环 习题 34: 访问列表的元素 习题 35: 分支和函数 习题 36: 设计和调试 习题 37: 复习各种符号 习题 38: 阅读代码 习题 39: 列表的操作 习题 40: 字典, 可爱的字典 习题 41: 来自 Percal 25 号行星的哥顿人(Gothons) 习题 42: 物以类聚 习题 43: 你来制作一个游戏 习题 44: 给你的游戏打分 习题 45: 对象、类、以及从属关系 习题 46: 一个项目骨架 练习 47: 自动化测试 习题 48: 更复杂的用户输入 习题 49: 创建句子 习题 50: 你的第一个网站 习题 51: 从浏览器中获取输入 习题 52: 创建你的 web 游戏 下一步 老程序员的建议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值