# Lesson 4 Notes/Projects

The following code is for a basic login username/password checker for a user to sign into a application or website, using first if-elif-else statements, and the variant of it, will use a while loop to make things more clean looking and more efficient. 以下代码是用于用户登录应用程序或网站的基本登录用户名/密码检查器，使用第一个 if-elif-else 语句及其变体，将使用 while 循环使事情看起来更干净， 更高效。

Variant 1:

import logging

logger = logging.getLogger(__name__)

dict_data = {"aiyc": 1234, "bob": 1245}
else:


Variant 2:

import logging

dict_data = {"aiyc": 1234, "bob": 1245}
logger = logging.getLogger(__name__)
run = False
while not run:
run = True
else:


The second variant works better, since while loops make it much easier to keep asking for user input no matter how many times their input is invalid under our circumstances. While loops help a lot with something that requires a user to input something, since they are not like if or else statements, where you can only use them to check indefinitely once. While loops can be used to check for something until that circumstance or condition is met. This means that using them with user inputs, and defining a special condition for the while loop, and nesting logic statements such as if-elif-else statements in while loops, make it extremely easy and efficient to repeatedly ask or do something if a certain condition is not met.

Speaking of using all these loops and conditional statements, it is easy to trip over something really basic or easy to fix, such as a indentation problem. If you use two different methods of indenting a nested statement, or a statement that is meant to be inside of a codeblock, then python will return a IndentationError when you try running your code. There are two methods to indent code in python, using the "tab" key on your keyboard, or hitting the space key on your keyboard 4 times. You must use one method of indenting in all of your code, otherwise python will return an error stating something is wrong with your indentation. Copying a code with indents in it, from a website- most websites use the 4 spaces to indent their code, rather than using tabs, so you must keep this in mind when implementing outside code into your own code, as it could potentially cause a lot of problems especially in an IDE, such as pycharm, and it could drive you crazy trying to debug your code, while the simple issue is simply just to format the indentations in your code correctly.

If you nest a loop within a loop, such as a for loop nested within a while loop, and you try to use the "break" keyword to end the main loop, nothing will happen, since python cannot kill both loops with one keyword. This is where boolean flags come into play in python, since you can set a variable equal to a boolean value, and use a while loop to loop through certain actions while a certain boolean value is not being met. This results in a forever loop if you were never to set the boolean value to whatever meets the while loop's constraints, since the variable you compared it to, is predefined. This means that you have to manually set the boolean variable to whatever meets the while loop's constraints, then use the "break" keyword to kill the second loop. Otherwise, the program will be stuck in a forever loop, which is something you don't want. This is an example of a forever loop that will occur if you only try to use the break keyword to stop a forever loop, without any boolean flags:

while True:
for i in range(10):
print(i)
break
print("Loop is done!")


The loop above will never stop running because you only use the "break" keyword, and you do not set a boolean flag to completely force kill the while loop. The example below is a proper code that will stop after printing every value starting from 0 and going to 10, without printing out 10:

run = False
while not run:
for i in range(10):
print(i)
if i == 9:
run = True
print("Loop is done!")


The code given as an example above actually prints out everything from 0 - 10 ignoring the print statement for 10, (due to range()), and it prints out "Loop is done!", since this time it actually exits the for loop, and runs that statement, and then the code is finished executing. The reason why you cannot set a boolean flag after the "break" statement or put any code after the "break" statement, is because nothing after the break statement will run, since it's immediately skipped over.

Here is the line-by-line explanation of what each line in the code with the nested loop actually does:

run = False # sets a run flag, using a boolean value. 使用布尔值设置运行标志。
while not run: # runs code within loop if boolean flag is equal to False. 如果布尔标志等于 False，则在循环内运行代码.
for i in range(10): # loops through numbers in range 0 - 10. 循环遍历 0 - 10 范围内的数字
print(i) # prints number that is being looped through the range of 0 - 10, without printing 10. 打印在 0 - 10 范围内循环的数字，而不打印 10。
if i == 9: # checks to see if number being looped is equal to 9. 检查循环中的数字是否等于 9。
run = True # if number being looped is equal to 9, then set boolean flag value to be equal to True, thus ending the while loop, and stopping the program. 如果被循环的数字等于 9，则将布尔标志值设置为等于 True，从而结束 while 循环，并停止程序。
print("Loop is finished!") # after while loop is exited, print a mesasge stating that the loop is finished. 在 while 循环被激发后，打印一条消息，说明循环已完成。


If you want to make sure 100% that both loops are killed, then you should add the "break" keyword after you set your boolean flag's value to True, this way it will not only kill the while loop if the number that's being looped through is equal to 9, but it will also kill the for loop, thus guaranteeing that the program will 100% be finished running, if the number that is being looped through is equal to 9.

The easiest way to determine the output of a while loop, is to acquire a "reverse thought process". A typical person would try to go step by step, and try to visualize in their head, step by step from the starting point, what the output of a code would be. This is not very efficient as it takes a while for you to go step by step. Instead, what you could do is, you could immediately start visualizing from the most likely point where the program's next step, would be to return False, and kill the while loop, and once you are sure that is what the program will do, then you could be sure that the pattern from the starting point will be the pattern for output, all the way until the point where you determined the program's next step would be to return False, which means your program will output every value/output in that pattern all the way from the starting point to that value. For example, if you wrote this code:

run = False
while not run:
for i in range(10):
print(i)
if i == 9:
run = True
break
print("Loop is finished!")


You could start your thought process from 9, since that is that last number where the next step for the program, would be to return False, since 10 = 10, and the while loop only runs when the number being looped through is less than 10. This means that you know that the program will only output every value from the starting point, 0, to 9, and print the message that is supposed to be run when the program exits, since the next step for the value 9, would be to return False, which would stop the loop, which means that nothing is outputted after 9, and the program immediately prints out the exiting message.

AI悦创·推出辅导班啦，包括「Python 语言辅导班、C++辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发」，全部都是一对一教学：一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。QQ、微信在线，随时响应！V：Jiabcdefh
AI悦创 » Lesson 4 Notes/Projects