Getting started with Python Basics_ 3 conditional statements and iterative loops

lc013 2021-09-15 08:41:48
getting started python basics_ basics


Python The first two chapters of Basics :

  • Python Basic introduction – Introduction and environment configuration
  • Python Basic introduction _2 Basic syntax and variable types

This is the third content , It mainly introduces conditional statements and iterative loop statements , The content is also relatively simple , Directory as follows :

Python Basic introduction _3 Conditional statements and iterative loops _Python


Conditional statements and iterative loops

1. Conditional statements

Python A conditional statement is the result of the execution of one or more statements ( Judge True perhaps False) To determine the code block to execute .

On the whole, it can be divided into four statements :

  • if sentence
  • if-else sentence
  • if-elif-else sentence
  • Nested statement ( Multiple if sentence )
if sentence

Given a binary condition , Execute the statement if the condition is met A, If you are not satisfied, skip , The code example is as follows :

a = 3
# if sentence 
if a > 0:
print('a =', a)

  • 1.
  • 2.
  • 3.
  • 4.
if-else sentence

Also given the binary condition , Execute the statement if the condition is met A, The execution statement... Is not satisfied B, The code example is as follows :

a = 3
# if-else
if a > 2:
print('a is ', a)
else:
print('a is less 2')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
if-elif-else sentence

Given multivariate conditions , Meet the conditions 1, Execute statement 1, Meet the conditions 2, Execute statement 2, By analogy , A simple code example is as follows :

a = 3
# if-elif-else
if a > 5:
print('a>5')
elif a > 3:
print('a>3')
else:
print('a<=3')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
Nested statement

Nested statements can contain more if sentence , Or is it if-else 、if-elif-else The sentence of , A simple code example is shown below :

a = 3
# Nested statement 
if a < 0:
print('a<0')
else:
if a > 3:
print('a>3')
else:
print('0<a<=3')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

2. Iteration loop

Python There are mainly two kinds of circular statements in ,while Circulation and for loop , And then there was no do-while loop .

while loop

A simple while The cycle is as follows ,while The termination condition of the loop is while The following statement does not satisfy , That is to say False When , The following code example is when n=0 When , It will exit the loop .

n = 3
while n > 0:
print(n)
n -= 1

  • 1.
  • 2.
  • 3.
  • 4.

Another example , When used for input, let the user constantly input content , Until a certain condition is met , sign out .

promt = "\ninput something, and repeat it."
promt += "\nEnter 'q' to end the program.\n"
message = ""
while message != 'q':
message = input(promt)
print(message)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
for loop

for Loops can explicitly define the number of cycles , And often used in lists 、 Traversal of dictionaries, etc . A simple example is as follows :

# for
l1 = [i for i in range(3)]
for v in l1:
print(v)

  • 1.
  • 2.
  • 3.
  • 4.

The above example is actually used twice for loop , The first is used to generate a list from a list derivation l1 , And it's using range function , The specified number of cycles is 3 Time , The second time is used to traverse the list .

about range function , There are also the following usages :

l2 = ['a', 'b', 'c', 'dd', 'nm']
# Specify the interval 
for i in range(2, 5):
print(i)
# Specify the interval , And add a step of 10
for j in range(10, 30, 10):
print(j)
# combination len To traverse the list 
for i in range(len(l2)):
print('{}: {}'.format(i, l2[i]))

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

in addition , For the loop of the list , Sometimes you want to print the value and index value of the current element at the same time , May adopt enumerate function , A firm example is as follows :

l2 = ['a', 'b', 'c', 'dd', 'nm']
for i, v in enumerate(l2):
print('{}: {}'.format(i, v))

  • 1.
  • 2.
  • 3.
break and continue And... In loop statements else sentence

break Statement is used to terminate a loop statement , Examples are as follows :

# break
for a in range(5):
if a == 3:
break
print(a)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

This is what if a = 3 , It will end for Loop statement .

continue Used to skip the current loop , Enter the next cycle , Examples are as follows :

# continue
for a in range(5):
if a == 3:
continue
print(a)

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Loop statements can have else Clause , It's exhausting the list ( With for loop ) Or the condition becomes false ( With while loop ) Causes the loop to terminate when executed , but Cyclic quilt break Do not execute on termination . Examples are as follows :

# else
for a in range(5):
print(a)
else:
print('finish!')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Reference resources

  • 《Python Programming from entry to practice 》
  • Python Basic course
  • One day quick start python
  • Super easy to understand Python Entry level tutorial , Hurry to collect !

Summary

This article is mainly a simple arrangement of Python The usage of conditional statements and loop statements .

Besides , The code of this article is uploaded to my github Yes :

https://github.com/ccc013/Python_Notes/tree/master/Practise

Welcome to my WeChat official account. – Machine learning and computer vision , Or scan the QR code below , Let's talk , Learning and progress !

Python Basic introduction _3 Conditional statements and iterative loops _github_02

 

版权声明
本文为[lc013]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/09/20210909141403060T.html

  1. Take you to learn more about nginx basic login authentication: generating passwords using Python
  2. 超硬核Python避坑学习方案奉上!入门到就业一篇就搞定!
  3. Talk about how JMeter executes Python scripts concurrently
  4. Talk about how JMeter executes Python scripts concurrently
  5. Talk about how JMeter executes Python scripts concurrently
  6. python内置函数通过字符串的方式来执行函数代码块,类似java的反射机制相当强大!
  7. python内置函数通过字符串的方式来执行函数代码块,类似java的反射机制相当强大!
  8. python內置函數通過字符串的方式來執行函數代碼塊,類似java的反射機制相當强大!
  9. Les fonctions intégrées Python exécutent des blocs de code de fonction à travers des chaînes, et les mécanismes de réflexion comme Java sont assez puissants!
  10. Python module 1
  11. Python tip: use namedtuple instead of manually created classes
  12. Python - poetry(3)配置项详解
  13. Python - poetry(3)配置项详解
  14. Python - poetry(3)配置項詳解
  15. Python - poetry(3)配置項詳解
  16. Python - détails de l'élément de configuration Poetry (3)
  17. Python - détails de l'élément de configuration Poetry (3)
  18. Python案例实战,pygame模块,Python实现字母代码雨
  19. Python calculation vector angle code
  20. Python基础面试题解读|《Python面试100层》|第1层
  21. 面对小白的pandas命令手册+练习题【三万字详解】
  22. 面對小白的pandas命令手册+練習題【三萬字詳解】
  23. Face au Manuel de commande pandas de Xiaobai + question d'exercice [30 000 mots pour plus de détails]
  24. Interprétation des questions d'entrevue de base Python | 100 couches d'entrevue Python | couche 1
  25. Python data structure and algorithm (17) -- merge sort
  26. Les fonctions intégrées Python exécutent des blocs de code de fonction à travers des chaînes, et les mécanismes de réflexion comme Java sont assez puissants!
  27. Python笔记-uiautomator2截图点击,OpenCV找图
  28. Python文档阅读笔记-OpenCV中Template Matching
  29. Python笔记-利用OpenCV的matchTemplate屏幕找图并使用pyautogui点击
  30. Python筆記-利用OpenCV的matchTemplate屏幕找圖並使用pyautogui點擊
  31. Notes python - utilisez l'écran matchtemplate d'OpenCV pour trouver des images et cliquez sur
  32. Notes de lecture de documents python - Matching de modèles dans OpenCV
  33. Notes python - capture d'écran de l'automate 2 Cliquez pour ouvrir la vue
  34. python链接云服务器的mysql8
  35. python鏈接雲服務器的mysql8
  36. Mysql8 pour les serveurs Cloud liés Python
  37. Python资源大集合,要的话可以拿走!
  38. ️万字【Python基础】保姆式教学️,小白快速入门Python!
  39. ️萬字【Python基礎】保姆式教學️,小白快速入門Python!
  40. Wanzi [base Python] Baby - sitting Teaching, Little White Quick Start Python!
  41. Realizing the function of sending e-mail automatically with Python
  42. Smtpauthenticationerror in Python: solution
  43. 8 steps to teach you how to solve Sudoku in Python! (including source code)
  44. Python change la vie | identifier facilement des centaines de numéros de livraison
  45. Python change life | utilisation de modèles reconnus par ocr
  46. Bibliothèques Python utiles et intéressantes - - psutil
  47. 3. Traitement des données pandas
  48. 【Python编程基础】控制流之链式比较运算符
  49. MFC uses Python scripting language
  50. 【Python編程基礎】控制流之鏈式比較運算符
  51. 【 base de programmation python】 opérateur de comparaison de chaîne pour le flux de contrôle
  52. Python game development, pyGame module, python implementation of Xiaole games
  53. Mise en œuvre du Code de vérification unique (OTP) avec le cadre de repos Django
  54. Python - eval ()
  55. Python - Programmation orientée objet - _Rapport()
  56. Différence entre python - rep (), Str ()
  57. Python - Programmation orientée objet - _Appel()
  58. Python calling matlab script
  59. Python - Programmation orientée objet - _Nouveau() et mode Singleton
  60. Python - Programmation orientée objet - méthode magique (méthode de double soulignement)