Python conditions cycle

Bowen outline:

  • A, Python condition determination
  • Two, Python cycle
  • Third, the control loop
  • Four, Python loop comprehensive example

A, Python condition determination

Python is an if statement with a conditional statement, if a double branch, if multiple branch statement, and their implementation in the shell if statement exactly the same, but some differences in syntax, as follows (all described in the flowchart of the if statement are executed with reference shell in):

Note: In Python, on the code indentation there are strict requirements, Python is the use of spaces to indent way represents a set of statements, usually indicates a set of statements (by default there will be four spaces to indent) with four spaces, so that we reduce the workload of code when writing code.

1, single-branch if statement:

Implementation process:

Python conditions cycle

Single-branch if statement example:

money = 1000      #首先定义一个变量
if (money > 500):     #测试条件是:如果money变量大于500,则条件成立,输出下面的内容
    print '吃大餐'      #输出的内容为吃大餐,该print语句就是if中的代码块,默认print前面有4个空格

2, two-branch if statement:

Implementation process:

Python conditions cycle

Two-branch if statement example:

money = 1000
if (money < 500):
    print '吃大餐'
else:
    print '吃土'

3, multi-branch if statement:

Implementation process:
Python conditions cycle

Multi-branch if statement example:

print '你还有多少钱?'         #输出提示信息
money = input()     #定义一个变量,变量值是接受键盘输入的值。
if (money > 500):    #如果变量值大于500,则输出“吃大餐”
    print '吃大餐'
elif (money > 100):   #如果变量值大于100,则输出“吃盖饭”
    print '吃盖饭'
else:            #如果前面两个条件都不成立,则输出“吃土”
    print '吃土'

4, using the if statement common problems:

Question (1): When using the if-elif-else statements, logical error prone, because that's down from the judge, if the condition is true, then the following conditional judgment is not carried out, just take for example, If the following code is written like this:

print '你还有多少钱?'         #输出提示信息
money = input()     #定义一个变量,变量值是接受键盘输入的值。
if (money > 100):    #如果变量值大于500,则输出“吃大餐”
    print '吃大餐'
elif (money > 500):   #如果变量值大于100,则输出“吃盖饭”
    print '吃盖饭'
else:            #如果前面两个条件都不成立,则输出“吃土”
    print '吃土'

You can be seen what will happen? Problem is that as long as you enter a value greater than 100, then it will output "eat rice bowl", even if you enter 800, it will not output, "fancy meal", because the first test condition was set up, complete execution after the first code block, the program directly out of this if-elif-else statement is not executed later.

Questions (2): IF statement is not indented block of statements is likely to commit an error, the following code will direct the compiler error:

money = 1000      #首先定义一个变量
if (money > 500):    
 print '吃大餐'    #这一行语句没有代码块,程序必定会报错,不能正常运行

But also to guarantee the same level of consistent statements indented spaces, even if only a space of difference, they have expressed a different block of statements, the error model is as follows:

money = 1000      #首先定义一个变量
if (money > 500):    
    print '吃大餐' 
         print '吃大餐'     #多了一个空格

Question (3): For the use of other languages turn Python friends, because the habit will often forget the back of the conditional test colon (feeling was talking about myself), you need a lot of attention.

Two, Python cycle

Often need to repeat the code is running programming, Python provides for a while and circulation.

1, while circulation

while loop may be determined according to the conditions, determining whether to perform loop statement block syntax is as follows:

while 循环语句:
    循环操作语句

while语句的执行流程如下:
循环条件后面也要使用冒号,然后缩进写循环操作语句,先判断条件是否成立,如果为True,则执行循环操作语句,如果为False,则跳出循环

i = 1            #定义一个变量
sum = 0      #定义一个变量
while i <= 3:       #测试条件是变量“i”小于或等于3,则执行下面循环体中的语句
    print ('请输入第%d个月的工资:' %i)            #等待键盘输入工资,并赋值给变量“i”
    sum = sum + int(input())       #将上面键盘输入的工资数和变量sum相加,并在赋值给变量sum
    i = i + 1  #执行一次变量“i”的值就+1。
#执行至此,然后返回去再进行判断,变量“i”是否小于或等于3,如果是,则再执行一遍循环语句;
#如果不是,则跳出循环,执行下面的语句
#注意,以下都没有缩进了,已经不属于while循环了
month = i - 1      #当循环条件不成立时,“i”的值都已经为4了,所以这里要减去1,并赋值给变量month
avg = sum / month       #把3个月的工资总和除以月份,就是平均工资
print ('近%d个月的平均工资是%d' %(month,avg))             #输出平均工资信息
#在上面的输出语句中,“%d”表示将后面的%(month,avg)这两个变量的值,依次赋值给语句中的两个“%d”

执行的结果如下:

请输入第1个月的工资:             #手动依次输入进三个月的工资
11000
请输入第2个月的工资:
12000
请输入第3个月的工资:
13000
近3个月的平均工资是12000      #最后的输出结果,OK!没问题。

字符串的格式化输出介绍

在上面的脚本中,使用了字符串的格式化输出,就是“%d”,字符串的格式化是将若干值插入带有“%”替代符的字符串中,从而可以动态地输出字符串,在上面的Python脚本中,字符串中的“%d”表示插入的是一个整型数据,字符串后面的“%i”表示取的是变量“i”的值。

字符串格式化中可以使用的替代符除了“%d”,还有其他替代符,如下:

Python conditions cycle

上面三种替换符的使用情况:
(1)每行字符串中单个替代符的使用:

#脚本如下:
num = 5
numstr = "五"
numF = 5.55
print ("第%d名"%num)
print ("第%s名"%numstr)
print ("第%f名"%numF)
#执行结果如下:
第5名
第五名
第5.550000名

(2)字符串中还可以使用多个替代符,对应的变量使用元组即可,示例如下:

#脚本如下:
first = 1
second = 2
print ("第%d名和第%d名"%(first,second))
#执行结果如下:
第1名和第2名

使用多个替代符时,注意顺序不要放错,否则可能会出现类型不匹配的问题。

(3)还可以使用字典格式化多个值,如下:

#代码如下:
num = {"first":1,"second":2}             #定义一个字典
print ( "第%(second)d名和第%(first)d名"%num )
#执行结果如下:
第2名和第1名

在上面代码中,因为字典是无序的,所以使用字典时需要把键指出来,明确哪个位置要用到哪个键值。

while循环的嵌套使用

while循环可以嵌套使用,示例代码如下:

#代码如下:
j = 1
prompt = '请输入员工姓名:'
while j <= 2:
    sum = 0
    i = 1
    name = raw_input(prompt)
    while i <= 3:
        print '请输入第%d月的工资:' %i
        sum = sum +input()
        i = i + 1
    i = i - 1
    avg = sum / i
    print '%s的近%d个月的平均工资是:%d' %(name,i,avg)
#执行结果如下:
请输入员工姓名:张三
请输入第1月的工资:
11000
请输入第2月的工资:
12000
请输入第3月的工资:
13000
张三的近3个月的平均工资是:12000
请输入员工姓名:李四
请输入第1月的工资:
7000
请输入第2月的工资:
8000
请输入第3月的工资:
9000
李四的近3个月的平均工资是:8000
员工平均工资计算完成!

在上面的代码中,外层循环(第一个while语句)用于输入员工姓名,用变量j控制循环的次数,共2次;内层循环(第二个while语句)用于输入近三个月的工资,用变量i控制,也就是在外层循环输入一个名字后,需要输入3次月工资,然后输出这个员工的平均工资,一共可以输入两个员工。第四行的代码放在了外层循环,是对sum变量做了清零,是因为每次输入一个人的近三个月的成绩后,sum都需要清零处理,以便计算下一个人的工资。如果不这样,之前的sum值就会保存,程序就无法达到预期的目的。

2、for循环

for循环是另一种用于控制循环的方式,while是使用条件判断执行循环,而for是使用遍历元素的方式进行循环。

(1)for循环的几种方式

for的语法结构如下:

for  变量 in 集合:
    语句块

常用的有以下几种使用方式:

1)for循环可以对字符串进行遍历,逐个获得字符串的每个字符,示例如下:

#代码如下:
for letter in 'Python':
    print 'Current letter:%s' %letter
#执行结果如下:
Current letter:P
Current letter:y
Current letter:t
Current letter:h
Current letter:o
Current letter:n

上面的代码中“for letter in 'Python' :”的作用是对“Python”字符串的字符逐个遍历,把字符赋值给变量letter,然后执行for对应的语句块,直到字符串取值完毕。看执行结果就知道怎么回事咯,这里就不啰嗦了。

2)for循环可以对列表和元组进行遍历,如下:

#代码如下:
Python = ['西瓜','苹果','香蕉']
for letter in Python:
    print letter
#执行结果如下:
西瓜
苹果
香蕉

语句“for letter in Python:”的作用就是遍历列表中的元素,把元素赋值给letter,输出语句每次输出一个水果。

3)需要循环操作的内容相同时,可以用for循环结合range()函数使用,如下:

#代码如下:
for i in range(0,5):
    print '每天进步一点点。'
#执行结果如下:
每天进步一点点。
每天进步一点点。
每天进步一点点。
每天进步一点点。
每天进步一点点。

range(0,5)输出的是一个列表,由第一个参数0开始,默认每次加1,当大于或等于第二个参数时结束,所以列表中不包括第二个参数值。range()函数中还可以写入第三个参数,如:range(0,5,2),意思是每次加2,最后的列表值是“[0,2,4]”,所以range()函数的作用是创建一个数字列表,取值范围是从起始数字开始到结束数字之前的内容。for循环可以对列表进行遍历,所以可以针对range()函数的结果进行遍历。

4)for循环示例:

#代码如下:
subjects = ('python','mysql','linux')
sum = 0
for i in subjects:
    print '请输入%s的测试成绩:' %i
    score = input()
    sum +=score                  # 与sum = sum+score效果一样
avg = sum / len(subjects)
print '张三的平均测试成绩为%d' %avg
#执行结果如下:
请输入python的测试成绩:
80
请输入mysql的测试成绩:
90
请输入linux的测试成绩:
100
张三的平均测试成绩为90

上面代码的作用是接收3门课程的成绩,计算输出平均成绩,使用for循环遍历测试列表subjects,接受测试成绩后使用sum累加,最后输出平均成绩。

5)for循环嵌套举例

#代码如下:
staffs = ['张三','李四']
months = ['1','3','5']
for staff in staffs:
    sum = 0
    for month in months:
        print '请输入%s的第%s个月的工资:' %(staff,month)
        sum = sum + input()
    avg = sum / len(months)
    print '%s的平均工资是%d' %(staff,avg)
#执行结果如下:
请输入张三的第1个月的工资:
11000
请输入张三的第3个月的工资:
12000
请输入张三的第5个月的工资:
13000
张三的平均工资是12000
请输入李四的第1个月的工资:
21000
请输入李四的第3个月的工资:
22000
请输入李四的第5个月的工资:
23000
李四的平均工资是22000

上面代码中,第一次循环对员工姓名进行了遍历,第二层循环对所指定的月份进行了遍历。

6)任何语言中都有逻辑表达式,它是用逻辑运算符和变量连接起来的表达式,逻辑运算符如下所示:

Python conditions cycle

逻辑运算符的使用举例:

举例1:

>>> print (not True)
False
>>> print (True and False)
False
>>> print (True or False)
True

举例2:

>>> score = 180
>>> if (score < 0 or score > 100):   #如果score小于0或大于100,那么就为真
    print '成绩错误,不能小于0或大于100'

成绩错误,不能小于0或大于100
>>> if (not (score > 0 and score < 100)):     #如果score不大于0并且不小于100,那么就为真。
    print '成绩错误,不能小于0或大于100'

成绩错误,不能小于0或大于100

三、循环的控制

When do while and for loop operations, sometimes need to change the normal execution of the order cycle, then you need to use to achieve cycle control statements, loop control statements have break and continue.

1, break (interrupt)

When the statement block cycle break statement has to be out of the entire cycle, corresponding to the shell of the exit. Examples are as follows:

#代码如下:
staffs = ['张三','李四']
months = ['1','3','5']
for staff in staffs:
    sum = 0
    for month in months:
        print '请输入%s的第%s个月的工资:' %(staff,month)
        score = input()
        if (score < 0 or score > 50000):   
            print '输入的工资要大于0或者小于50000,循环退出'
            break;     # break语句,跳出这个循环
        sum += score
    avg = sum / len(months)
    print '%s的平均工资是%d' %(staff,avg)
#执行结果如下:
请输入张三的第1个月的工资:
50001             #输入了一个比50000大的数字
输入的工资要大于0或者小于50000,循环退出
张三的平均工资是0
请输入李四的第1个月的工资:

2, continue (continue)

The difference between the break and continue in that: it is not the end of the whole cycle continue, but skip the current round of the loop remaining statements, the test cycle reset state, ready to enter the next cycle, as follows:

#代码如下:
staffs = ['张三','李四']
months = ['1','3','5']
for staff in staffs:
    sum = 0
    i = 0
    while (i < len(months)):
        print '请输入%s的第%s个月的工资:' %(staff,months[i])
        score = input()
        if (score < 0 or score > 50000):
            print '输入的工资要大于0或者小于50000,请重新输入。'
            continue;
        sum += score
        i += 1
    avg = sum / len(months)
    print '%s的平均工资是%d' %(staff,avg)
#执行结果如下:
请输入张三的第1个月的工资:
50001
输入的工资要大于0或者小于50000,请重新输入。
请输入张三的第1个月的工资:
30000
请输入张三的第3个月的工资:
25000
请输入张三的第5个月的工资:
60000
输入的工资要大于0或者小于50000,请重新输入。
请输入张三的第5个月的工资:
20000
张三的平均工资是25000
请输入李四的第1个月的工资:

In the above code, the first layer loop through recycling for employees, while the second layer using a while loop to loop through the month, continue to use that to jump to the next round of the nearest cycle, which is the second layer, while if after the test if the condition is not satisfied, then execute continue, code "i + = 1", and did not execute, execute it again while loop, so the same month when called again to re-enter. In this way, more humane.

Four, Python loop comprehensive example

Examples requirements are as follows:

  • Menu display operation, there are three options, represented by the letters N, E, Q represents;
  • N represents the input new user name and password;
  • E represents a user name and password;
  • Q to Quit program.

1, the full script as follows:

#代码如下:
kgc = {}
prompt = '''
    (N) ew user login
    (E) ntering user login
    (Q)uit
Enter choice:'''
while True:
    choice = raw_input(prompt).strip()[0].lower()
    print '\n--You picked : [%s]' %choice
    if choice not in 'neq':
        print '--invalid option,try again--'
    else:
        if choice=='n':
            prompt1 = 'login desired:'
            while True:
                name = raw_input(prompt1)
                if(kgc.has_key(name)):
                    prompt1 = '--name taken,try another:'
                    continue
                else:
                    pwd = raw_input('password:')
                    kgc[name] = pwd
                    break
        elif choice =='e':
            name = raw_input('login:')
            pwd = raw_input('password:')
            password = kgc.get(name)
            if password == pwd:
                print '--welcome back--',name
            else:
                print '--login incorrect--'
        else:
            print 'quit'
            break
#执行结果如下:

    (N) ew user login
    (E) ntering user login
    (Q)uit
Enter choice:N

--You picked : [n]
login desired:张三
password:123

    (N) ew user login
    (E) ntering user login
    (Q)uit
Enter choice:e

--You picked : [e]
login:张三
password:123
--welcome back-- 张三

    (N) ew user login
    (E) ntering user login
    (Q)uit
Enter choice:q

--You picked : [q]
quit
>>> 

2, explain the role and meaning of the code:

kgc = {}             #首先定义一个空字典,用于存放新建的用户及密码
prompt = '''                #这是一段提示信息,三引号表示若需要输入多行内容时使用。
    (N) ew user login
    (E) ntering user login
    (Q)uit
Enter choice:'''
while True:                  #条件是永远为真
    choice = raw_input(prompt).strip()[0].lower()  
#上面一段是等待键盘输入的字符串(n、q、e),strip()函数去掉字符串前后的空格,然后取第一个字符。
#函数lower()的作用是将字符变成小写字母,为后面的条件判断做准备
    print '\n--You picked : [%s]' %choice    #换行输出提示信息,提示你刚刚输入的是什么。
    if choice not in 'neq':       #如果输入的不是neq这三个字符其中之一
        print '--invalid option,try again--'           #那么输出一段错误提示信息
    else:     #否则执行下面的内容
        if choice=='n':        #如果输入的是“n”
            prompt1 = 'login desired:'     #定义一个提示信息的变量
            while True:                  #进行while循环
                name = raw_input(prompt1)  #等待键盘输入用户名,提示信息就是上面定义的prompt1变量
                if(kgc.has_key(name)):   #如果输入的用户名已存在字典中,
                    prompt1 = '--name taken,try another:'     #重新定义一下提示信息的变量内容       
                    continue     #然后执行continue语句,重新进行循环
                else:          #反之
                    pwd = raw_input('password:')      #继续输入用户的密码
                    kgc[name] = pwd        #然后将用户名和密码写入字典中
                    break       #while循环结束
        elif choice =='e':               #如果输入的“e”
            name = raw_input('login:')     #那么等待键盘输入用户名,提示信息为“login”
            pwd = raw_input('password:')  #等待键盘输入密码,raw_input()括号中的内容时提示信息
            password = kgc.get(name)    #查询字典中的用户名对应的密码和输入的密码是否一致
            if password == pwd:     #如果一致
                print '--welcome back--',name      #则输出欢迎信息
            else:     #反之
                print '--login incorrect--'       #输出错误
        else:     #如果输入的不是n也不是e,又在neq三个字符中,那么输出的肯定是q了
            print 'quit'    #所以就退出咯
            break         #所以就退出咯

-------- end of this article so far, thanks for reading --------

Guess you like

Origin blog.51cto.com/14154700/2439207