首页 > 代码库 > python3练习2

python3练习2

1:编写for循环,利用索引遍历出每一个字符    msg = ‘hello egon 666‘
msg = ‘hello egon 666‘
i = 0
for i in range(0, len(msg)):
    print(msg[i], end=‘,‘)
    i += 1

  

2:编写while循环,利用索引遍历出每一个字符  msg = ‘hello egon 666‘
msg = ‘hello egon 666‘
i = 0
while i < len(msg):
    print(msg[i], end=‘,‘)
    i += 1

  

3:msg = ‘hello alex‘  中的alex替换成66
msg = ‘hello alex‘
print(msg.replace(‘alex‘, ‘66‘))

  

    4:msg = ‘/etc/a.txt|365|get‘ 将该字符的文件名,文件大小,操作方法切割出来

msg = ‘/etc/a.txt|365|get‘
print(msg.split(‘|‘))

  

5.编写while循环,要求用户输入命令,如果命令为空,则继续输入
while True:
    cmd = input(‘cmd>>> ‘)
    if len(cmd) > 0:
        print(‘命令为:‘, cmd)
        break

6.编写while循环,让用户输入用户名和密码,如果用户为空或者数字,则重新输入
while True:
    name = input(‘username: ‘)
    if len(name) == 0:
        continue
    pwd = input(‘password:‘)
    break

7.编写while循环,让用户输入内容,判断输入的内容以alex开头的,则将该字符串加上_66结尾
while True:
    tips = input(‘tips: ‘)
    if tips.startswith(‘alex‘):
        tips = tips.replace(‘alex‘, ‘alex_66‘)
        print(tips)
        break

  

8.1.两层while循环,外层的while循环,让用户输入用户名、密码、工作了几个月、每月的工资(整数),用户名或密码为空,或者工作的月数不为整数,或者月工资不为整数,则重新输入

2.认证成功,进入下一层while循环,打印命令提示,有查询总工资,查询用户身份(如果用户名为alex则打印superuser,如果用户名为yuanhao或者wupeiqi,则打印normaluser,其余情况均打印unkownuser,退出功能

3.要求用户输入退出,则退出所有循环(使用tag的方式)

tag = True
while tag:
    user = input(‘username:‘)
    pwd = input(‘password:‘)
    work_mons = input(‘work_mons:‘)
    salary = input(‘salary:‘)
    if len(user) != 0 and len(pwd) != 0 and work_mons.isdigit() and salary.isdigit():
        print(‘登录成功!‘)
        print(‘1‘, ‘\n‘, ‘查询总工资‘)
        print(‘2‘, ‘\n‘, ‘查询用户身份‘)
        print(‘3‘, ‘\n‘, ‘退出登录‘)
        print(‘登录成功,请选择!‘)
        while tag:
            i = input(‘>>>‘)
            if i == ‘1‘:
                w = int(work_mons)
                sa = int(salary)
                s = sa * w
                print(‘总工资是:‘, s)
            elif i == ‘2‘:
                if user == ‘alex‘:
                    print(‘superuser‘)
                elif user == ‘yuanhao‘ or user == ‘wupeiqi‘:
                    print(‘normaluser‘)
                else:
                    print(‘unknown user‘)
            elif i == ‘3‘:
                tag = False
            else:
                print(‘输入错误,请输入有效选项‘)
                continue
    else:
        print(‘failure‘)

  

# 运行效果如下:
# user: egon
# password: 123
# work_mons: 12
# salary: 10000
#
# 1
# 查询总工资
# 2
# 查询用户身份
# 3
# 退出登录
#
# >>: 1
# 总工资是: 120000.0
#
# 1
# 查询总工资
# 2
# 查询用户身份
# 3
# 退出登录
#
# >>: 2
# unkown
# user
#
# 1
# 查询总工资
# 2
# 查询用户身份
# 3
# 退出登录
#
# >>: 3

python3练习2