Python基础知识-条件判断与循环

条件判断

条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
  • 如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
  • 如果 "condition_1" 为False,将判断 "condition_2"
  • 如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
  • 如果 "condition_2" 为False,将执行"statement_block_3"块语句

注意:
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。

1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。

if中常用的操作运算符
< 小于
<= 小于等于
> 大于
>= 大于等于
== 等于
!= 不等于

if条件语句可以多层嵌套使用,但是不建议太多层,影响代码阅读

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  ("你输入的数字不能整除 2 和 3")

注意:这段代码属于多行代码需要写到.py文件里,然后在命令行模式下运行。

循环

Python中的循环语句有 for 循环和 while循环

  • while循环
while 判断条件:
    语句
n = 100
 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 到 %d 之和为: %d" % (n,sum))
  • for循环
for 遍历元素 in 遍历体:
    执行代码
languages = ["C", "C++", "Perl", "Python"] 
for x in languages:
  print (x)

tips:break 语句,break 语句用于跳出当前循环体

languages = ["C", "C++", "Perl", "Python"] 
for x in languages:
  if x == 'C++':
    break
  print (x)

执行结果:C if条件成立,执行break,跳出循环,循环结束,只打印了'C'。

猜你喜欢

转载自blog.csdn.net/weixin_34401479/article/details/87530878