Index: Python3 Scripting Part 1 (Basics) Python3 Scripting Part 2 (Loops and Constructs) I decided to write a whole Python3 tutorial series after I saw the posts and emails my readers sent me. For the next article in this tutorial series, we will discuss the different loop and decision constructs as well as Boolean expressions. Many programmers agree that loop and decision constructs are the most powerful features of programming languages. Python supports IF, WHILE, and FOR constructs. Many of you may be wondering about UNTIL constructs; Python3 does not support UNTIL constructs, but there is an easy way to mimic an UNTIL construct. IF: All or nearly all programming languages support IF constructs. These decision constructs allow the program to perform tests and only execute if a statement is true. I will show what an IF construct looks like and then I will explain it in the script. Code: VAR = 7 if VAR == 6: print('If the variable \'VAR\' equals 6, then you would see this text.') elif 'text'.casefold() in VAR: print('If the string \'text\' is in the variable \'VAR\', then this sentence will be printed') elif VAR =< 17: print('If VAR is equal to or less than 17, this line will be executed. Because this statement is true, you will see this sentence printed') else: print('Depending on what you are wanting to accomplish, the else statement may write an error code to a log file, create a missing file this construct was looking for, or what ever you need done if the other test false.') Code: STR = 'Linux, Irix, Solaris, Haiku' if 'IRIX'.casefold() in STR.casefold(): print('If the word "irix" is in the variable "STR", then this is executed. The ".casefold()" makes the letters lowercase. This is how case-insensitive pattern matching can be implemented. Whether Irix is stored in the variable as "irix", "Irix", "IRIX", or some other combination, this line will be executed.') #No "elif" or "else" lines are required or you may have one or the other. However, you must have "if". IF constructs also support nesting which is embedding constructs inside of others. This means if a certain statement evaluates to true, then the nested construct will execute. Code: import math, platform #I am importing math and platform if math.cos(37): #If this command executes successfully do - if 'linux'.casefold() in platform.system().casefold(): print('This is a Linux system that can calculate the cosine of 37.') NOTE: "platform.system()" prints the system type. For example, on GNU/Linux systems, the output is "Linux". Some nested IF constructs can be combined into one statement. Doing so is better for code maintenance and performance. Code: import math, platform #I am importing math and platform if math.cos(37) and 'linux'.casefold() in platform.system().casefold(): #If this command executes successfully do - print('This is a Linux system that can calculate the cosine of 37.') Notice the Boolean operator AND between the two statements. The print() command will only execute if both statements are true. Programmers can also use the Boolean OR which means either statement can be true. In this example, either the system must execute math.cos(), be a Linux system, or both. The IF construct can also use the Boolean NOT - Code: import os if not os.path.isfile('./file.var'): SOME CODE The above code will execute some code if "./file.var" is not a file. NOT negates the statement. "os.path.isfile()" tests if a path is a file. So, with these two together, code is executed if "./file.var" is not a file. Without NOT, the code would execute if the file existed. By the way, because Python is case-insensitive, the os.path.isfile() command would look for “./file.var” not any other case. IF constructs support various Boolean expressions - Code: == - equals != - does not equal < - less than > - greater than =< - equal to or less than >= - equal to or greater than is - equals is not - does not equal in - a string is in another (if 'irix'.casefold() in X.casefold():) not in - a string is not in another (if 'irix'.casefold() not in X.casefold():) NOTE: When testing strings, the casefold() command is not required. It can be used to perform a case-insensitive test. This works because both strings being compared are both made lowercase including many foreign alphabets like Greek and Cyrillic letters. Accented letters are also included. You may wonder why I am not using lowercase() instead of casefold(). Well, casefold() supports more letters and converts from uppercase to lowercase in a more efficient and accurate manner. In some IF constructs, the programmer may have some test, but does not want any code to execute under those conditions. The IF statements require some task to perform if the condition is true. In cases like this, use the "pass" command. Code: if not math.isfinite(X): pass #A valid command must be here. Comments cannot be used as substitutes for commands to occupy this line. elif Z >= X: NUM = math.sqrt(math.acos(Z)) In the above code, nothing happens if X is an infinite number. The "pass" command is executed which is a null command. However, if X is finite, then the first statement is false which means the ELIF statement is tested. If Z is equal to or greater than X, then the arc cosine of Z is then passed to the square root command and then that final answer is saved to a variable. Another use of “pass” is if the user does not want actions to be performed under certain conditions and knows that the construct would at least execute ELSE. To prevent any actions from occurring with particular conditions and ELSE, state the conditions and use the pass command. WHILE: The WHILE construct will continue to execute code while the statement is true. WHILE loops are popular for counters. Code: while COUNTER != 7: COUNTER += 1 print(COUNTER) If a programmer intends that the WHILE loop end at some point or they wish the loop to stop when it starts repeating the same action, use the "break" command. Look at this example - Code: while True: print('LOOP') break The above code will print "LOOP" once and then the loop will end. Even if there were a counter in the construct (or any other data constant change), the loop would break after the first iteration because the Python interpreter knows that it is impossible for the loop to end. As stated above, the WHILE loop will continue while the statement is true, so if the statement is literally "True", the loop will never end. If the condition statement had a chance of ending like "while X in Y", then it is possible for the loop to end because the variables can change. NOTE: Yes, you can use "True" and "False" in Python code. Just like IF constructs, WHILE loops support the ELSE statement which is executed the first instance the WHILE statement is false. This means the loop may run one or more iterations and then execute the ELSE statement on the first false. Then, the loop ends. FOR: The FOR loop is more useful than what many newbie programmers would expect. The FOR loop is helpful and performs well when performing repetitive tasks. For example, assume a programmer made a script that contains these lines of code that finds and deletes certain strings of text. TEXT = re.sub('word1', '', TEXT, flags=re.I) #import the re module to use this find and replace command TEXT = re.sub('word2', '', TEXT, flags=re.I) TEXT = re.sub('word3', '', TEXT, flags=re.I) TEXT = re.sub('word4', '', TEXT, flags=re.I) NOTE: By the way, this is the structure of the re.sub() command - "re.sub(FIND, REPLACE, TEXT_TO_CHANGE, FLAGS)". "re.I" makes the find and replace case-insensitive. The code can be made simple by using a FOR loop. This allows the code to be smaller, easier to maintain, and faster. Look at the code below which shows the above code turned into a FOR loop. Code: REMOVE = ['word1', 'word2', 'word3', 'word4'] for FIND in REMOVE: TEXT = re.sub(FIND, '', TEXT, flags=re.I) The REMOVE variable contains a list (the different data types will be explained in a different article). This list contains the words the user wanted found and removed. Now, if the user wishes to add more words, the programmer can simply add another word or phrase. The FOR statement "for FIND in REMOVE:" gets an entry out of REMOVE and places it in the variable FIND. After the FOR loop is code that is indented further than the FOR statement. The FIND variable is typed in the spot for data to be found. The FOR loop will get one string out of the list and perform the listed commands on it. Once the list has been read and run through the code, the FOR loop ends. Using a FOR loop in place of large, repetitive code makes the code easier to maintain and the program faster. UNTIL: Some programming languages have an UNTIL loop. Unfortunately, Python3 does not have such a useful statement. Well, here is a way to have an UNTIL construct in your code. WHILE and UNTIL are opposites - WHILE X is true do Y; UNTIL X is true do Y. The WHILE construct will continue while a condition is true. An UNTIL loop will continue until a condition is true. In Python, if you want to make code that does some task until the counter is seven, then type code like this - Code: while COUNTER != 7: COUNTER += 1 In the form of a WHILE loop, the code will still execute until the counter equals seven. For example, if the counter starts at zero, it will stop at seven. Print Results: The print() command can print the results of tests. Users can write code like this - Code: X = 7 print(X == 7) Because the variable “X” is “7”, the output will be “True”. Programmers can also print text at the same time as the evaluation results. Code: print('TEXT', X == 7) The above code will print the string “TEXT” with the results of the Boolean test. In the next article, we will discuss the different types of data. Feel free to ask questions about this series (like clarification) via Linux.org, my email, or Google Plus account (Google.com/+DevynJohnson). If you have a simple question, feel free to also ask at the same place. However, if your question is more complex, ask on the Python mailing lists or the Python community on Google Plus.