while loop of python learning notes

Keywords: Python Java Ruby REST

python learning notes (8) while loop

1. while cycle
In the previous blog, we have learned about the for loop. Here we introduce another loop, while.
The syntax of while is very simple. According to its English definition "when...", as long as the following conditional statements of while are met, its loop body will always execute. Thus, the main differences between for loop and while loop are as follows:
If we know the number of loops, we usually choose for loop, but if we want to perform the operation as long as the conditions are met, we choose while loop.

age = 16
while (age < 18):
	print("You are " + str(age) + " years old.")
	print("Therefore, you are still a child, now.")
	age += 1
print("You are " + str(age) + " years old.")
print("Therefore, you have become an adult!")

The operation result is:

You are 16 years old.
Therefore, you are still a child, now.
You are 17 years old.
Therefore, you are still a child, now.
You are 18 years old.

It can be seen that the general format of the while loop is:

while conditional_test:
	do something

Therefore, the while loop doesn't care how many times the loop will be executed (of course, if the user wants to know, you can put a dynamically updated variable in the loop body). As long as the conditional "test is True, do something once, and then continue to judge.

2. Advantages of while loop
I think the biggest advantage of the while loop is that it can give the process of the program to the user. We only need to set an exit that can be controlled by the user in the conditional "test, then the user can control the while loop outside the program. Take a simple example:

message = "Please tell me something, then I'll repeat it back to you: "
message += "\nIf you are unwilling to play, just tell me 'quit'.\n"
get = ''
while (get != 'quit'):
	get = input(message)
	if(get != 'quit'):
		print(get)

The operation result is:

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
Hello!
Hello!

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
My name is Good!
My name is Good!

Please tell me something, then I'll repeat it back to you: 
If you are unwilling to play, just tell me 'quit'.
quit

3. The improvement of while loop

Sometimes there are multiple conditions that restrict the process of the while loop, so we can set a flag variable (such as flag) to show whether the while loop is executing. This is not only convenient for us to control it, because once the condition changes, we can directly change the value of the flag variable; and once the while loop stops unexpectedly, it is convenient for us to debug.

4. continue and break
continue keyword:
Ignore the remaining code in the loop, return to the beginning of the loop directly, and decide whether to continue the loop according to the result of conditional test.
Example:

#Print out all multiples within 100 and 3
number = 0
while (number <= 100):
	number += 1
	if (number%3 != 0):
		continue
	else:
		print(number)

break keyword:
Exit the loop immediately and do not run the rest of the code in the loop.
Example:

number = 0
while True:
	number += 1
	if (number>100):
		break
	if (number%3 == 0):
		print(number)

The function is the same as that in the above example, but the actual use is different. The existence of break keyword allows us to write code such as while True (dead loop), because we can fully use break to implement the exit inside the program.

5. Advantages of while over for
I mentioned before that for loop can be used to traverse, but it can't modify the value at the same time of traversal, because it is likely to lead to the failure to track all elements, but while loop has no such problem. Here is the application of while loop for lists and dictionaries.

A element mark

languages_to_learn = ['python', 'c', 'java', 'ruby']
languages_learned = []
print("languages_to_learn:")
print(languages_to_learn)
print("\nlanguages_learned:")
print(languages_learned)
print()
while languages_to_learn:
	language_learning = languages_to_learn.pop()
	print("I am learning " + language_learning + ".")
	languages_learned.append(language_learning)
print("\nlanguages_to_learn:")
print(languages_to_learn)
print("\nlanguages_learned:")
print(languages_learned)

The operation result is:

languages_to_learn:
['python', 'c', 'java', 'ruby']

languages_learned:
[]

I am learning ruby.
I am learning java.
I am learning c.
I am learning python.

languages_to_learn:
[]

languages_learned:
['ruby', 'java', 'c', 'python']

I'm sure you are familiar with this operation. Many algorithms use this marking idea to prevent repeated operations.

B list element delete
You should remember that the. remove() function I mentioned earlier can only delete the first occurrence of the specified element value in the list. If we want to delete all the specified element values in the list, we can use while. Look at the example:

languages_0 = ['python', 'c', 'java', 'ruby', 'python']
languages_0.remove('python')
print(languages_0)
languages_1 = ['python', 'c', 'java', 'ruby', 'python']
while ('python' in languages_1):
	languages_1.remove('python')
print(languages_1)

The operation result is:

['c', 'java', 'ruby', 'python']
['c', 'java', 'ruby']

C dictionary information update
Here I've seen a very interesting small example, you can carefully experience the role of while loop.

favorite_languages = {}

#Set a flag to record the cycle status
flag = True

while flag:
	name = input("\nWhat's your name?\n")
	language = input("What's your favorite language?\n")

	favorite_languages[name] = language

	repeat = input("Go on?(y/n)")
	if (repeat == 'n'):
		flag = False

print("\n----Results are as followings.----\n")
for name, language in favorite_languages.items():
	print(name + " likes " + language + " best!")
print("Over!")

The operation result is:

Published 11 original articles, won praise 11, visited 1325
Private letter follow

Posted by SheepWoolie on Thu, 30 Jan 2020 03:29:17 -0800