selfteaching / selfteaching/selfteaching-python-camp

Day03 if语句

Open
#303 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

学习素材分享
Dominant language
Python
Stars
151
Forks
875
PR merge metrics
No merged PRs in 30d

Description

今天作业中用到了if语句,通过学习,现将遇到的情况整理如下:
1、简单的if语句
只有一个测试条件,如果条件测试的结果为Ture,Python就会执行紧跟在if语句后的代码,if语句中,缩进的作用与for循环中相同,如果测试通过了,将执行if语句后面的所有缩进行的代码,否则将忽略他们。

age = 19
if age >=18:
    print("You are old enough!")

运行结果为:
You are old enough!
2、if-else语句
if-else语句块类似于if语句,但其中的else语句可以指定测试未通过时可以执行的操作,也就是说,条件通过了执行一个操作,没有通过执行另外一个操作。

age = 17
if age >=18:
    print("You are old enough!")
else:
    print("You are too young!")

运行结果:
You are too young!
3、if-elif-else语句
Python只执行if-elif-else结构中的一个代码块,它依次检查每个测试条件,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。

age = 12
if age < 4:
    price=0
elif age <18:
    price=5
else:
    price=10
print("Your ticket cost is $"+ str(price)+".")

运行结果:
Your ticket cost is $5.
4、省略else的语句
if-elif结构后的else并不一定要有,如果直到最终要测试的条件,就可以用elif代替else,这样,仅当满足相应的条件时,代码才会被执行。

age = 12
if age < 4:
    price=0
elif age <18:
    price=5
elif age <65:
    price=10
elif age >= 65:
    price=5
print("Your ticket cost is $"+ str(price)+".")

运行结果:
Your ticket cost is $5.
5、多个if
if-elif-else仅适用于只有一个条件满足的情况,遇到通过了的测试后,Python就会跳过余下的测试,但是当需要验证所有条件,且当多个条件为ture时需要执行相应的代码,就需要用多个if语句。

month = ['January','February','March']
if 'January' in month:
    print("Jan")
if 'February' in month:
    print("Feb")
if 'March' in month:
    print("Mar")
print("Three months passed!")

总结:如果只想执行一个代码块就用if-elif-else,如果要运行多个代码块,就使用一系类独立的if语句。

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue contains Chinese notes and Python examples about if, if-else, and if-elif-else statements, but names no documentation file, test, or requested change. First identify where this lesson belongs; done should mean the intended educational content is placed or corrected there with its examples preserved and clear output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.