Python basics finishing - conditional/loop statement

1. Conditional Statements

basic statement

The Python programming language specifies that any non-zero and non-null (null) value is true, and 0 or null is false.

The if statement in Python programming is used to control the execution of the program. The basic form is:

if 条件判断:
    执行语句
else:
    执行语句

When the "judgment condition" is established (non-zero), the following statement is executed, and the execution content can be multiple lines, which are distinguished by indentation to indicate the same range.

Multiple conditional judgment statement

Since python does not support switch statements, multiple conditional judgments can only be implemented with elif. If the judgment requires multiple conditions to be judged at the same time, you can use or (or), which means that the judgment condition is successful when one of the two conditions is established. ; When using and (and), it means that the judgment condition is successful only when two conditions are met at the same time; else is an optional statement. When the content needs to be executed when the condition is not established, the relevant statement can be executed. When the judgment condition is multiple value, the following forms can be used.

if 条件语句:
    执行语句
elif 条件语句:
    执行语句
elif 条件语句:
    执行语句
...
else:
    执行语句

      When if has multiple conditions, parentheses can be used to distinguish the order of judgment. The judgments in parentheses are executed first. In addition, the priority of and and or is lower than the judgment symbols such as > (greater than) and < (less than) , that is, greater than and less than In the absence of parentheses, it will take precedence over and or.

#!/user/bin/python
# -*- coding: cp936 -*-
h=1.75
w=80.5
a=80.5/(1.75*1.75)
if a<18.5:
    print"过轻"
elif 18.5<a and a<25:
    print "正常"
elif 25<a and a<28:
    print "过重"
elif 28<a and a<32:
    print "肥胖"
else:
    print "严重肥胖"

#输出结果
>>> 
过重
    

simple statement group

    
v=100
if (v==10):print "变量v的值为:",v
print "cood bye"

 

Python compound boolean expression calculation adopts the short-circuit rule, that is, if the value of the whole expression has been calculated by the former part, the latter part is not calculated anymore.

a,b=0,1
if (a>0) and (b/a>2):
    print "youo got it"
else:
    print "game over"

a,b=0,1
if (a>0) or (b/a>2):
    print "you got it"
else:
    print "game over"
#一个简单的条件循环语句实现汉诺塔问题
def my_print(args):
    print args
def move(n,a,b,c):
    my_print((a,'--->',c)) if n== 1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))
    move (3,'a','b','c')

2. Loop Statement

(1) While loop statement

The while statement in Python programming is used to execute a program in a loop, that is, under a certain condition, execute a certain program in a loop to process the same task that needs to be processed repeatedly. Its basic form is:

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

The executed statement can be a single statement or a block of statements. The judgment condition can be any expression, and any non-zero or non-null (null) value is true; when the judgment condition is false, the loop ends.

The execution flow chart is as follows:

python_while_loop

Python while statement execution process

#!/user/bin/python
# -*- coding: cp936 -*-
list=[12,37,5,42,8,3]
n1=[]
n2=[]
n=0
while n<len(list):
    if (list[n]%2==0):
        n1.append(list[n])
    else:
        n2.append(list[n])
    n=n+1
print "n1列表内容:%s;n2列表内容:%s"%(n1,n2)

#输出结果

>>> 
n1列表内容:[12, 42, 8];n2列表内容:[37, 5, 3]
    

Usage of break and continue

The function of break is to terminate the loop when certain conditions are met; the function of continue is to stop the operation of the item that meets the conditions when certain conditions are met.

#打印偶数
i=1
while i<10:
    i+=1
    if i%2>0:
        continue
    print i
#打印出从1到10
i=1
while 1:
    print i
    i+=1
    if i>10:
        break

#输出结果

>>> 
2
4
6
8
10
1
2
3
4
5
6
7
8
9
10

loop using else statement

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
>>> 

simple statement group

i=input("please input number:")
while i<0:print "game over"
print i

#输出结果

>>> 
please input number:12
12

 

guess size game

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import random
s = int(random.uniform(1,10))
#print(s)
m = int(input('输入整数:'))
while m != s:
    if m > s:
        print('大了')
        m = int(input('输入整数:'))
    if m < s:
        print('小了')
        m = int(input('输入整数:'))
    if m == s:
        print('OK')
        break;

boxing games

import random
while 1:
    s=int(random.randint(1,3))
    if s==1:
        ind='石头'
    elif s==2:
        ind='剪子'
    elif s==3:
        ind='布'
    m=raw_input('输入 石头、剪子、布,输入"end"结束游戏:')
    blist=['石头','剪子','布']
    if (m not in blist) and (m=='end'):
        print "输入错误,请从新输入!"
    elif m==ind:
        print "电脑出了:"+ind+",平局!"
    elif (m=='石头' and ind=='剪刀') or (m=='剪刀' and ind=='布') or (m=='布' and ind=='石头'):
        print "你赢了"
    elif (m=='石头' and ind=='布') or (m=='布' and ind=='剪刀') or (m=='剪刀' and ind=='石头'):
        print '机器赢了'
 
    elif m=='end':
        break

Decimal to Binary

denum=input("输入十进制数:")
print denum,"(10)",
binnum=[]
#二进制数
while denum >0:
    binnum.append(str(denum%2))
    denum //= 2
print '='
while len(binnum)>0:
    import sys
    sys.stdout.write(binnum.pop())

(2) for loop statement

Python for loops can iterate over any sequence of items, such as a list or a string.

grammar:

The syntax of the for loop is as follows:

for iterating_var in sequence:
   statements(s)

Iterate through sequence index

fruits=['banana','apple','mango']
for index in range(len(fruits)):
    print '当前水果:',fruits[index]
print "game over"
for i,j in enumerate(fruits):
    print i,j

 

else statement

In python, for ... else means this, the statement in for is no different from the ordinary one, the statement in else will be executed when the loop is executed normally (that is, the for is not interrupted by breaking out of break), while ... The same goes for else.

for num in range(10,20):
    for i in range(2,num):
        if num%i==0:
            j=num
            print '%d 等于%d*%d'%(num,i,j)
            break
    else:
        print num,'是一个质数'

 

Bubble Sort

arays=[1,8,2,6,3,9,4]
for i in range(len(arays)):
    print len(arays)
    for j in range(i):
        if arays[i] <arays[j]:
            arays[i],arays[j]=arays[j],arays[i]
print arays

#输出结果

>>> 
7
7
7
7
7
7
7
[1, 2, 3, 4, 6, 8, 9]

 

(3) Loop nesting

Python for loop nesting syntax:

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python while loop nesting syntax:

while expression:
   while expression:
      statement(s)
   statement(s)

Prime numbers up to 100:

num=[]
i=2
for i in range(2,100):
    j=2
    for j in range(2,i):
        if (i%j==0):
            break
        else:
            num.append(i)
print num

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325459489&siteId=291194637