Python 决策、循环

决策和循环

几乎所有稍微复杂的程序都有决策功能,决策功能有一个特殊的叫法:控制结构。
控制结构决定计算机向左转还是向右转,换言之,就是决定继续处理数据集还是退出循环。

  • 比较运算符 ==、<、>、!=、<=
def is_even(n):
	remainder=n%2           #取余运算
	if remainder==0:        #注意冒号
		print('n is even.')
  • 布尔运算 and、or 和 not
    age=int(input('Enter your age:'))
    if age>12 and age<20:      #注意冒号
    	print('Wow! You are a teenager.')
  • if 条件语句
def check_range(n):
    if n<1:
        print('n is below the range 1 to 100.')
    elif n<101:       #可以并用多个elif
        print('n is inside the range.')
    else:             #限用一个else
        print('n is above the range 1 to 100.')
  • while 循环语句
n=1
while n<=10:          #当n大于10时退出循环。
	print(n,end=' ')  #指定打印末尾输出字符
	n+=1
  • break语句

    运行后跳出循环。

import random
n=random.randint(1,50)	#生成随机数
while True:				#借助 break 跳出循环
    ans=int(input('Enter your guess:'))
    if ans==n:
        print('Success!You win!')
        break
    elif ans>n:
        print('Too high.')
    else:				#记得冒号
        print('Too low.')

综合运用

  1. 计算阶乘
n=int(input('Enter value of n:'))
prod=i=1                #数值初始化
while i<=n:
    prod*=i
    i+=1
print('The factorial is:',prod)
  1. 打印斐波那契数列
a=b=1              #程序的简洁得益于独特的Python语法
while a<200:
	a,b=a+b,a
	print(a,end=' ')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值