SoFunction
Updated on 2024-11-19

Python's control structure of For, While, If loop problem

The main control structure of the traditional Python language is the for loop. However, it is important to note that for loops are not commonly used in Pandas, so the efficient execution of for loops in Python does not apply to the Pandas pattern. Some common control structures are listed below.

  • for loop
  • while loop
  • if/else statements
  • try/except statements
  • generator expression (math.)
  • list-deductive formula
  • pattern matching

All programs eventually need a way to control the flow of execution. This section describes some techniques for controlling the flow of execution.

01 for loop

The for loop is one of Python's most basic control structures. A common pattern for using for loops is to use the range function to generate a range of values and then iterate over them.

res = range(3) 
print(list(res)) 
 
# Output: [0, 1, 2]

for i in range(3): 
print(i) 
 
''' Output:
0
1
2
''' 

for loop list

Another common pattern for using for loops is to iterate over lists.

martial_arts = ["Sambo","Muay Thai","BJJ"] 
for martial_art in martial_arts: 
 print(f"{ martial_art} has influenced\ 
  modern mixed martial arts") 
 
'''exports:
Sambo has influenced modern mixed martial arts
Muay Thai has influenced modern mixed martial arts
BJJ has influenced modern mixed martial arts
''' 

02 while loop

A while loop is a type of loop that repeats as long as the condition is valid.A common use of while loops is to create infinite loops. In this example, the while loop is used to filter a function that returns one of two attack types.

def attacks(): 
 list_of_attacks = ["lower_body", "lower_body", 
  "upper_body"] 
 print("There are a total of {lenlist_of_attacks)}\ 
  attacks coming!") 
 for attack in list_of_ attacks: 
 yield attack 
attack = attacks() 
count = 0 
while next(attack) == "lower_body": 
 count +=1 
 print(f"crossing legs to prevent attack #{count}") 
else: 
 count += 1 
 print(f"This is not lower body attack, \ 
I will cross my arms for# count}") 
 
'''exports:
There are a total of 3 attacks coming!
crossing legs to prevent attack #1
crossing legs to prevent attack #2
This is not a lower body attack, I will cross my arms for #3
''' 

03 if/else statements

An if/else statement is a common statement that branches between judgments. In this example, if/elif is used to match branches. If there is no match, the last else statement is executed.

def recommended_attack(position): 
 """Recommends an attack based on the position""" 
 if position == "full_guard": 
 print(f"Try an armbar attack") 
 elif position == "half_guard": 
 print(f"Try a kimura attack") 
 elif position == "fu1l_mount": 
 print(f"Try an arm triangle") 
 else: 
 print(f"You're on your own, \ 
  there is no suggestion for an attack") 
recommended_attack("full_guard")# Output: Try an armbar attack
recommended_attack("z_guard") 
 
#exports:You're on your own, there is no suggestion for an attack 

04 Generator Expressions

Generator expressions build on the concept of the yield statement, which allows for inert evaluation of sequences. The benefit of generator expressions is that nothing is evaluated or put into memory until the actual evaluation is computed. This is the reason that the following example can be executed in a generated sequence of infinite random attacks.

In the generator pipeline, lowercase attacks such as "arm_triangle" are converted to "ARM_TRIANGLE", and then the underscores are removed to get "ARM TRIANGLE".

def lazy_return_random_attacks(): 
 """Yield attacks each time""" 
 import random 
 attacks = {"kimura": "upper_body", 
  "straight_ankle_lock": "lower_body", 
  "arm_triangle": "upper_body", 
  "keylock": "upper_body", 
  "knee_bar": "lower_body"} 
 while True: 
  random_attack (list(())) 
  yield random attack 
 
#Make all attacks appear as Upper Case 
upper_case_attacks = \ 
  (().upper() for attack in \ 
  lazy_return_random_attacks()) 
next(upper-case_attacks) 
 
# Output: ARM-TRIANGLE
## Generator Pipeline: One expression chains into the next 
#Make all attacks appear as Upper Case 
upper-case_attacks =\ 
 (attack. pop().upper() for attack in\ 
 lazy_return_random_attacks()) 
#remove the underscore 
remove underscore =\ 
 (("_")for attack in\ 
 upper-case_attacks) 
#create a new phrase 
new_attack_phrase =\ 
 (" ".join(phrase) for phrase in\ 
 remove_underscore) 
next(new_attack_phrase) 
 
# Output: 'STRAIGHT ANKLE LOCK'
for number in range(10): 
 print(next(new_attack_phrase)) 
 
'''Output:
KIMURA
KEYLOCK
STRAIGHT ANKLE LOCK
''' 

05 List Derivative

Syntactically list derivatives are similar to generator expressions, however a direct comparison of them reveals that list derivatives evaluate in memory. In addition, list derivatives are optimized C code, which can be considered a significant improvement over traditional for loops.

martial_arts = ["Sambo", "Muay Thai", "BJJ"] 
new_phrases [f"mixed Martial Arts is influenced by \ 
 (martial_art)" for martial_art in martial_arts] 
print(new_phrases) 
['Mixed Martial Arts is influenced by Sambo', \ 
'Mixed Martial Arts is influenced by Muay Thai', \ 
'Mixed Martial Arts is influenced by BJJ'] 

06 Intermediate themes

With these basics in place, it is important to understand not only how to create code, but also how to create maintainable code. One way to create maintainable code is to create a library, and another way is to use code written in an already installed third-party library. The general idea is to minimize and decompose complexity.

Writing Libraries with Python

It is very important to write a library in Python, and it does not take long to import the library into the project. The following examples are the basics of writing libraries: In the repository there is a folder called funclib with an _init_ .py file. To create a library, there needs to be a module containing a function in that directory.

First create a file.

touch funclib/

Then create a function in that file.

"""This is a simple module""" 
def list_of_belts_in_bjj(): 
 """Returns a list of the belts in Brazilian jiu-jitsu""" 
 belts= ["white", "blue", "purple", "brown", "black"] 
 return belts 
import sys;("..") 
from funclib import funcmod 
funcmod.list_of_belts_in-bjj() 
 
#exports:['white', 'blue', 'purple', 'brown', 'black'] 

import library

If the library is the directory above, you can use the Jupyter add method to bring the library in. Next, import the module using the folder/filename/function name namespace created earlier.

Installation of third-party libraries

Third-party libraries can be installed using the pip install command. Note that the conda command (

/docs/user-guide/tasks/) is an optional alternative to the pip command. The pip command will also work well if you use the conda command, since pip is an alternative to the virtualenv virtual environment, but it can also install packages directly.

Install the pandas package.

pip install pandas

Alternatively, file installers are available.

> ca  
pylint 
pytest 
pytest-cov 
click 
jupyter 
nbval 
 
> pip install -r  

Here is an example of using small libraries in Jupyter Notebook. It's worth pointing out that it's easy to create giant cobwebs of program code in Jupyter Notebook, and a very simple solution would be to create some libraries, then test and import them.

"""This is a simple module""" 
 
import pandas as pd 
 
def list_of_belts_in_bjj(): 
 """Returns a list of the belts in Brazilian jiu-jitsu""" 
 
 belts = ["white", "blue", "purple", "brown", "black"] 
 return belts 
 
def count_belts(): 
 """Uses Pandas to count number of belts""" 
 
 belts = list_of_belts_in_bjj() 
 df = (belts) 
 res = () 
 count = ()[0] 
 return count 
from  import count_belts 
print(count_belts()) 
 
#exports:5 

resemble

Classes can be reused and interacted with in Jupyter Notebook. The simplest class type is a name, and classes are defined in the following form.

class Competitor: pass

The class can be instantiated into multiple objects.

class Competitor: pass 
conor = Competitor() 
 = "Conor McGregor" 
 = 29 
 = 155 
nate = Competitor() 
 = "Nate Diaz" 
 = 30 
 = 170 
def print_competitor _age(object): 
 """Print out age statistics about a competitor""" 
 
 print(f"{} is {} years old") 
print_competitor_age(nate) 
 
#exports:Nate Diaz is 30 years old
print_competitor_age(conor) 
 
#exports:Conor McGregor is 29 years old 

The Difference Between Classes and Functions

The main differences between classes and functions include:

  • functions are easier to interpret.
  • Functions (typically) have state only inside the function, while classes maintain unchanged state outside the function.
  • Classes can provide a higher level of abstraction at the cost of complexity.

summarize

To this point this article on Python's control structures: For, While, If ... of the article is introduced to this, more related Python control structures If, While, For content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future more!