[Day4]python集训

[Day4]
1.判断语句(if-elif语句)
编程时经常需要检查一系列条件,并据此决定采取什么措施。在Python中,if 语句让你能够检查程序的当前状态,并据此采取相应的措施。
1.1 判别元素是否在列表中

nums=[1,2,3,4,5,6]
if 1 in nums:
   print('1 is in nums')
else:
 print('1 is not in nums')
 #输出结果
 1 is in nums

1.2 判等

student_name='david'
if student_name == 'david'
   print('He is from America.')
elif  student_name !='david':
   print('He is from China.')
#输出结果:
He is from America.

1.3 检查多个条件
示例1:在现实世界中,很多情况下需要考虑的情形都超过两个。例如,来看一个根据年龄段收费的游乐场:4岁以下免费; 4~18岁收费5美元; 18岁(含)以上收费10美元。

age=int(input('please enter your age:'))
if  0<=age<=4:
   print('free  ticket')
elif  4<=age<=18:
   print('you need to pay 5 dollars.')
elif   age>=18:
   print('you need to pay 10 dollars.')
#输出结果:
please enter your age:12
you need to pay 5 dollars.

示例2:成绩评级系列:90-100为A,75-89为B,60-74为C,60以下为D

score=int(input('please enter your score:'))
if 90<=score<=100:
    print('Degree A')
elif 75<=score<=89:
    print('Degree B')
elif 60<=score<=74:
    print('Degree C')
elif score<60:
    print('Degree D')
elseprint('wrong score,please enter again.')
#输出结果
please enter your score:34
Degree D

1.4 if语句的嵌套
示例:火车票安检系统:如果有票则允许进行安检,无票则提示要先买票。随后检查刀具长度,如果刀的长度小于20则安检通过,如果刀的长度大于20则不允许经过安检。

has_ticket=input('Do you has a ticket?yes/no')
if has_ticket=='yes':
    print('you can go to check.')
    knife_length=int(input('please enter the length of your knife:')) 
    if knife_length<20:
        print("have a good journey!")
    else:
        print('your knife is too long!')
elif has_ticket=='no':
    print('you need buy the ticket first.')
#输出结果1
Do you has a ticket?yes/noyes
you can go to check.
please enter the length of your knife:22
your knife is too long!
#输出结果2
Do you has a ticket?yes/nono
you need buy the ticket first.

1.5 if语句对列表的操作
1.5.1 检查特殊元素
示例:学生点名系统:检查学生是否到达,其中Mike缺席,其余同学到达。

student_name=['David','Mike','Lucy','Johnson']
for name in student_name:
     if  name == 'Mike':
        print('Mike is not here.')
     else:
        print(name+' is here')
#输出结果
David is here
Mike is not here.
Lucy is here
Johnson is here

1.5.2 检查列表是否为空列表
示例:检查是否有学生到达

student_name=[]
if student_name:
   for name in student_name:
       print(name+"is here.")
else:
   print('nobody is here.')
#输出结果
nobody is here.

1.5.3 操作多个列表—检查两个列表是否存在元素重复现象
示例:学生点名系统,对照学生名单进行检查,输出没有到达的同学姓名。

whole_student=['Mike','David','Lucy','James','Johnson','Danny']
present_student=['Mike','Lucy','David','Danny']
for name in whole_student:
    if name in present_student:
       print(name+' is here.')
    else:
       print(name+' is not here.')
#输出结果:
Mike is here.
David is here.
Lucy is here.
James is not here.
Johnson is not here.
Danny is here. 

2.循环语句
2.1 while循环
while 条件
满足时···
计数器规则
中断一次循环,下次继续:continue
中断一个循环:break
示例1:用while实现0-100累加

result=0
i=0
while i<=100:
   result+=i
   i+=1
print(result)
#输出结果
5050

示例2:向屏幕打印*,每行*的个数与行数保持一致

row=1
while row<=5:
       print('*'*row)
       row+=1
#输出结果
*
**
***
****
*****

示例3:体会break和continue的区别

i=0
while i<10:
  i+=1
  if i==5:
     continue      #跳过i=5时的循环,下次继续
  print(i)
  #输出结果
1
2
3
4
6
7
8
9
10
i=0
while i<10:
  i+=1
  if i==5:       
     break   #当i=5时跳出整个循环
  print(i)
 输出结果:
1
2
3
4 

3.三目运算符
判段的条件?条件为真时的结果:条件为假时的结果

#返回两个数中的较大者
x=int(input('please enter the first num:'))
y=int(input('please enter the second num:'))
print(x if(x>y) else y)
#输出结果:
please enter the first num:33
please enter the second num:11
33
#返回三个数中的较大者
x=int(input('please enter the first num:'))
y=int(input('please enter the second num:'))
z=int(input('please enter the third num:'))
a=(x if (x>y) else y)  # a为中间变量
print(a if (a > z) else z)
#输出结果为:
please enter the first num:11
please enter the second num:22
please enter the third num:33
33

4.容器:Python中常见的数据结构可以统称为容器。如列表、元祖、字典等。
5.可迭代对象:
迭代是访问集合元素的⼀种⽅式。迭代器是⼀个可以记住遍历的位置的对象。迭代器对象从集合的第⼀个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
我们已经知道可以对list、tuple、str等类型的数据使⽤for…in…的循环语法从
其中依次拿到数据进⾏使⽤,我们把这样的过程称为遍历,也叫迭代。
我们把可以通过for…in…这类语句迭代读取⼀条数据供我们使⽤的对象称之为可迭代对象(Iterable)。
怎么判断一个对象是否是可迭代的对象呢?可以用collections模块里面的iterable包的isinstance函数进行判断:

from collections.abc import Iterable
print(isinstance('abc',Iterable))  #字符串是可迭代对象
print(isinstance([1,2,3],Iterable)) #列表是可迭代对象
print(isinstance((1,2,3),Iterable)) #元祖是可迭代对象
#输出结果
True
True
True

6.生成器
通过列表生成式,我们可以直接创建一个列表,但是,受到内存限制,列表容量肯定是有限的,而且创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间,在Python中,这种一边循环一边计算的机制,称为生成器:generator。
生成器是一个特殊的程序,可以被用作控制循环的迭代行为,python中生成器是迭代器的一种,使用yield返回值函数,每次调用yield会暂停,而可以使用next()函数和send()函数恢复生成器。
只有把一个列表生成式的[]中括号改为()小括号,就创建一个generator

lis = [x*x for x in range(10)]   #用列表生成一组数列
print(lis)
#输出结果
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

7.迭代器
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器。生成器都是Iterator对象,但list、dict、str虽然是Iterable(可迭代对象),却不是Iterator(迭代器)。

from collections.abc import Iterator
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterator))
print((isinstance('abc',Iterator))
#输出结果
True
False
False

作业:
请对方输入一个0-9之间的数字,进行检查,若不是数字提示:您输入的不是数字,请输入0-9间的数字,若数字不在0-9范围内,提示用户输入0-9之间的数字,直至用户输入正确。
系统随机生成一个长度为3的数字列表,且列表中元素在0-9之间并且不相等。将用户输入与该列表进行比较,若为列表第一个元素,则荣获第一名,列表第二个元素,则荣获第二名,列表第三个名字,则荣获第三名,否则提示用户未得奖,输入1重新开始游戏,输入2则结束游戏。
注意:每次游戏中列表中数字要求随机生成,每轮游戏都不相等。

import random
while True:
 num=int(input('please enter your num:'))
 if 0<=num<=9:
    list1=[0,1,2,3,4,5,6,7,8,9]
    a=random.sample(list1,3)
    if num==a[0]:
       print('一等奖')
    elif num==a[1]:
        print('二等奖')
    elif num==a[2]:
        print('三等奖')
    else:
        print('未中奖')
 else:
    print('请输入0-9之间的数字')
 print('Do you want try it again? 1-yes,2-no')
 result=int(input('make you choice:'))
 if result==1:
     continue
 else:
     break
 输出结果:
please enter your num:1
未中奖
Do you want try it again? 1-yes,2-no
make you choice:1
please enter your num:2
未中奖
Do you want try it again?1-yes,2-no
make you choice:2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值