首页 > 代码库 > Python:条件判断

Python:条件判断

条件控制:if...elif...else

if condition_1:        statement_1elif condition_2:        statement_2else:        statement_3

判断过程:

如果"condition_1"为 True 将执行"statement_1"块语句 ?如果"condition_1"为False,将判断"condition_2"如果"condition_2"为 True 将执行"statement_2"块语句 ?如果"condition_2"为False,将执行"statement_3"块语句

例1:

num = int(input("输入一个数字:"))if num % 2 == 0:        if num % 3 == 0:                print(输入的数字既能整除2也能整除3)        else:                print(输入的数字只能整除2,不能整除3)else:        if num % 3 ==  0:                print(输入的数字只能整除3,不能整除2)        else:                print(输入的数字既不能整除3,也不能整除2)

输出结果:

please input a number:9这个数只能整除3,不能整除2

 

例2:猜幸运数字游戏

lucky_num = 7input_num = -1guess_num = 0while lucky_num != input_num and guess_num < 3:    print(Number:,guess_num)    input_num = int(input(input a number:))    if input_num > lucky_num:        print("it‘s too big !!!")    elif input_num < lucky_num:              print("it‘s too small !!!")    guess_num += 1if lucky_num == input_num:     print(binggo)else:    print(too many retrs!!!)

输出结果:

input a number:6its too small !!!Number: 1input a number:9its too big !!!Number: 2input a number:8its too big !!!Number: 3too many retrs!!!
#再玩一次!input a number:8its too big !!!Number: 1input a number:7Number: 2binggo

 

Python:条件判断