第六章第2讲:条件与循环(1)

 

1.python中的缩进,其控制代码块的开始与结束

names = ["Alice","Bela"]
if "Alice" in names:
#print(True) # 如果缩进没有,运行时该行会保错
    print(True)
else:
    print(False)

2.比较运算符

num1 = int(input("Enter your first number:"))
num2 = int(input("Enter your first number:"))
if num1 < num2:
    print(num1,"<",num2)
if num1 > num2:
    print(num1,">",num2)
if num1 == num2:
    print(num1,"=",num2)
if num1 != num2:
    print(num1, "!=", num2)

结果:

Enter your first number:34
Enter your first number:4
34 > 4
34 != 4

 3.if-elseif-else

num1 = int(input("Enter your first number:"))
if num1 >= 10:
    print(num1,">=10")
elif num1 >= 5:
    print("5<",num1,"<10")
elif num1 >= 1:
    print("1<",num1,"<5")
else:
    print(num1,"<=0")

结果:

Enter your first number:-3
-3 <= 0

 4.多条件测试

     if的格式:

  if条件:

    代码块

  else:

    代码块

 

# 多条件测试
age = int(input("Enter your age:"))
grade = int(input("Enter your grade:"))
if age >=18:
    if grade >= 12:
        print("You can play this game!")
    else:
        print("sorry,you can't play this game!")
else:
    print("sorry,your age <=18! You can't play this game!")

# 多条件测试(推荐使用如下方式)
age = int(input("Enter your age:"))
if age >=18:
    grade = int(input("Enter your grade:"))
    if grade >= 12:
        print("You can play this game!")
    else:
        print("sorry,you can't play this game!")
else:
    print("sorry,your age <=18! You can't play this game!")

 5. and 、or、not

# and
age = int(input("Enter your age:"))
grade = int(input("Enter your grade:"))
if age >=18 and grade >= 12:
    print("You can play this game!")
else:
    print("sorry,your age <=18! You can't play this game!")

# or
age = int(input("Enter your age:"))
grade = int(input("Enter your grade:"))
if age >=18 or grade >= 12:
    print("You can play this game!")
else:
    print("sorry,your age <=18! You can't play this game!")

# not
age = int(input("Enter your age:"))
if not(age < 18):
    grade = int(input("Enter your grade:"))
    if grade >= 12:
        print("You can play this game!")
    else:
        print("sorry,you can't play this game!")
else:
    print("sorry,your age <=18! You can't play this game!")

 

posted @ 2019-06-26 07:12  Ling_07  阅读(149)  评论(0编辑  收藏  举报