Python学习进程(5)Python语法

    本节介绍Python的基本语法格式:缩进、条件和循环

    (1)缩进:

    Python最具特色的是用缩进来标明成块的代码。

>>> temp=4;x=4;
>>> if(temp>0):
...   print(x+1);  #这里要进行缩进
...
5

    Python这样设计的理由纯粹是为了程序好看。

    (2)条件语句:

    Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。

    条件语句的书写方式:

if 判断条件:
    执行语句……
else:
    执行语句……
>>> firstPerson='欧阳明日';secondPerson='上官燕';thirdPerson='司马长风';
>>> a=True;b=False;
>>> if(a and b): #不加括号也是对的
...    print(firstPerson,'love',secondPerson);
... elif(a or b):
...   print(secondPerson,'love',thirdPerson);
... else:
...   print('game over');
...
上官燕 love 司马长风

    

    (3)for循环:

    for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

    for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)

    1)普通for循环

sunjimeng@SJM:~/文档$ cat text.py
for letter in 'Python':
  print('当前字母',letter);
fruits=['banana','apple','juice'];
for fruit in fruits:
  print('水果是:',fruit);
sunjimeng@SJM:~/文档$ python3.5 text.py
当前字母 P
当前字母 y
当前字母 t
当前字母 h
当前字母 o
当前字母 n
水果是: banana
水果是: apple
水果是: juice

    2)通过序列索引迭代:

sunjimeng@SJM:~/文档$ cat text.py
fruits=['banana','apple','juice'];
for index in range(len(fruits)):
  print('当前水果:',fruits[index]);
sunjimeng@SJM:~/文档$ python3.5 text.py
当前水果: banana
当前水果: apple
当前水果: juice

    3)循环使用else语句:

    for... else :

    for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

sunjimeng@SJM:~/文档$ cat t1.py
for num in range(10,20):
  for i in range(2,num):
    if(num%i==0):
      j=num/i;
      print(num,'等于',i,'*',j);
      break;
  else:
    print(num,'是一个质数'); 
sunjimeng@SJM:~/文档$ python3.5 t1.py
10 等于 2 * 5.0
11 是一个质数
12 等于 2 * 6.0
13 是一个质数
14 等于 2 * 7.0
15 等于 3 * 5.0
16 等于 2 * 8.0
17 是一个质数
18 等于 2 * 9.0
19 是一个质数

    (4)while循环:

    while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件:
    执行语句……

    1)普通while循环:

sunjimeng@SJM:~/文档$ cat text.py
count=10
while count>0:
  count=count-1
  print('当前数为:',count) 
sunjimeng@SJM:~/文档$ python3.5 text.py
当前数为: 9
当前数为: 8
当前数为: 7
当前数为: 6
当前数为: 5
当前数为: 4
当前数为: 3
当前数为: 2
当前数为: 1
当前数为: 0

    2)中断循环:

     continue 用于跳过该次循环,break 则是用于退出循环:

i=0
while i<10:
    i=i+1;
    if i%2==0:
        print(i)
k=0
while k<10:
    k=k+1
    if k%2==0:
        continue
    print(k)
2
4
6
8
10
1
3
5
7
9
sunjimeng@SJM:~/文档$ cat text1.py
ndex=10;
while ndex>0:
  ndex=ndex-1
  if ndex%5==0:
    break;
  print('当前数为:',ndex)
sunjimeng@SJM:~/文档$ python3.5 text1.py
当前数为: 9
当前数为: 8
当前数为: 7
当前数为: 6

    3)while...else语句:

程序代码:
count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")
结果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

 

原文地址:https://www.cnblogs.com/MenAngel/p/5682292.html