py教程第8讲-分支和循环之一

small = x if (x < y and x < z) else (y if y < z else z)

练习:

>>> x, y, z = 7, 6, 5
>>> small = x (if x < y and x < z) else (y if y < z else z) ##if不能再括号中。语法: a = b if () else (), 如果括号中还有一层,句式一样。
SyntaxError: invalid syntax
>>> small = x if( x < y and x < z) else (y if y < z else z)

>>> small
5

if语句

if expression:
  if_suite
如果表达式的值非0或者为布尔值True, 则代码组 if_suite 被执行; 否则就去执行下一条语句。

Python 还支持 elif (意指 “else-if ”)语句,语法如下:
if expression1:
  if_suite
elif expression2:
  elif_suite
else:
  else_suite

score = int(input('请输入分数:')) #输入成绩得分,输出得分等级
if 100 >= score >= 90:
  print('A')
elif 90 > score >= 80:
  print('B')
elif 80 > score >= 70:
  print('C')
elif 70 > score >= 60:
  print('D')
else:
  print('输入错误')

 

 

while循环:

while expression:
  while_suite

语句 while_suite 会被连续不断的循环执行, 直到表达式的值变成 0 或 False; 接着Python 会执行下一句代码。

>>> a = 0
>>> while a < 3:
    print ('loop #%d' % a)
    a += 1


loop #0
loop #1
loop #2
>>> while a < 3:
    print ('loop #%d' % a)
    a += 1


>>> a
3
>>> a = 0
>>> while a < 3:
    print ('loop #%d' % (a))
    a += 1


loop #0
loop #1
loop #2

 

 

for循环(Python 中的for 接受可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素

>>> for item in ['I ', 'love ', 'Python']:
     print item

SyntaxError: invalid syntax
>>> for item in ['I ', 'love ', 'Python']:
    print (item)


I
love
Python

>>> for item in ['I ', 'love ', 'Python']:
print (item, end=',')


I ,love ,Python,
>>> for item in ['I ', 'love ', 'Python']:
print (item, end='')


I love Python

 

>>> who = 'knights'
>>> what = 'Ni!'
>>> print('We are the', who, 'who say', what, what, what, what)
We are the knights who say Ni! Ni! Ni! Ni!
>>> print('We are the %s who say %s % (who, what*4)) ###新手常犯错误之一:在字符串首尾忘记加引号(导致“SyntaxError: EOL while scanning string literal”)

SyntaxError: EOL while scanning string literal
>>> print('We are the %s who say %s' % (who, what*4))
We are the knights who say Ni!Ni!Ni!Ni!

range()函数经常和len()函数一起用于字符串索引。

>>> b = 'China'
>>> for a in range(len(b)):
    print(b[a], %d % a)

SyntaxError: invalid syntax
>>> for a in range(len(b)):
    print((b[a], %d )% a)

SyntaxError: invalid syntax
>>> for a in range(len(b)):
    print(b[a], '%d' % a)


C 0
h 1
i 2
n 3
a 4
>>> for a in range(len(b)):
print(b[a], '(%d)' % a)


C (0)
h (1)
i (2)
n (3)
a (4)

 列表解析:表示你可以在一行中使用一个for 循环将所有值放到一个列表当中。

>>> list2 = [x**2 for x in range(len(b))]
>>> list2
[0, 1, 4, 9, 16]

assert的作用:

当其右边条件为假的时候,程序自动崩溃并抛出AssertionError的异常。

 

posted @ 2016-11-18 10:51  月光边境Eric  阅读(263)  评论(0编辑  收藏  举报