1. 程式人生 > >python3練習2

python3練習2

情況 use highlight light 繼續 sof int ons class

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