菜鸟的学习之路-----Python中常用的语句

前言:我们学过C语言的都知道C语言中包含很多的语句,例如if-else选择结构,while循环,同样在Python中也有很多与之用法相似的语句,下面就由我来个给大家一一介绍。
1.学习第一弹------for循环
话不多说先举一个例子:求一个数的阶乘

res=1           
num=int(input('请输入你要算的阶乘的数字: '))
for i in range(1,num+1,1):  
    res*=i
print('%d!=%d' %(num,res))

执行结果:

在这里插入图片描述
在这里插入图片描述
##在写for循环的时候,为了跳出循环,常常要使用到break,continue,exit,他们之间的区别是什么呢
我们来举例来说明一下

for i in range(5):
    if i==3:
        #break
        continue
        print('I love you')
        #exit()

    print('I hate you')

在这里插入图片描述 根据上面的实验效果我们的出下面的结论

break:跳出整个循环,不会再循环后面的内容
continue:跳出本次循环,continue后面的代码不再执行,但是循环依然继续
exit():结束程序的运行
##for 循环练习1
“”"
有1,2,3,4四个数字
求这四个数字能生成多少互不相同且无重复数字的三位数(122,133)
“”"
count=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i !=j and j !=k and i!=k:
print(i100+j10+k)
count+=1
print(’%d’ %count)
在这里插入图片描述
##for循环练习2##
“”"
用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name=‘root’, passwd=‘beautiful’)
3. 登陆仅有三次机会, 如果超>过三次机会, 报错提示;

“”"

count=0
for i in range(1,4):
    Name=input('please input your username: ')
    Password=input('please input your password: ')
    if Name=='root' and Password=='beautiful':
     print('登陆成功!!')
     break
    else:
     print('登陆失败,你还有%d次机会' %(2-count))
     count+=1
else:
    print('登陆次数超过三次,请稍后再试!!!')
运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190322171013565.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190322171018873.png)
2.学习第二弹---------while循环
基本结构:
while 条件():
条件满足时,做的事情1
条件满足时,做的事情2

“”"
#1.定义一个变量,记录循环次数
i = 1

#2.开始循环
while i <= 3:
#循环内执行的动作
print(‘hello python’)
#处理计数器
i += 1
先来一个例子:先来讲一下死循环
while True:
print(‘I get it’)
条件为真,会一直循环下去;
经典案例:
在控制台连续输出五行%,每次依次递增:
%
% %
% % %
% % % %
% % % % %

i=1

while i <= 5:
j=1
while j <= i:
print(’%’,end=’’) ##打印并且输出不换行
j+=1
print(’’)
i+=1
在这里插入图片描述
换个方式:
%%%%%
%%%%
%%%
%%
%

    i=5
while i >=1:
    j=1
    while j <= i:
       print('%',end='')
       j+=1
    print('')
    i-=1

在这里插入图片描述
##while循环练习##
猜数字游戏
“”"

  1. 系统随机生成一个1~100的数字;

  2. 用户总共有5次猜数字的机会;

  3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;

  4. 如果用户猜测的数字小于系统给出的数字,打印"too small";

  5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退出循环;
    “”"

    import random

    trycount = 0
    computer = random.randint(1,100)
    while trycount < 5:
    player = int(input(‘Num:’))
    if player > computer:
    print(‘too big’)
    trycount += 1
    elif player < computer:
    print(‘too small’)
    trycount += 1
    else:
    print(‘恭喜,猜对了!!’)
    print(computer)
    break

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值