python learning the usage --while True

In the learning process, often encounter the usage adopted while True. Below an example will be described:

Create a user login system, the user enters a user name and password, if you can correctly enter the system.

1, the beginning of my own writing:

d = {} # dictionary database, all the user's username and password is stored in this

name = input ( "Please enter your user name:")
IF name in d:
password = the INPUT ( "Please enter your password")
IF d [name] == password:
Print ( 'into the system')
the else:
Print ( 'password you entered is incorrect, please try again')
the else:
Print ( 'username you entered is incorrect, please re-enter')

The procedural logic to write their own seemingly right:
- let the user enter a user name, if the user name exists, they continue to let the user enter a password, if the correct password to enter the system. If the password is incorrect to re-enter.
- If the user name does not exist, suggesting that "the username you entered is incorrect, please re-enter"

But in actual operation, if the user enters a user name and password are correct, it is naturally no problem. But if there is a input is incorrect, the system will only show that "the username you entered is incorrect, please re-enter" or "password you entered is incorrect, please re-enter." That is, if an error occurs, does not return to its original place, continue to request input.

2, using the loop while True:

With this statement is the core idea is that if something goes wrong, you can continue the cycle.

d = {}

Ture the while:
name = the INPUT ( 'Please enter your user name:')
IF name in d:
BREAK
the else:
Print ( 'The username you entered does not exist, please try again')
the Continue

True the while:
password = the INPUT ( 'Please enter your password:')
IF d [name] == password:
Print ( 'into the system')
BREAK
the else:
Print ( 'The password you entered is incorrect, please re-enter')
continue

the above program can achieve the desired purpose: the user returns the name or password input error to the beginning, request continuation input.

while True statement must be the end of the cycle of break statement, otherwise it would have been the cycle continues.

Of course, we met if the password is wrong, you have the opportunity to be prompted to enter the password several times. It can be achieved:

. 5 = COUNT
the while COUNT:
password = INPUT ( 'Enter your password:')
IF D [name] password ==:
Print ( 'Enter system')
BREAK
the else:
COUNT - =. 1
Print ( 'code you entered is not correct, there are times {} input opportunity '.format (COUNT))
the Continue
---------------------
author: geerniya
source: CSDN
original: https: // blog.csdn.net/geerniya/article/details/77524173
Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/huigebj/p/11298332.html