目录
1、if语句
#if条件判断学习
people =20
cats = 30
dogs = 15
if people <cats:#条件判断人数数量是否小于猫,若小于,则执行if后面的语句(这个要输出)
print("Too many cats! The world is doomed")
if people>cats:#判断人的数量是否小于猫
print("Not many cats! The world is saved")
if people<dogs:#判断人的数量是否小于狗
print("The world is drooled on")
if people >dogs:#判断人的数量是大于狗 这个要输出
print("The world is dry")
dogs+=5#更新参数 目前dogs变成了20
if people>=dogs:#是等于的
print("People are greater than or equal to dogs")
if people<=dogs:
print("People are greater than or equal to dogs")
if people==dogs:
print("People are dogs.")
if 语句就是告诉脚本,如果布尔表达式是True,那就运行if语句下面的代码段,否则的话就跳过
同时python提供if搭配else,如果if语句表达式如果布尔值为假,则执行else后面的代码段
为什么if下面代码要缩进4个空格?
通过一行代码结尾的冒号告诉python你正在创造一个新的代码块,然后缩进4个空格告诉python这个代码块里面都有什么。
if True and True:
print('success')
if False:
print(0)#无任何输出
if True:
print(0)
#打印出0
2、if嵌套使用
#嵌套if语句
print("""You enyer a darker room with two doors.
Do you go through door #1 or door #2?""")#打印这个和语句
door = input('>')
if door == '1':
print("There's a giant bear here eating a cheese cake")
print("What do you do?")
print("1. Take the cake")
print("2 . Scream at the bear")
bear = input('>')
if bear == '1':
print("The bear eats your face off.Good job!")
elif bear =='2':
print("The bear eats your legs off.Good job!")
else:
print(f"Well ,doing {bear} is probably better")
print("Bear runs away")
elif door == '2':
print("You stare into the endless abyss at Cthulhu retina")
print("1.Blueberries")
print("2.Yellow jacket clothespins")
print("3. Understanding revolvers yelling melodies.")
insanity = input('>')
if insanity =='1' or insanity =='2':
print("Your body survives powered by a mind of jello.")
print("Good job")
else:
print("The insanity rots your eyes into a pool of muck")
print("Good job")
else:
print("You stumble around and fall on a knife an die.Good job")
x = int(input('>'))
if x== 1:
print('猜对了')
y = int(input('>'))
if y != 2:
print('恭喜通关')
这里注意input()函数:无论我们输入的值是int,float,还是string,最后input函数返回的这个数据的类型均为string,所以在上述代码中利用int()将字符串类型转化为整型。
3、for语句
#for 循环
import numpy as np
a= list(range(6))
for i in a:
print("i is {}".format(i))
#for循环遍历字典的用法
dic1 = {1:'xiaosun',2:'xiaoyang'}
for k,v in dic1.items():
print(k,v)
4、列表的操作
4.1 append和extend
#列表其他操作
lst = ['dahuang','xiaosun','xiaojia','xiaoyang','gaozige','xiaohu','laoxia']
lst.append({'xiaopi':'zhou'})
lst
#append在列表末尾添加对象,并保持原数据结构
lst = ['dahuang','xiaosun','xiaojia','xiaoyang','gaozige','xiaohu','laoxia']
lst.extend(['xiaohe','xiappeng'])
lst
append和extend的用法可以从上述代码中看到append是保持原有数据结构将整体添加在新的列表末尾,extend是将整体中元素一一一添加在新列表末尾。
lst = ['dahuang','xiaosun','xiaojia','xiaoyang','gaozige','xiaohu','laoxia']
lst.insert(2,'xiaoxun')
lst
#在编号2的位置插入xiaoxun
4.2 insert()
insert(index,obi)在index=?位置插入元素
x = ['Monday','tuesday','wednesday','thursday','Friday']
x.remove('Monday')
x
x = ['Monday','tuesday','Monday','thursday','Friday']
x.remove('Monday')
x
4.3 remove()
remove()---移除列表中某个值的第一个匹配项,例如第二个代码中当列表出现相同元素时,匹配这个元素第一次出现时就删除这个严肃(自己的理解)
#统计某个元素在列表中出现的次数
list1= [123,456]
list2 = list1*3
print(list2)
list2.count(123)
4.4 count()
*为列表重复操作符,count()统计元素出现的次数
list1= [123,456]
list2 = list1*3
list2.index(123,4,5)
4.5 list.index()
list.index(x,[start,end]):引用上述例子解释,寻找元素123在list2中索引值4-5的123元素匹配的索引位置,list2时list1重复3次,此时list2 = [123,456,123,456,123,456],所以此代码输出为4。(有错误请指出)
a= [454,78,78545,545,123]
a.sort(reverse = True)
a
#默认是升序,reverse = False是默认时候的状态
list.sort()对列表元素进行排序操作
range()函数只处理第一个到最后一个数,但是不包括最后一个数。
5、while语句
while-loop只要一个布尔表达式是True,while-loop就会一直执行它下面的代码块直到为假。
#while 循环
i= 0#初始化i的值
numbers = []#建立一个空列表,命名为numbers
while i<6:#循环开始,当i>=6时跳出while循环
print(f"At the top i is {i}")#{}依次赋值0,1,2,3,4,5,到6进不来循环,直接输出后面的print()
numbers.append(i)#将循环得到的i的值添加到空列表中【0,1,2,3,4,5】
i=i+1
print("Numbers now:",numbers)
print(f"At the bottom i is {i}")
print("The numbers:")
for num in numbers:#循环结束后number为0,1,2,3,4,5】
print(num)
如果在中间i的值不进行+1更新,就会陷入死循环
我们可以CTRL+C终止程序
6、分支和函数
练习
from sys import exit
def gold_room():#定义函数
print("This room is full of gold. How much do you take")#输出这句话
choice = int(input('>'))#用户输入转换为int型
if 0 in choice or 1 in choice:#条件判断0或1是否在choice中,在则执行下面语句
how_much = int(choice)#choice变成整型
else:
dead("Man ,learn to type a number")
if how_much<50:
print("Nice , You're not greedy,you win!")
exit(0)
else:
dead("You greedy bastard")#你这个贪婪的混蛋
def bear_room():#定义bear_room函数
print("哪里有个熊")
print("这个熊有一对蜂蜜")
print("肥熊实在另一扇门面前")
print("你将如何移动熊")
bear_moved = False
while True:#循环开始
choice = input(">")#提示用户输入
if choice == 'Take honey':#选择了Take honey直接退出游戏
dead("The bear looks at you then slaps yous face")
elif choice == 'taunt bear' and not bear_moved:#bear_moved本身是False,not bear_moved是True
print("The bear han moved from the door")
print("You can go through it now")
bear_moved = True
elif choice == 'taunt bear' and bear_moved:#若是输入了taunt bear,但是bear_moved本身在小循环里面设置为真,所以同时为真成立了
dead("The bear gets pissed off and chews your leg")
elif choice == 'open door' and bear_moved:#选了open door 但是bear_moved本身是真的的所以也成立
gold_room()
else:
print("I got no idea what that means")
def cthulhu_room():
print("Here you see the great evil cthulhu")
print("He,it,whatever stares at you and you go insnsane")
print("Do you flee for your life or eat your head")
choice = input(">")
if 'flee' in choice:#如果选择了flee就调用了stare函数
stare()
elif 'head' in choice:
dead("Well that tasty!")
else:
cthulhu_room()
def dead(why):
print(why,"Good job")#调用了这个函数相当于退出游戏
exit(0)
def stare():
print("You are in a room")
print("There is a door to your right and left")
print("Which one do you take?")
choice = input('>')
if choice == 'left':
bear_room()
elif choice == 'right':
cthulhu_room()
else:
dead("You stumble around the room until you starve")
stare()
#先运行stare函数
#输入left开始调用bear—room函数 输入right调用cthulhu_room()函数,输入不在两者之间,退出游戏,调用dead()函数
在这里可以使用while True 构建无限循环,自己的理解在这里作用是调用这个函数后就算出入错了也进入循环,输出else语句,不用来来回回输错了重新进行游戏。
参考链接