zoukankan      html  css  js  c++  java
  • if判断,while循环的使用

    1.猜年龄

    示例代码:

    user_lisa = 18   # 定义一个年龄
    count = 0  # 循环次数
    while count < 3:  # 循环的次数小于3次
        user = input('please your enter username:').strip()  # 用户输入,去两边空格
        if user.isdigit():  # 如果输入的是数字字符串的情况下
            user = int(user)  # 转换成整型
            if user == user_lisa:  # 用户输入的值和定义的值相等时,退出整个程序
                print('you got it')  
                exit()  
            elif user > user_lisa:  # 用户输入的值大于定义的值,提示输小点
                print('try smaller')  
            else:
                user < user_lisa   # 用户输入的值小于定义的值,提示输大点
                print('try bigger')
        else:
            print('try again')   # 如果用户输入的不是数字,提示重试
        count += 1   # 循环的次数自加1
    print('too many times') # 提示次数太多
    View Code

    2、用户登陆

    方法一:

    count = 0
    user_name = 'lisa'
    pwd = '123'
    while count <3:
        username =input('please enter your username:')
        password =input('please enter your password:')
        if username == user_name and password == pwd:
            while True:
                user_cmd = input('Please enter your cmd:').strip()
                print('The cmd is %s'%user_cmd)
                if user_cmd == 'q':
                    break
            break
        else:
            print('login failed')
        count += 1
    View Code

    方法二:

    count = 0
    user_name = 'lisa'
    pwd = '123'
    while count <3:
        username =input('please enter your username:')
        password =input('please enter your password:')
        if username == user_name and password == pwd:
            while True:
                user_cmd = input('Please enter your cmd:').strip()
                print('The cmd is %s'%user_cmd)
                if user_cmd == 'q':
                    exit()
        else:
            print('login failed')
        count += 1
    View Code

    3、使用while循环输出1、2、3、4、5、6、8、9、10

    # 使用while循环输出1、2、3、4、5、6、8、9、10
    count = 1       # 定义初始值
    while count < 11:  # 当count小于11时,执行以下代码
        if count == 7:  # 当count等于7时,count自加1,且退本次循环
            count += 1
            continue
        print(count) # 打印count的值
        count += 1 # count自加1
    View Code

    输出结果:

    1
    2
    3
    4
    5
    6
    8
    9
    10
    View Code
  • 相关阅读:
    mysql面试题
    Excel下载打不开
    Linux安装jdk1.8和配置环境变量
    Linux压缩、解压文件
    Linux常用命令1
    VMware下载安装及CentOS7下载安装
    ueditor的简单配置和使用
    linux的tomcat服务器上部署项目的方法
    TortoiseSVN客户端的使用说明
    CentOS 6.5系统上安装SVN服务器
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/7860691.html
Copyright © 2011-2022 走看看