current position:Home>Daily python, Chapter 9, while loop
Daily python, Chapter 9, while loop
2022-01-31 07:13:13 【Qing'an slag】
「 This is my participation 11 The fourth of the yuegengwen challenge 9 God , Check out the activity details :2021 One last more challenge 」.
This is Qing'an , Take you to understand while In simple terms . Let's see .
while loop
while Statement allows the program to run as many times as you want , If True It's going to run all the time
while Conditional statements :
conditional , Program
i = 0
while i < 5:
print(' Qing'an ')
i += 1
# As a result, :
# Qing'an
# Qing'an
# Qing'an
# Qing'an
# Qing'an
Copy code
while by True When :
while True:
i = input(' Please enter a number :')
if i == '1':
break
# As a result, :
# Please enter a number :2
# Please enter a number :3
# Please enter a number :1
Copy code
In this while We don't enter a string in the loop 1, It's going to go on and on , It's over , Look at the example below and you will see .
input function
I'm learning while Before the cycle , Let's study first input() function , This function causes the program to pause , Waiting for user input ! Look at the code :
lisi = input(" Please enter the content :")
print(lisi)
Copy code
input This is how functions are used , In parentheses, we can enter the prompt we want to output , Remember, it's just a string type , He can match if,for,while To use , There will be a lot of practical exercises at the end of this chapter to help you understand .
Here, we press enter after entering Qing'an on the console ,python Will run itself print Print the results directly . We can also define the type of input content , For example, integer int type :
lisi = int(input(" Please enter the content :"))
print(lisi)
# Write two
lisi = input(" Please enter the content :")
zhangsan = int(lisi)
print(zhangsan)
Copy code
Here we have another step to define another variable to receive the input content , Here's what's interesting int We can only enter numbers , If you enter a string, an error will be reported !!!
while loop
while A loop is a program that runs continuously , Until the conditions are not met !
i =1
while i < 5:
print(i)
i += 1
Copy code
Look at the example above , We first define a variable i,i by 1, Next step into while loop , We are while The loop here gives a judgment , That is, simple mathematical and logical judgment , What is noteworthy here is i += 1, Maybe some little friends don't understand , In fact, that is i = i+1, It's easier . Another point is why this i += 1 Put it in print Back .
- We started by defining a variable i=1, We want to output 5 within ,1 And 1 The figures above , You have to put i First, the output , To accumulate
- If our i = 0, that i += 1 Put it in print The front is right , Otherwise, the output is 2,3,4,5, It doesn't meet the result we want
Let's do another example :
zhangsan = ""
while zhangsan != "lisi":
zhangsan = input(" Please enter the content :")
print(zhangsan)
Copy code
explain :
- We are while Define a string variable before the loop , If you use it directly here input function ,while The cycle will fall into an endless cycle .
- Another bad thing is that the content we enter will also be printed together , The solution is a if Judge
zhangsan = ""
while zhangsan != "lisi":
zhangsan = input(" Please enter the content ")
if zhangsan != "lisi":
print(zhangsan)
Copy code
We made another judgment here , Use this judgment to remove redundant content .
In addition to using logical judgment , We can also use while The true loop in the statement , That is to say, if the conditions are not met, the cycle will continue . besides , We also have a series of exit loops , See the following example
i = True
while i:
zhangsan = input(" Please enter the content :")
if zhangsan == "lisi":
i = False
else:
print(zhangsan)
Copy code
Here we use False An end loop was performed ,while True: It will make the program judge that the conditions are not met in the process It runs all the time . When satisfied, the loop ends .
break sentence
It can control which statements run , Which statements don't run .
while True:
zhangsan = input(" Please enter the content :")
if zhangsan == "lisi":
break
else:
print(zhangsan)
Copy code
Put it here when zhangsan End the loop when the conditions are met
continue
also continue Statement can be used , It won't be with break equally , End the cycle directly ,continue You can judge whether to execute the next program according to the conditions
# A simple example
while True:
i = input(" Please enter a letter :")
if i == 'q':
continue
elif i == 'w':
break
else:
print(' continue ')
# Please enter a letter :q
# Please enter a letter :e
# continue
# Please enter a letter :w
Copy code
# Complex examples
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number)
Copy code
- Here we are just like the example above , Set a variable to 0, Then put the accumulation in print It's ahead
- there % Shi Mo Yu means ( Divide the current number by 2 Remainder ), When the remainder is 0 When you enter continue, The program stops outputting , When the modular remainder is not 0 Print the current number when
actual combat
# Define a list of variable names
name = ['zhangsan','lisi','wangwu','zhaoliu']
# Then define a list of users who complete authentication
name_user = []
while name:
users = name.pop()
print(f" What has been verified is :{users.title()}")
name_user.append(users)
for name_users in name_user:
print(f" The users who have completed the verification are :{name_users.title()}")
Copy code
Here , We simply use while List validation was performed , We used .pop(),.append(),.title() Method , This is what we talked about when we talked about the list , Forget the little partner, hurry to review , Let's go straight to the interpretation stage :
.pop() The way is to remove , But we can still access it , Here we give the removed list string to a new variable , In order to add later ..append() Methods? , It means adding , Add the previously removed list string to the empty list we defined , Reuse for Cycle to print .
We can also do Delete Operation
name = ['zhangsan','lisi','wangwu','zhaoliu','zhangsan','lisi']
while 'lisi' in name:
name.remove('lisi')
print(name)
Copy code
Here we use to determine whether a string is included in the list ,in Method , Then use the list operation to delete , And print
copyright notice
author[Qing'an slag],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310713119205.html
The sidebar is recommended
- My friend's stock suffered a terrible loss. When I was angry, I crawled the latest data of securities with Python
- Python interface automation testing framework -- if you want to do well, you must first sharpen its tools
- Python multi thread crawling weather website pictures and saving
- How to convert pandas data to excel file
- Python series tutorials 122
- Python Complete Guide - printing data using pyspark
- Python Complete Guide -- tuple conversion array
- Stroke the list in python (top)
- Analysis of Python requests module
- Comments and variables in Python
guess what you like
-
New statement match, the new version of Python is finally going to introduce switch case?
-
Fanwai 6 Different operations for image details in Python opencv
-
Python crawler native code learning (I)
-
Python quantitative data warehouse building series 2: Python operation database
-
Python code reading (Part 50): taking elements from list intervals
-
Pyechart + pandas made word cloud pictures of 19 report documents
-
[Python crawler] multithreaded daemon & join() blocking
-
Python crawls cat pictures in batches to realize thousand image imaging
-
Van * Python | simple crawling of a planet
-
Input and output of Python practice
Random recommended
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
- Python hashlib module
- The cover of Python 3 web crawler development (Second Edition) has been determined!
- The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
- [Python basics] explain Python basic functions in detail, including teaching and learning
- Python web crawler - crawling cloud music review (4)
- The first step of scientific research: create Python virtual environment on Linux server
- Writing nmap scanning tool in Python -- multithreaded version
- leetcode 2057. Smallest Index With Equal Value(python)
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python crawler actual combat, requests module, python realizes capturing a video barrage
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
- How IOS developers learn python programming 3-operator 2
- How IOS developers learn python programming 2-operator 1
- [Python applet] 8 lines of code to realize file de duplication
- Python uses the pynvml tool to obtain the working status of GPU
- Data mining: Python actual combat multi factor analysis
- Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
- Use Python VTK to batch read 2D slices and display 3D models
- Complete image cutting using Python version VTK
- Python interface automation test framework (basic) -- common data types Dict
- Python specific text extraction in actual combat challenges the first step of efficient office