python:if判断、循环结构和列表解析

>>> a='123456789'
>>> a[::-1]		//反向输出
'987654321'
>>> a[-1::-1]
'987654321'

if语句
标准if条件语句的语法
if expression
if_suite
else
else_suite
• 如果表达式的值非0或者为布尔值True, 则代码组
if_suite被执行;否则就去执行else_suite
• 代码组是一个python术语,它由一条或多条语句组
成,表示一个子代码块

• 扩展if语句结构

if expression1:
  if_suite
elif expression2:
  elif_suite
else:
  else_suite

练习01

#!/usr/local/bin/python3
default_username='root'
default_password='123456'
username=input('localhost login:')  #输入用户名
if username==default_username:  #判断用户名是否正确
   password=input('password:')  #用户名正确则输入密码
   if password==default_password:  #判断密码是否正确
      print('welcome ',username,'!')   #密码正确则输出欢迎
      exit
   else:
      print('password error!')     #密码错误则输出错误提示信息
      exit
else:
   print('username error!')        #用户名错误则输出错误提示信息
   exit

练习02
#!/usr/local/bin/python3
x = input('id:')
print( 'yes' if int(x) > 55 else "no")

练习03
#!/usr/local/bin/python3
num=input('grade:')
x=int(num)
if x > 90:
  print('优秀')
elif x > 80:
  print('好')
elif x > 70:
  print('良')
elif x > 60:
  print('及格')
else:
  print('你要努力了')
  exit

练习04
#!/usr/local/bin/python3
#石头剪刀布游戏
import random
alist = ['石头', '剪刀', '布']
x  = random.randint(0,2)
computer = alist[x]
print('''
 0:石头
 1:剪刀
 2:布
''')
y = input('guest number[0-2]')
y = int(y)
if y >= 0 and y <= 2:
   guest = alist[y]
   if guest == computer:
      print('平局!')
   elif guest== '石头' and computer == '剪刀':
      print('你赢了')
   elif guest== '石头' and computer == '布':
      print('你输了')
   elif guest== '剪刀' and computer == '石头':
      print('你输了')
   elif guest== '剪刀' and computer == '布':
      print('你赢了')
   elif guest== '布' and computer == '剪刀':
      print('你输了')
   elif guest== '布' and computer == '石头':
      print('你赢了')
else:
   print('你犯规了...')

简化版
#!/usr/local/bin/python3
#石头剪刀布游戏
import random
alist = ['石头', '剪刀', '布']
x  = random.randint(0,2)
blist = [(0,1), (1,2), (2,0)]
print('''
 0:石头
 1:剪刀
 2:布
''')
y = input('guest number[0-2]')
y = int(y)
if y >= 0 and y <= 2:
   res= '你赢了'if (y,x) in blist else '你输了'
   print(res)
else:
   print('你犯规了...')

循环结构
• 一组被重复执行的语句称之为循环体,能否继续重复,
决定循环的终止条件
• Python中的循环有while循环和for循环
• 循环次数未知的情况下,建议采用while循环
• 循环次数可以预知的情况下,建议采用for循环

while结构
while循环语法结构
• 当需要语句不断的重复执行时,可以使用while循环
while expression:
while_suite
• 语句while_suite会被连续不断的循环执行,直到表达
式的值变成0或False

练习01
#!/usr/local/bin/python3
#计算1—100以内所有整数的和
i,count = 1, 0
while i <= 100:
   count += i
   i += 1
print(count)

练习02
#!/usr/local/bin/python3
#计算1—100以内所有偶数的和
sum = 0
i = 0
while i <= 100:
  i+= 1
  if i % 2:
    continue
  sum += i
print('result is %d'%sum)

练习03
#!/usr/local/bin/python3
#计算1--100以内所有奇数的和
sum = 0
i = 0
while i <= 99:
  i+= 1
  if not i % 2:
    continue
  sum += i
print('result is %d'%sum)

练习03
#!/usr/local/bin/python3
default_username='root'
default_password='123456'
while True:  //判断永远为真,直到用户输入正确为止
 username=input('localhost login:')  #输入用户名
 password=input('password:')         #输入密码
 if username == default_username and password == default_password:  #判断用户名
和密码是否输入正确
    print('welcome', username, '!')  //正确则打印欢迎
    break  //结束循环
 else:
    print('输入错误!')  //否则提示输出错误

练习04
#!/usr/local/bin/python3
import random
a = random.randint(0,100)
num = 1
while num <= 5:
  user = input('请猜一个数:')
  b = int(user)
  if a == b:
     print('猜对了!')
     break
  else:
     num += 1
     print('猜错了,请重新猜!')
print('正确答案是', a)

练习05
#!/usr/local/bin/python3
#石头剪刀布游戏,三局两胜制
import random
gamelist= ['石头', '剪刀', '布']
winlist= [(0,2), (1,0), (2,1)]
xcount= 0
ycount= 0
while True:
  print('''
  0:石头
  1:剪刀
  2:布
  ''')
  x = random.randint(0,2)
  y = input('guest number[0-2]:')
  y = int(y)
  if y >= 0 and y <= 2:
    if x == y:
      print('平局', end= '\n\n')
      continue
    elif (x,y) in winlist:
      ycount += 1
    else:
      xcount += 1
    print('电脑:', gamelist[x],' ', '用户:', gamelist[y])
    if xcount == 2:
       print('你输了')
       break
    elif ycount == 2:
       print('你赢了')
       break
  else:
    print('你犯规了...')

for循环和range函数
• python中的for接受可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素
语法结构:
for iter_var in iterable:
suite_to_repeat
• 与while循环一样,支持break、continue、else语句
• 一般情况下,循环次数未知采用while循环,循环次数已知,采用for循环

range函数
• for循环常与range函数一起使用
• range函数提供循环条件
• range函数的完整语法为:
range(start, end, step =1)

练习01
#!/usr/local/bin/python3
#斐波那契数列就是某一个数,总是前两个数之和,比如0,1,1,2,3,5,8
#生成指定长度的斐波拉契数列
alist = [0, 1]
n = input('num: ')
n = int(n)-2
for i in range(n):
    x = alist[-1]+ alist[-2]
    alist.append(x)
print(alist)

练习02
#!/usr/local/bin/python3
#打印九九乘法表
for x in range(1, 10):
   for y in range(1, x+ 1):
     print(str(x)+'x'+str(y)+'=',x*y, end= '\t')
   else:
     print()	//print()函数自带换行

列表解析
它是一个非常有用、简单、而且灵活的工具,可以用来动态地创建列表
• 语法:
[expr for iter_var in iterable]
• 这个语句的核心是for循环,它迭代iterable对象的所有条目
• expr应用于序列的每个成员,最后的结果值是该表达式产生的列表

>>> alist= [1, 2, 3, 9]
>>> blist=[]
>>> for i in alist:
...    blist.append(i**2)
... 
>>> blist
[1, 4, 9, 81]
>>> [i**2 for i in alist]
[1, 4, 9, 81]
>>> alist=[1, 2, 3, 7]
>>> blist=[i**2 for i in alist]
>>> blist
[1, 4, 9, 49]
>>> [5+i for i in range(5)]
[5, 6, 7, 8, 9]
>>> [5+i for i in range(10) if i%2==0]
[5, 7, 9, 11, 13]
>>> ['192.168.1.'+ str(i) for i in range(255)]
['192.168.1.0', '192.168.1.1',..]

**************
>> True
True
>>> bool()
False
>>> bool(' ')
True

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值