Python系列 21 分支结构

2021/7/1 17:38:57

本文主要是介绍Python系列 21 分支结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

分支结构

分支结构能够让计算机像人一样进行思考,应对不同的场景做出不同的回应。

Python中不支持switch语法,目前仅支持if/else形式,但是在Python3.10的测试版本中,貌似支持了switch语法,这里不做例举。

if

多条if语句出现会逐行进行判断,条件为真则执行其下的代码块,条件为假则略过:

if 条件判断:
    逻辑代码...
if 条件判断:
    逻辑代码...
if 条件判断:
    逻辑代码...

示例演示:

userAge = int(input("Please enter your age:"))
if userAge < 18:
    print("juvenile")
if userAge >= 18 and userAge < 30:
    print("youth")
if userAge >= 30 and userAge < 60:
    print("middle aged")
if userAge >= 60 and userAge < 80:
    print("elderly")
if userAge >= 80:
    print("Can still meal")

if/else

if代表如果怎样就怎样,else代表否则怎样就怎样。

一组if/else只会执行其中的一个。

以下是Python中if/else语法:

if 条件判断:
    逻辑代码...
else:
    逻辑代码...

示例演示:

userinput = input("Enter any character, determine if it is a numeric string:")
if userinput.isdigit():
    print("Is a digital string")
else:
    print("Not a digital string")

if/elif/else

多条if会按顺序依次执行,对每一条if语句都进行判定,而如果使用elif则只会从多条逻辑判定中取出最先为True的进行执行,后续的判定将不会被执行。

也就是说,if/elif/else三者只会执行一个。

语法使用如下:

if 条件判断:
    逻辑代码...
elif 条件判断: 
    逻辑代码...
elif 条件判断:
    逻辑代码...
else:
    逻辑代码

示例演示:

userAge = int(input("Please enter your age:"))
if userAge < 18:
    print("juvenile")
elif userAge < 30:
    print("youth")
elif userAge < 60:
    print("middle aged")
elif userAge < 80:
    print("elderly")
else:
    print("Can still meal")

三元表达式

三元表达式中有三个重要的元素:

  1. 条件是第一元素

  2. 条件成立返回的值是第二元素

  3. 条件不成立返回的值是第三元素

普通形式

如果只是一个简单if/else判定,我们可以将代码写在一行,语法如下:

<on_true> if <condition> else <on_false>

示例演示:

age = int(input("Please enter your age:")) 
result = "adult" if age >= 18 else "underage"
print(result)

其他形式

上面的三元表达式是最常见的一种,除此之外再介绍几种不常见的。

第二种,这种有一个BUG,不能区分0或者Fasle:

<condition> and <on_true> or <on_false>

如下所示,如果1大于0就返回0,否则返回False,但是第二种的返回的结果永远是False:

result = 1 > 0 and 0 or False
print(result)

# False

如果使用第一种,就不会有这样的问题:

result = 0 if 1 > 0 else False
print(result)

# False

第三种,语法如下:

(<on_false>, <on_true>)[condition]

示例如下:

age = int(input("Please enter your age:"))
result = ("underage", "adult")[age >= 18]
print(result)

第四种,语法如下:

{True: <on_true>, False: <on_false>}[<condition>]

示例如下:

age = int(input("Please enter your age:"))
result = {True: "adult", False: "underage"}[age >= 18]
print(result)

Python语法糖

链式比较

在Python中的判定支持一种链式比较,下面是常规的比较:

age = 13
if age > 12 and age < 18:
    print("juvenile")

通过链式比较进行简写:

age = 13
if 12 < age < 18:
    print("juvenile")

# eq: age > 12 and age < 18

获得布尔值

判定用户输入的是否为数字串,如果为数字串result变量为True,否则为False。

很多情况下,初学者可能会写出下面这种代码:

userInput = input("Please enter your age:")
result = None
if userInput.isdigit():
    result = True
else:
    result = False
print(result)

其实一行代码就可以搞定:

userInput = input("Please enter your age:")
result = bool(userInput.isdigit())
print(result)

或者你也可以使用另一种方式:

userInput = input("Please enter your age:")
result = userInput.isdigit() or False
print(result)

实例练习

输入一个数字,判断该数字是奇数还是偶数:

num = int(input("Enter a number: "))
if (num % 2) == 0:
    print("%s an even number" % num)
else:
    print("%s an odd number" % num)

输入一个年份,判断该年份是否是闰年?

year = int(input("Enter a year: "))
if (year % 4) == 0:
    if (year % 100) == 0:
        if (year % 400) == 0:
            print("%s is a leap year" % year)   # 整百年能被400整除的是闰年
        else:
            print("%s not is leap year" % year)
    else:
        print("%s is a leap year" % year)       # 非整百年能被4整除的为闰年
else:
    print("%s not is leap year" % year)

输入某年某月某日,判断这一天是这一年的第几天?

year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
sumInt = None

months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
if 0 < month <= 12:
    sumInt = months[month - 1]
else:
    print('data error')
sumInt += day

leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print('it is the %dth day.' % sum)


这篇关于Python系列 21 分支结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程