Home  >  Article  >  Backend Development  >  Learning records of python basic loops

Learning records of python basic loops

高洛峰
高洛峰Original
2017-03-21 09:46:271760browse

1. while loop

If the condition is true (true), repeat the same operation, if the condition is not met, jump out of the loop

while loop condition:

  Loop operation

(1) while loop example

Example: Enter the test scores of Wang Xiaoming’s 5 courses and calculate the average grade

i=1                                            # 初始化循环计数器i
sum=0                                          # 初始化总成绩变量
while i<=5:                                    # 从i为1开始到5,重复执行一共5次接受考试成绩、求和的操作
        print (&#39;请输入第%d门课程的考试成绩&#39;%i)    # 提示用户输入成绩,其中用到了格式化输出,%d的取值随i的值显示,第1门课程,第2门课程……
        sum=sum+input()                        # 把用户输入的成绩赋值给sum,最后保存着5次成绩的和
        i=i+1                                  # 每次循环 i 都自增1,直到大于5跳出循环
avg=sum/(i-1)                                  # 当第五次执行完i=i+1时,i为6,跳出循环,计算出sum/(i-1)的值就是平均值,并赋值给avg
print (&#39;王晓明5门课程的平均成绩是%d&#39;%avg)          # 格式化输出avg的值,由于用了%d所以计算出的%avg的数值有小数也会省去,接收整数部分

(2) Nested while Loop example

After the outer loop meets the conditions, the execution code starts to execute the inner loop. When all the inner loops are executed, if the outer loop conditions are still met, the outer loop is executed again, and so on, until the outer loop is jumped out.

Example: Enter the scores of 5 subjects of two students respectively, and calculate the average score respectively

j=1                                         # 定义外部循环计数器初始值
prompt=&#39;请输入学生姓名&#39;                       # 定义字符串变量,在用户输入时调用此变量可以减少敲汉字的麻烦
while j<=2:                                 # 定义外部循环为执行两次
    sum=0                                   # 定义成绩初始值,之所以定义在这里,是为了当第二个学生输入成绩时可以让sum初始化为0,重新接收新学生的成绩和
    i=1                                     # 定义内部循环计数器初始值
    name = raw_input(prompt)               # 接收用户输入的学生姓名,赋值给name变量
    while i<=5:                             # 定义内部函数循环5次,就是接收5门课程的成绩
        print (&#39;请输入第%d门的考试成绩: &#39;%i)   #提示用户输入成绩,其中用到了格式化输出,%d的取值随i的值显示,第1门课程,第2门课程……
        sum= sum + input()                  # 接收用户输入的成绩,赋值给sum
        i+=1                                # i变量自增1,i变为2,继续执行循环,直到i等于6时,跳出循环
    avg=sum/(i-1)                           # 计算第一个学生的平均成绩 sum/(6-1),赋值给avg
    print name,&#39;的平均成绩是%d\n&#39;%avg         # 输出学生成绩平均值
    j=j+1                                   # 内部循环执行完毕后,外部循环计数器j自增1,变为2,再进行外部循环
print &#39;学生成绩输入完成!&#39;                     # 外部循环结束,提示输入完成!

2. for loop

(1) Use for statement can traverse all elements, such as outputting characters in a string one by one, outputting elements in a list one by one, elements in tuples, elements in sets (pay attention to the order of each element when assigning values), dictionary The keys in...

for letter in &#39;Python&#39;:
  print letter结果:P
y
t
h
o
n
fruits=[&#39;西瓜&#39;,&#39;水蜜桃&#39;,&#39;葡萄&#39;]
for fruit in fruits:
    print fruit

结果:
西瓜
水蜜桃
葡萄

(2) Repeat the same operation

Use the range() function to create a list of numbers

Value range: From the starting number to before the ending number

for i in range(0,5):  #依次把0到4保存在变量i中
    print &#39;Mr.Mangood最酷!&#39;

结果:
Mr.Mangood最酷!
Mr.Mangood最酷!
Mr.Mangood最酷!
Mr.Mangood最酷!
Mr.Mangood最酷!

Enter Wang Xiaoming’s three test scores and calculate the average

subjects=(&#39;linux系统&#39;,&#39;Mysql数据库&#39;,&#39;Python语言&#39;)  # 定义一个元组,三个元素代表三门课程
sum=0                                            # 定义变量num为初始化成绩分数
for i in subjects:                               # 把元组里的每一个元素依次赋值给i,一共有三次
    print &#39;请输入%s的考试成绩&#39;%i                   # 提示输入成绩,运用了格式化字符串功能,用i每次取得的元素名表达出成绩名字,%s的意思是字符串
    score = input()                              # 接收用户输入的成绩赋值给score
    sum += score                                 # 把成绩赋给sum,相当于sum = sum + score
avg= sum / len(subjects)                         # 跳出for循环后,计算平均值,这里用函数len()来计算变量subjects的长度,因为subjects定义为一个元组,因此长度即为元素个数3
print &#39;王晓明的平均成绩为%d&#39;%avg                    # 输出平均成绩

结果:
请输入linux系统的考试成绩
87
请输入Mysql数据库的考试成绩
78
请输入Python语言的考试成绩
90
王晓明的平均成绩为85

(3) Nested for loop

Enter Huang Xiaoming , Yang Ying, two classmates, each took three courses, and calculated the average score

student = (23&#39;黄晓鸣&#39;,&#39;杨影&#39;)                      #定义学生姓名的元组
subjects=(&#39;linux系统&#39;,&#39;Mysql数据库&#39;,&#39;Python语言&#39;)  #定义课程名字的元组
for j in student:                                #把j依次取两名学生的值进行两次循环
    sum=0                                        #初始化成绩的值
    print &#39;%s同学的考试成绩&#39;%j                     #打印出标题
    for i in subjects:                           #定义课程循环
        print &#39;请输入%s的考试成绩&#39;%i               #提示输入其中一名学生的考试成绩
        score = input()                          #接收考试成绩赋值给score
        if score<0 or score>100:                 #判断分数取值范围,做提醒
            print &#39;注意成绩大小&#39;    
        sum+=score                               #每次输入成绩后,sum值都累加
    avg= sum/len(subjects)                       #求出平均成绩
    print j,&#39;的平均成绩是%d\n&#39;%avg                 #打印平均成绩
print&#39;完成学生成绩录入工作&#39;                         #提示完成工作

3. Loop control

LoopControl statementCan change the normal execution order of the loop

Loop control statement

breakStatement: jump out of this loop (only one layer of loops in a nested loop jumps out)

continueStatement: skip the remaining statements of the current round of loop body, retest the loopstate, and enter the next round of loop. For example, the number of loops is 5 times in total. If continue is encountered four times, then the execution will not continue and the fifth loop judgment will be carried out directly

4. Loop controlComprehensive case

1. Requirements analysis

Show menu

(N)ew User Login

(E)ntering User Login

(Q)uit

Enter choice:

Note: Enter the letter N to receive the new login name and password and save it in the dictionary

Input the letter E, receive login name, password, search, match user input is correct

Enter the letter Q, exit

2, execute steps

(1) Compilation Menu

 (2) Use while statement to implement menusingle selection-outer loop

 (3)Use while statement to receive new login name-inner loop

 (4) Use the if statement to judge the menu and perform related operations

3. CodeArchitecturePicture

Learning records of python basic loops

4. Specific code

db={}           
prompt=&#39;&#39;&#39;         
    (N)ew user login
    (E)ntering user login
    (Q)uit
Enter choice:&#39;&#39;&#39;
while True:         
    choice = raw_input(prompt).strip()[0].lower()       #读取控制台输入的字符串,去除其首尾多余的空格后,将第一个字符串转换为小写字母
    print &#39;\n--You picked:[%s]&#39;%choice      
    if choice not in &#39;neq&#39;:
        print &#39;--invaild option:,try again--&#39;
    else:
        if choice == &#39;n&#39;:
            prompt1 = &#39;--login desired:&#39;
            while True:
                name = raw_input(prompt1)
                if db.has_key(name):            #判断字典里的键值是否已经有输入的name值,如果有的话触发continue重新执行while循环,因为触发continue前prompt1被重新定义了,所以执行了新的name = raw_input(prompt1)
                    prompt1 = &#39;--name taken,try another: &#39;
                    continue
                else:
                    break
            pwd = raw_input(&#39;password:&#39;)    #验证字典中的键没有输入的name值后,跳出循环,把用户输入的密码赋值给pwd
            db[name] = pwd      #把值传给字典db中的name键实现字典数据的完善
        elif choice == &#39;e&#39;:
            name = raw_input("login:")
            pwd = raw_input(&#39;password:&#39;)
            password = db.get(name)     #登录时,接收用户输入的登录名和密码后,把字典db中name键的值赋给password
            if password == pwd:     #比较字典中的密码password和用户输入的密码pwd是否一致
                print &#39;welcome&#39;,name
            else:
                print &#39;shibai&#39;
        else:
            print &#39;quit!&#39;
            break


The above is the detailed content of Learning records of python basic loops. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn