Starfruit Python Advanced Lecture 7-Conditional Judgment

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

 

This part of the content has been discussed in Chapter 6 of the Basic Tutorial: Python Control Structure (1) if statement, now we will discuss this if statement in depth.

7.1 Whether to judge

The simplest judgment results are only "yes" and "no". For example: Beijing is the capital of China, and nothing else is the capital of China.

Then in Python programming, we can use an if-else.

#是否判断
city = input("Please input:")
if city == "北京":
	print(city+"是中国的首都")
else:
	print(city+"不是中国的首都")

运行结果:
Please input:北京
北京是中国的首都

Please input:上海
上海不是中国的首都

It should be noted that Python's if statement is only executed when the condition before the colon is True. If it is not a judgment statement, it is possible to force the variable before the colon to be specified as True, for example:

#if的True条件:
s = True
t = False
if s:
	print("真")
else:
	print("假")
if t:
	print("真")
else:
	print("假")
if not t:
	print("真")
else:
	print("假")

运行结果:
真
假
真

7.2 Enumeration judgment

Sometimes our judgment conditions are not only "yes" or "no". For example, an old lady watches a certain TV station on time every night at 20:00, as shown in the following table:

date TV show
Monday Program A
Tuesday Program B
Wednesday Program C
Thursday Program D
Friday Program E
on Saturday Program F
on Sunday Program G

We can see from the table that the old lady at 20:00 on Monday was watching program A, so what program was not watching on Monday? We cannot use simple "yes" or "no" anymore.

Python provides us with if-elif-else to express this enumeration judgment. The code is as follows:

s = input("请输入今天是星期几[只能输入1到7之间的数字]:")
if s == '1':
	print("今晚是节目A")
elif s == '2':
	print("今晚是节目B")
elif s == '3':
	print("今晚是节目C")
elif s == '4':
	print("今晚是节目D")
elif s == '5':
	print("今晚是节目E")
elif s == '6':
	print("今晚是节目F")
elif s == '7':
	print("今晚是节目G")
else:
	print("输入错误!")

运行结果:
请输入今天是星期几[只能输入1到7之间的数字]:3
今晚是节目C
请输入今天是星期几[只能输入1到7之间的数字]:7
今晚是节目G
请输入今天是星期几[只能输入1到7之间的数字]:a
输入错误!

As you can see from the code, we put 7 normal situations in the if-elif statement, and put the exception statement in the else statement. This is a common processing method.

7.3 Conditions and and or

When we were young, we all heard my parents say: If you got 90 points in this exam and the weather is good on Sunday, I will take you to the playground. You happen to be a school bully, and it's easy to get 90 points, thinking haha, you can play again on Sunday! But Heavenly Father doesn't make beauty, it rains heavily on Sunday, and the plan is over ...

Now we use the if statement to write this situation:

#条件与
s = int(input("考试成绩是[请输入0到100的整数]:"))
t = input("星期天天气是[只能输入好或者不好]:")
if s >= 90 and t == "好":
	print("去游乐场玩!")
else:
	print("不能去游乐场玩!")

运行结果:
考试成绩是[请输入0到100的数字]:92
星期天天气是[只能输入好或者不好]:好
去游乐场玩!
考试成绩是[请输入0到100的整数]:88
星期天天气是[只能输入好或者不好]:好
不能去游乐场玩!
考试成绩是[请输入0到100的整数]:93
星期天天气是[只能输入好或者不好]:不好
不能去游乐场玩!
考试成绩是[请输入0到100的整数]:82
星期天天气是[只能输入好或者不好]:不好
不能去游乐场玩!

It can be seen that only if the score is greater than or equal to 90 points and the weather is both satisfied, the statement after the if can be executed. As long as one condition is not met, the else statement is executed. This is the role of the logical conditional symbol And. The two conditions A and B must be both true to return true, otherwise they both return false.

If your mom and dad are in a good mood, say this: as long as you scored 90 points or the weather is good on Sunday, let ’s go to the indoor playground! The if statement now becomes:

#条件或
s = int(input("考试成绩是[请输入0到100的整数]:"))
t = input("星期天天气是[只能输入好或者不好]:")
if s >= 90 or t == "好":
	print("去室内游乐场玩!")
else:
	print("不能去室内游乐场玩!")
运行结果:
考试成绩是[请输入0到100的整数]:92
星期天天气是[只能输入好或者不好]:好
去室内游乐场玩!
考试成绩是[请输入0到100的整数]:87
星期天天气是[只能输入好或者不好]:好
去室内游乐场玩!
考试成绩是[请输入0到100的整数]:93
星期天天气是[只能输入好或者不好]:不好
去室内游乐场玩!
考试成绩是[请输入0到100的整数]:85
星期天天气是[只能输入好或者不好]:不好
不能去室内游乐场玩!

It can be seen that the statement after the if is executed only if the two conditions of score greater than or equal to 90 points and good weather are met, and the else statement is executed only when both conditions are not met. This is the role of the logical conditional character Or. As long as one of the two conditions A or B is true, it returns true.

Logical conditioners can be nested and used, such as (A and B) or (C and D). The sequence is to judge the result of each layer from the inside out, and then use this result to judge the result of the next layer.

7.4 Size judgment and multiple judgment

Comparing the size of two numbers, there are 6 cases of> (greater than),> = (greater than or equal to), <(less than), <= (less than or equal to), == (equal to),! = (Not equal to), we can Continue to use if-elif-else to express these situations. For the reason why you need to add float before the input () function and str before the score in the print, please refer to the explanation in the previous section.

#大小判断举例1
score = float(input("Please input:"))
if score > 60:
	print("考试成绩是:"+str(score)+"分,及格")
elif score == 60:
	print("考试成绩是:"+str(score)+"分,刚好及格")
else:
	print("考试成绩是:"+str(score)+"分,不及格")

运行结果:
Please input:85.5
考试成绩是:85.5分,及格
Please input:60
考试成绩是:60.0分,刚好及格
Please input:58.5
考试成绩是:58.5分,不及格

But in fact, such program logic is not rigorous, you can enter any character after the input prompt of Please input :.

If a character a is entered, how does the program handle it?

Please input:a
Traceback (most recent call last):
  File "a.py", line 1, in <module>
    score = float(input("Please input:"))
ValueError: could not convert string to float: 'a'

We see that the program reported an error because the character a cannot be converted to a floating-point number. You may have thought of adding else judgment, but this is more complicated than the 7.2 example. We will do the following analysis:

Step 1, we want to make sure that the input is a number;

The second step, the number must be between 0 and 100, in this case we can use the procedure of the size judgment example 1

For the first step we further decompose:

1.1 If the input characters are all numbers 0-9, it is a legal number

1.2 If the input character contains a decimal point, then only one decimal point may be a number

Judging after removing the decimal point, it is divided into two cases:

1.2.1 If the first character is a negative sign, all numbers starting from the second character are 0-9, which is a legal number

1.2.2 If the first character is not a minus sign, all characters are numbers 0-9, it is a legal number

Write the code for the judgment conditions of the first step as follows:

#判断输入的是否是数字
s = input("Please input:")
#取输入的小数点个数
dot = s.count('.')
#如果没有小数点或者只有1个小数点
if dot == 0 or dot == 1:
	#即去掉小数点
	new_s = s.replace('.','')
	#如果第一个字符不是负号
	if new_s[0] != '-':
		#去掉小数点之后的字符全部是0-9的数字,才是合法数字
		if new_s.isdigit():
			print(s+"是合法数字!")
		else:
			print(s+"不是合法数字!")
	#如果第一个字符是负号
	else:
		#从第二个字符开始的字符全部是0-9的数字,才是合法数字
		if new_s[1:].isdigit():
			print(s+"是合法数字!")
		else:
			print(s+"不是合法数字!")
#如果小数点多于1个,不是合法数字
else:
	print(s+"不是合法数字!")

运行结果:
Please input:96
96是合法数字!
Please input:0.33
0.33是合法数字!
Please input:0.33.333
0.33.333不是合法数字!
Please input:-5.26
-5.26是合法数字!
Please input:as87j
as87j不是合法数字!
Please input:9.rt
9.rt不是合法数字!

Why bother to do so many judgment statements, is to filter out the user's erroneous input to the greatest extent, and avoid throwing exceptions directly by Python.

Then we add the judgment statement of whether the number is qualified in the case of legal numbers. The complete code is as follows:

#学生考试成绩分类
s = input("Please input:")
#取输入的小数点个数
dot = s.count('.')
#如果没有小数点或者只有1个小数点
if dot == 0 or dot == 1:
    #即去掉小数点
    new_s = s.replace('.','')
    #如果第一个字符不是负号
    if new_s[0] != '-':
        #去掉小数点之后的字符全部是0-9的数字,才是合法数字
        if new_s.isdigit():
            print(s+"是合法数字!")
            if float(s) >= 60 and float(s) <= 100:
                print("考试成绩是:"+str(s)+"分,及格")
            elif float(s) < 60 and float(s) >= 0:
                print("考试成绩是:"+str(s)+"分,不及格")
            else:
                print("但是"+s+"不是合法成绩!")
        else:
            print(s+"不是合法数字!")
    #如果第一个字符是负号
    else:
        #从第二个字符开始的字符全部是0-9的数字,才是合法数字
        if new_s[1:].isdigit():
            print(s+"是合法数字!")
            if float(s) >= 60 and float(s) <= 100:
                print("考试成绩是:"+str(s)+"分,及格")
            elif float(s) < 60 and float(s) >= 0:
                print("考试成绩是:"+str(s)+"分,不及格")
            else:
                print("但是"+s+"不是合法成绩!")
        else:
            print(s+"不是合法数字!")
#如果小数点多于1个,不是合法数字
else:
    print(s+"不是合法数字!")

运行结果:
Please input:120
120是合法数字!
但是120不是合法成绩!
Please input:96
96是合法数字!
考试成绩是:96分,及格
Please input:56.7
56.7是合法数字!
考试成绩是:56.7分,不及格
Please input:0.0
0.0是合法数字!
考试成绩是:0.0分,不及格
Please input:-3.2
-3.2是合法数字!
但是-3.2不是合法成绩!
Please input:60
60是合法数字!
考试成绩是:60分,及格

to sum up:

if-else is whether to judge.

if-elif-else is an enumeration judgment.

The two conditions A and B must be both true to return true; as long as one of the two conditions A or B is true, it returns true.

When comparing numbers, pay attention to whether the compared values ​​are legal, and multiple judgments are needed to remove the illegal values.

 

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

If you think this chapter is helpful to you, welcome to follow, comment and like! Github welcomes your Follow and Star!

Published 55 original articles · won praise 16 · views 6111

Guess you like

Origin blog.csdn.net/yty_7/article/details/104365245