[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-4":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":15,"prev_article":16,"next_article":20,"created_at":24},4,"Python条件语句","Python conditional statements","#### if语法\n\nPython条件语句是通过一条或多条语句的执行结果（True或者False）来决定执行的代码块。\n\n可以通过下图来简单了解条件语句的执行过程:\n\n![](https:\u002F\u002Fsecu","#### If syntax\n\nPython conditional statements are blocks of code that are executed based on the execution result of one or more statements (True or False).\n\nThe following figure can be used to briefly understand the execution process of conditional statements:","#### if语法\n\nPython条件语句是通过一条或多条语句的执行结果（True或者False）来决定执行的代码块。\n\n可以通过下图来简单了解条件语句的执行过程:\n\n![](https:\u002F\u002Fsecure2.wostatic.cn\u002Fstatic\u002FcgftHjFUdHRRCCpXB8bS4W\u002Fimage.png)\n\nPython程序语言指定任何非0和非空（null）值为true，0 或者 null为false。\n\nPython 编程中 if 语句用于控制程序的执行，基本形式为：\n\n```Python\nif 判断条件：\n    语句1……\nelse：\n    语句2……\n```\n\n语句1就是if判断条件成立所执行的语句\n\n那么判断条件不成立，就执行else下的语句2\n\n在python中，使用缩进来表示层级关系\n\n```Python\nif 5&gt;2:\n    print(\"条件成立\",\"执行语句1\")\nelse:\n    print('条件不成立',\"执行语句2\")\n# 条件成立 执行语句1 \n```\n\nif 语句的判断条件可以用&gt;（大于）、&lt;(小于)、==（等于）、&gt;=（大于等于）、&lt;=（小于等于）来表示其关系。\n\n当判断条件为多个值时，可以使用以下形式：\n\n```Python\nif 判断条件1:\n    执行语句1……\nelif 判断条件2:\n    执行语句2……\nelif 判断条件3:\n    执行语句3……\nelse:\n    执行语句4……\n```\n\n如下例：\n\n```Python\n# 根据分数判断等级\nscore = int(input(\"请输入你的成绩：\"))\nif score &gt;=60 and score &lt;80:\n    print(\"成绩及格\")\nelif score&gt;=80 and score &lt;90:\n    print(\"成绩良好\")\nelif score&gt;=90 and score &lt;=100:\n    print(\"成绩优秀\")\nelse:\n    print(\"成绩不及格\")\n    \n# 输入 50  输出成绩不及格\n# 输入 88  输出成绩良好\n```\n\n由于 python 并不支持 switch 语句，所以多个条件判断，只能用 elif 来实现，如果判断需要多个条件需同时判断时，可以\n\n1. 使用 or （或），表示两个条件有一个成立时判断条件成功\n2. 使用 and （与）时，表示只有两个条件同时成立的情况下，判断条件才成功。\n\n当if有多个条件时可使用括号来区分判断的先后顺序，括号中的判断优先执行\n\n此外 and 和 or 的优先级低于&gt;（大于）、&lt;（小于）等判断符号，即大于和小于在没有括号的情况下会比与或要优先判断\n\n---\n\n你也可以在同一行的位置上使用if条件判断语句和输出语句，如下：\n\n```Python\n# 根据分数判断等级\nscore = int(input(\"请输入你的成绩：\"))\nif score &gt;=60 and score &lt;80: print(\"成绩及格\")\nelif score&gt;=80 and score &lt;90: print(\"成绩良好\")\nelif score&gt;=90 and score &lt;=100: print(\"成绩优秀\")\nelse: print(\"成绩不及格\")\n    \n# 输入 50  输出成绩不及格\n# 输入 88  输出成绩良好\n```\n\n\n\n### if嵌套\n\n[Python](http:\u002F\u002Fc.biancheng.net\u002Fpython\u002F) 中，if、if else 和 if elif else 之间可以相互嵌套。因此，在开发程序时，需要根据场景需要，选择合适的嵌套方案。需要注意的是，在相互嵌套时，一定要严格遵守不同级别代码块的缩进规范。\n\n例如，在最简单的 if 语句中嵌套 if else 语句，形式如下：\n\n```Python\nif 表达式 1：\n  if 表示式 2：\n    代码块 1\n  else：\n    代码块 2\n```\n\n又或者，在 if else 语句中嵌套 if else 语句，形式如下：\n\n```Python\nif 表示式 1：\n    if 表达式 2：\n        代码块 1\n    else：\n        代码块 2\nelse：\n    if 表达式 3：\n        代码块 3\n    else：\n        代码块 4\n```\n\n【实例】判断是否为酒后驾车  \n如果规定，车辆驾驶员的血液酒精含量小于 20mg\u002F100ml 不构成酒驾；酒精含量大于或等于 20mg\u002F100ml 为酒驾；酒精含量大于或等于 80mg\u002F100ml 为醉驾。先编写 Python 程序判断是否为酒后驾车。\n\n![](https:\u002F\u002Fsecure2.wostatic.cn\u002Fstatic\u002Frr7YogJgXdUUAxz6V5N35B\u002Fimage.png)\n\n于是我们使用if嵌套来实现这个需求：\n\n```Python\nproof = int(input(\"输入驾驶员每 100ml 血液酒精的含量：\"))\nif proof &lt; 20:\n    print(\"驾驶员不构成酒驾\")\nelse:\n    if proof &lt; 80:\n        print(\"驾驶员已构成酒驾\")\n    else:\n        print(\"驾驶员已构成醉驾\")\n```\n\n又或者使用if嵌套改进我们的得分评判系统：\n\n```Python\nscore = int(input(\"请输入你的成绩：\"))\nif score &gt;= 60:\n    if score&gt;=80:\n        if score&gt;=90:\n            print(\"成绩优秀\")\n        else:\n            print(\"成绩良好\")\n    else:\n        print(\"成绩及格\")\nelse:\n    print(\"成绩不及格\")\n# 这次我们实现的是三重嵌套 \n```\n\n\n\n### 三目运算\n\nPython 可通过 if 语句来实现三目运算符的功能，因此可以近似地把这种 if 语句当成三目运算符。作为三目运算符的 if 语句的语法格式如下：\n\n```Python\nTrue_code if decide else False_code\n```\n\n三目运算符的规则是：先对逻辑表达式 expression 求值，如果逻辑表达式返回 True，则执行并返回 True_statements 的值；如果逻辑表达式返回 False，则执行并返回 False_statements 的值\n\n```Python\n条件成立执行语句1 if 条件 else 条件不成立执行语句2\n```\n\n看如下代码：\n\n```Python\na = 5\nb = 3\nst = \"a大于b\" if a &gt; b else  \"a不大于b\"\n# 输出\"a大于b\"\nprint(st)\n```\n\n如果只是需要在控制台看到结果，那我们可以这样写：\n\n```Python\na,b=3,5\nprint(f\"{a}&gt;{b}\") if a&gt;b else print(f\"{a}&lt;{b}\")\n# 3&lt;5\n```\n\n又或者是使用一个print语句\n\n```Python\na,b=5,3\nprint(f\"{a}&gt;{b}\" if a&gt;b else f\"{a}&lt;{b}\")\n```\n\n实例：使用三目运算符实现判断两个数字大小（实现if else 语句的效果）\n\n```Python\nx=int(input('请输入第一个数字'))\ny=int(input('请输入第二个数字'))\nif x&gt;y:\n    print(f'{x}大于{y}')\nelse:\n    print(f'{x}小于{y}')\n\n```\n\n```Python\n# 条件成立那里放前面，else语句下面就放后面\nx=int(input('请输入第一个数字'))\ny=int(input('请输入第二个数字'))\nprint(f'{x}大于{y}' if x&gt;y else f'{x}小于{y}') \n```\n\n我们同样可以使用如if嵌套的方法进行三目运算符嵌套，这样可以构成更加复杂的表达式。在嵌套时需要注意 if 和 else 的配对，例如：\n\n```Python\na if a&gt;b else c if c&gt;d else d\n# 理解为\na if a&gt;b else ( c if c&gt;d else d ) \n# 可以使用小括号\n\n```\n\n这是使用if else 在三个数字中输出最小的数\n\n```Python\na, b, c = -1, -5, 1\nif a &lt; b and a &lt; c:\n    print(a)\nelif b &lt; c and b &lt; a:\n    print(b)\nelse:\n    print(c)\n```\n\n如何用三目运算符进行实现？课后作业！\n\n```Python\na, b, c = -1, 2, 1\nprint(a if a &lt; b and a &lt; c else  b if b &lt; c and b &lt; a else c)\n\n```","#### If syntax\n\nPython conditional statements are blocks of code that are executed based on the execution result of one or more statements (True or False).\n\nThe following figure can be used to briefly understand the execution process of conditional statements:\n\n! [](https:\u002F\u002Fsecure2.wostatic.cn\u002Fstatic\u002FcgftHjFUdHRRCCpXB8bS4W\u002Fimage.png)\n\nThe Python programming language specifies that any non-0 and non-null values are true, and 0 or null is false.\n\nIn Python programming, if statements are used to control the execution of programs, and their basic form is:\n\n```Python\nif judgment condition:\nStatement 1......\nelse：\nStatement 2......\n```\n\nStatement 1 is the statement executed by the if-if judgment condition\n\nThen if the judgment condition is not true, execute statement 2 under else\n\nIn Python, indentation is used to represent hierarchical relationships\n\n```Python\nif 5>2:\nprint(\"condition holds\", \"execution statement 1\")\nelse:\nprint('condition not valid', \"execution statement 2\")\n# Condition Validation Execution Statement 1\n```\n\nThe judgment conditions of the if statement can be expressed as > (greater than), \u003C (less than), == (equal to), > = (greater than or equal), and \u003C = (less than or equal).\n\nWhen the judgment condition is more than one value, you can use the following form:\n\n```Python\nif judgment condition 1:\nExecution Statement 1......\nELIF judgment condition 2:\nExecution Statement 2......\nELIF judgment condition 3:\nExecution statement 3......\nelse:\nExecution Statement 4......\n```\n\nFor example:\n\n```Python\n# Grades are judged based on scores\nscore = int(input(\"Please enter your grade:\"))\nif score >=60 and score \u003C80:\nprint(\"Passing grade\")\nelif score>=80 and score \u003C90:\nprint(\"Good grade\")\nelif score>=90 and score \u003C=100:\nprint(\"Excellent\")\nelse:\nprint(\"Failed\")\n    \n# Input 50 outputs failed grades\n# Input 88 output is good\n```\n\nSince Python does not support switch statements, multiple conditional judgments can only be implemented with elif, if multiple conditions need to be judged at the same time\n\n1. Use or (or) to indicate that one of the two conditions is true, and the condition is judged to be successful\n2. When using and (and ), it means that the judgment condition is successful only when both conditions are true at the same time.\n\nWhen there are multiple ifs, parentheses can be used to distinguish the order of judgments, and the judgments in parentheses are executed first\n\nIn addition, the priority of and and or is lower than that of judgment symbols such as > (greater than) and \u003C (less than), that is, greater than and less than will be judged in the absence of parentheses\n\n---\n\nYou can also use the if condition judgment statement and the output statement on the same line, as follows:\n\n```Python\n# Grades are judged based on scores\nscore = int(input(\"Please enter your grade:\"))\nif score >=60 and score \u003C80: print\nelif score>=80 and score \u003C90: print(\"Good grade\")\nELIF score>=90 and score \u003C=100: print (\"Excellent\")\nelse: print(\"Failed\")\n    \n# Input 50 outputs failed grades\n# Input 88 output is good\n```\n\n\n\n### if nested\n\n[Python] (http:\u002F\u002Fc.biancheng.net\u002Fpython\u002F), if, if else, and if elif else can be nested with each other. Therefore, when developing a program, you need to choose the appropriate nesting scheme according to the needs of the scenario. It should be noted that when nesting with each other, you must strictly abide by the indentation specifications of code blocks at different levels.\n\nFor example, nest an if else statement in the simplest if statement with the following form:\n\n```Python\nif expression 1:\nif expression 2:\nCode block 1\nelse：\nCode block 2\n```\n\nAlternatively, nest an if else statement in an if else statement in the form of:\n\n```Python\nif expression 1:\nif expression 2:\nCode block 1\nelse：\nCode block 2\nelse：\nif expression 3:\nCode block 3\nelse：\nCode block 4\n```\n\nExample: Determine whether it is drunk driving\nIf it is stipulated that the blood alcohol content of the vehicle driver is less than 20mg\u002F100ml, it does not constitute drunk driving; the alcohol content is greater than or equal to 20mg\u002F100ml is drunk driving; the alcohol content is greater than or equal to 80mg\u002F100ml is drunk driving. First, write a Python program to determine whether it is drunk driving.\n\n! [](https:\u002F\u002Fsecure2.wostatic.cn\u002Fstatic\u002Frr7YogJgXdUUAxz6V5N35B\u002Fimage.png)\n\nSo we use if nesting to implement this requirement:\n\n```Python\nproof = int(input(\"Enter the driver's blood alcohol per 100ml:\"))\nif proof \u003C 20:\nprint(\"The driver does not constitute a drunk driving\")\nelse:\nif proof \u003C 80:\nprint(\"The driver has constituted a DUI\")\nelse:\nprint(\"The driver has constituted drunk driving\")\n```\n\nOr use if nesting to improve our scoring system:\n\n```Python\nscore = int(input(\"Please enter your grade:\"))\nif score >= 60:\nif score>=80:\nif score>=90:\nprint(\"Excellent\")\nelse:\nprint(\"Good grade\")\nelse:\nprint(\"Passing grade\")\nelse:\nprint(\"Failed\")\n# This time we are implementing triple nesting\n```\n\n\n\n### Trinocular Operations\n\nPython can implement the function of a trinocular operator through an if statement, so it can be roughly treated as a trinocular operator. The syntax format of an if statement as a trinocular operator is as follows:\n\n```Python\nTrue_code if decide else False_code\n```\n\nThe rules for the trinocular operator are: first evaluate the logical expression expression, if the logical expression returns True, execute and return a value of True_statements; if the logical expression returns False, execute and return a value of False_statements\n\n```Python\nCondition Valid Execution Statement 1 if Condition else Condition Not Valid Execution Statement 2\n```\n\nLook at the code below:\n\n```Python\na = 5\nb = 3\nst = \"a is greater than b\" if a > b else \"a is not greater than b\"\n# Output \"a is greater than b\"\nprint(st)\n```\n\nIf you just need to see the result in the console, then we can write something like this:\n\n```Python\na,b=3,5\nprint(f\"{a}>{b}\") if a>b else print(f\"{a}\u003C{b}\")\n# 3\u003C5\n```\n\nOr use a print statement\n\n```Python\na,b=5,3\nprint(f\"{a}>{b}\" if a>b else f\"{a}\u003C{b}\")\n```\n\nExample: Use the trinocular operator to determine the size of two numbers (realize the effect of the if else statement)\n\n```Python\nx=int(input('Please enter the first number'))\ny=int(input('Please enter the second number'))\nif x>y:\nprint(f'{x} greater than {y}')\nelse:\nprint(f'{x} less than {y}')\n\n```\n\n```Python\n# If the condition is true, put it in the front, and put it below the else statement\nx=int(input('Please enter the first number'))\ny=int(input('Please enter the second number'))\nprint(f'{x} greater than {y}' if x>y else f'{x} less than {y}')\n```\n\nWe can also use methods such as if nesting to nest the trinocular operator, which can form more complex expressions. When nesting, we need to pay attention to the pairing of if and else, for example:\n\n```Python\na if a>b else c if c>d else d\n# Understood as\na if a>b else ( c if c>d else d )\n# Parentheses can be used\n\n```\n\nThis is the smallest number of the three numbers output using if else\n\n```Python\na, b, c = -1, -5, 1\nif a \u003C b and a \u003C c:\nprint(a)\nelif b \u003C c and b \u003C a:\nprint(b)\nelse:\nprint(c)\n```\n\nHow to implement it with the trinocular operator? After-class homework!\n\n```Python\na, b, c = -1, 2, 1\nprint(a if a \u003C b and a \u003C c else  b if b \u003C c and b \u003C a else c)\n\n```","Python",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250712010832__【哲风壁纸】女孩-黑猫女孩.png",[11],false,{"id":17,"title":18,"title_en":19},3,"根据ip获取城市","Get the city according to IP",{"id":21,"title":22,"title_en":23},5,"python基础--循环语句","Python Basics - Loop Statements","2025-07-21T05:02:07+08:00"]