pytthon基础第一天——if判断、while循环、for循环、python字符串

本文通过三个具体实例介绍Python编程技巧:猜年龄游戏、用户登录验证及循环输出特定序列。涉及基本输入输出、条件判断、循环控制等核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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') # 提示次数太多

 

 

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

方法二:

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

 

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

输出结果:

1
2
3
4
5
6
8
9
10
View Code

 

转载于:https://www.cnblogs.com/yujiemeigui/p/7860691.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值