1. What is a conditional statement?
Python conditional statements are code blocks that are executed based on the execution results (True or False) of one or more statements.
2. if-else
Think about it:
When using if, it can only do what it needs to do when the conditions are met. So what should you do if you need to do something when the conditions are not met?
Answer: else
1. The usage format of if-else
if 条件: 满足条件时要做的事情1 满足条件时要做的事情2 ...(省略)... else: 不满足条件时要做的事情1 不满足条件时要做的事情2 ...(省略)...
2. Application
The following uses an example of buying a ticket to help everyone understand.
Result 1: There is a ticket.
chePiao = 1 # 用1代表有车票,0代表没有车票 if chePiao == 1: print("有车票,可以上火车") print("终于可以见到Ta了,美滋滋~~~") else: print("没有车票,不能上车") print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
Run result:
Result 2: Situation without ticket.
chePiao = 0 # 用1代表有车票,0代表没有车票 if chePiao == 1: print("有车票,可以上火车") print("终于可以见到Ta了,美滋滋~~~") else: print("没有车票,不能上车") print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
Result 2: Without ticket, running result:
三、elif
想一想:
if能完成当xxx时做事情
if-else能完成当xxx时做事情1,否则做事情2
如果有这样一种情况:当xxx1时做事情1,当xxx2时做事情2,当xxx3时做事情3,那该怎么实现呢?
答:elif
1. elif的使用格式如下
if xxx1: 事情1 elif xxx2: 事情2 elif xxx3: 事情3
说明:
- 当xxx1满足时,执行事情1,然后整个if结束。
- 当xxx1不满足时,那么判断xxx2,如果xxx2满足,则执行事情2,然后整个if结束。
- 当xxx1不满足时,xxx2也不满足,如果xxx3满足,则执行事情3,然后整个if结束。
- 当xxx1不满足时,xxx2也不满足,当xxx3不满足时....以此类推,直到整个if结束。
例:改变score的值对应不同的考试等级
score = 77 if score>=90 and score<=100: print('本次考级,等级为A') elif score>=80 and score<90: print('本次考试,等级为B') elif score>=70 and score<80: print('本次考试,等级为C') elif score>=60 and score<70: print('本次考试,等级为D') elif score>=0 and score<60: print('本次考试,等级为E')
运行结果:
2. 和else一起使用
if 性别为男性: 输出男性的特征 ... elif 性别为女性: 输出女性的特征 ... else: 第三种性别的特征 ...
代码说明:
- 当 “性别为男性” 满足时,执行 “输出男性的特征”的相关代码。
- 当 “性别为男性” 不满足时,如果 “性别为女性”满足,则执行 “输出女性的特征”的相关代码。
- 当 “性别为男性” 不满足,“性别为女性”也不满足,那么就默认执行else后面的代码,即 “第三种性别的特征”相关代码。
elif必须和if一起使用,否则出错。
4. Summary
This article is based on the basics of Python and introduces several common conditional judgment statements. Through the actual operation of small projects, we can better understand the conditional judgment statements. usage.
A detailed explanation of the difficulties encountered during the project practice and the points that need attention are given.
The above is the detailed content of Python basic conditional statements. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
