# Counter
# range(10)返回[0,9]的数列,可以理解为给rang()一个正数n,会返回一个[0,10)的序列
# 实际上 rang()函数只会在需要的时候才返回序列中的下一个数字
# 向前计数
print("Counting...")
for i in range(10) :
print(i, end = " ")
# rang(0, 50, 5), rang(起始点,结束点,计数单位),所以rang(0, 50, 5)会在[0, 50)中以5为计数单位返回序列[0,5,10,15,20,25...45]
# 以五为单位进行计数
print("\n\nCounting by fives")
for i in range(0, 50, 5) :
print(i, end = " ")
# rang(10, 0, -1)最后参数为-1,表示从起始点开始,通过每次加上-1的方式向结束点前进
# 向后计数
print("\n\nCounting backwards")
for i in range(10, 0, -1) :
print(i, end = " ")
print("\n\nPress the enter key to exit.\n")
输出结果:
字符串String
字符串是由多个字符组成的序列,是不可变的。
理解不可变性
序列分为两种:可变的(mutable)和不可变的(immutable)
可变(mutable)是说序列可以被修改
不可变(immutable)是说序列不可以被修改
举个例子:
一个字符串
word = "aggregate"
word[0] = 'c' #【だめ 达咩, 不行】,不可变性!!!
word = "congregate" # 这个是给word重新赋值为了"congregate",而不是把之前的字符串"aggregate"给修改了
import random
word = "austere"
print("The word is : ", word, "\n")
# 顺序访问
for i in word :
print(i)
'''
随机访问
random.randrange(low, high) 用于产生两个指定断点间的随机数
'''
# 创建两个端点
high = len(word) # 7
low = -len(word) # -7
# 创建一个能够执行10次的for循环
for i in range(10) :
# 生产随机数,作为索引
position = random.randrange(low, high)
# word[position]通过索引读取该位置的元素
print("word[", position ,"]\t",word[position])
print("\n\nPress the enter key to exit.\n")
执行结果:
"+" ,可以用于连接两个字符串,每用一次"+"连接符就创建一个新字符串
python复制代码
message = input("Enter a message: ")
new_message = ""
VOWELS = "aeiou"
print()
for letter in message :
if letter.lower() not in VOWELS :
new_message += letter
print("A new string has been created: ", new_message)
print("\n Your massage without vowels is : ", new_message)
# Hero's Inventory
# 演示元组的创建及使用
#创建一个空的元组
inventory = ()
# 把元组当做条件来用
# 只要元组中各有一个元素就是True
# 空元组就是False, not inventory 则为True
if not inventory :
print("You are empty-handed")
input("\nPress the entry key to continue.")
#创建一个带有一些内容的元组
inventory = ("sword",
"armor",
"sheield",
"healing poting")
# 打印元组
print("\nThe tuple inventory is : ")
print(inventory)
# 尝试修改元组,元组是不可变的,这行代码会报错
# inventory[0] = "battleax"
# 打印元组中的各个元素
for item in inventory :
print(item)
# 获取元组的长度
print("You have", len(inventory), "items in your possession.")
# 用in测试成员关系
if "healing potion" in inventory :
print("You will live to fight another day.")
# 使用索引,随机访问元素
# 通过索引显示元素
index = int(input("\nEnter the index number for an item in inventory: "))
print("At index", index, "is", inventory[index])
# 对元组进行切片
start = int(input("\nEnter the index number to begin a slice: "))
finish = int(input("\nEnter the index number to end the slice: "))
print("inventory[", start, ",", finish, "] is", end = " ")
print(inventory[start:finish])
# 连接两个元组
chest = ("gold", "gems")
print("\nYou find a chest. It contains: ")
print(chest)
print("You add the contents of the chest to you inventory.")
inventory += chest
print("Your inventory is now: ")
print(inventory)
input("\n\nPress the enter key to exit.")