第1章 Python基礎-Python介紹&循環語句 練習題&作業


1.簡述編譯型與解釋型語言的區別,且分別列出你知道的哪些語言屬於編譯型,哪些屬於解釋型?

高級語言分為編譯型與解釋型兩種,分別從執行速度、開發效率、跨平台性三個方面說它們的區別。
編譯型語言因為執行的是機器碼文件,所以執行速度快且不依賴解釋器,但每次修改源代碼都需要重新編譯,所以導致開發效率低,不同的操作系統,調用的底層機器指令不同,所以跨平台性差。
解釋型語言需要解釋器邊把源文件解釋成機器指令邊交給cpu執行,所以執行速度要比編譯型慢很多,但是每次修改時立刻見效,所以開發效率很高,解釋器已經做好了對不同操作系統的交互處理,天生跨平台。
C/C++/C#/Delphi/Go屬於編譯型,PHP/Java/JavaScript/Python/Perl/Ruby屬於解釋型。 

2.執行 Python 腳本的兩種方式?

(1).交互方式:啟動python解釋器,執行命令
(2).腳本方式:Python xxx.py 或者 chmod +x xxx.py && ./xxx.py

3.Python單行注釋和多行注釋分別用什么?

單行注釋:#要注釋內容
多行注釋:"""要注釋內容""" 或者'''要注釋內容'''

4.聲明變量注意事項有哪些?

(1).變量由數字、字母和下划線組成
(2).變量不能以數字開頭
(3).變量不能使用Python關鍵字
(4).變量區分大小寫
     模塊名,包名 :小寫字母, 單詞之間用_分割。
     類名:首字母大寫。
     全局變量: 大寫字母, 單詞之間用_分割。
     普通變量: 小寫字母, 單詞之間用_分割。
     函數: 小寫字母, 單詞之間用_分割。
     實例變量: 以_開頭,其他和普通變量一樣 。
     私有實例變量(外部訪問會報錯): 以__開頭(2個下划線),其他和普通變量一樣 。
     專有變量: __開頭,__結尾,一般為python的自有變量(不要以這種變量命名)。

5.如何查看變量在內存中的地址?

id(變量名)

6.寫代碼

a. 實現用戶輸入用戶名和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗!

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import getpass
_username = "seven"
_password = "123"

username = input("username:")
password = getpass.getpass("password:")

if username == _username and password == _password:
    print("hello,seven")
else:
    print("error,input again")

b. 實現用戶輸入用戶名和密碼,當用戶名為 seven 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import getpass
_username = "seven"
_password = "123"
count = 0
while count < 3:
    count += 1
    username = input("username:")
    password = getpass.getpass("password:")

    if username == _username and password == _password:
        print("hello,seven")
        break
    else:
        print("error,input again")
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import getpass
_username = 'seven'
_password = '123'
count = 0
def login():
    username = input('username:')
    password = getpass.getpass('password:')
    return username,password
while count<3:
    username,password = login()
    if username == _username and password == _password:
        print('hello,seven')
        break
    else:
        count += 1
        print ('error,input again')

c. 實現用戶輸入用戶名和密碼,當用戶名為 seven 或 alex 且 密碼為 123 時,顯示登陸成功,否則登陸失敗,失敗時允許重復輸入三次

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import getpass
_username = ['seven','alex']
_password = "123"
count = 0
while count < 3:
    count += 1
    username = input("用戶名:")
    # password = input("密碼:")
    password = getpass.getpass("密碼:")

    if username in _username and password == _password:
        print("登陸成功!")
        break
    else:
        print("登陸失敗!")

7.寫代碼

a. 使用while循環實現輸出2-3+4-5+6...+100 的和

# 2+4+6...+100
# -3-5...-99

count = 1
sum = 0
while count < 100:
    count += 1
    if count % 2 == 0 :
        sum += count
    else:
        sum -= count
print(sum)
sum = 0
for count in range(2,101):
    # print(count)
    if count % 2 == 0 :
        sum += count
    else:
        sum -= count
print(sum)

b. 使用 while 循環實現輸出 1,2,3,4,5, 7,8,9, 11,12

count = 0
while count <= 12:
    if count == 6 or count == 10:
        pass # 換成continue不行,因為會跳過本次循環,count不能+1,count永遠==6,永遠跳過本次循環。
    else:
        print(count)
    count += 1
count = 0
while count < 12:
    count += 1
    if count == 6 or count == 10:
        pass # 換成continue可以,因為雖然跳出了本次循環,但是下次循環的時候count可以+1。
    else:
        print(count)

c. 使用while 循環輸出100-50,從大到小,如100,99,98...,到50時再從0循環輸出到50,然后結束

count = 101
while count > 50:
    count -= 1
    print(count)
    if count == 50:
        count = 0
        while count < 51:
            print(count)
            count += 1
        break

d. 使用 while 循環實現輸出 1-100 內的所有奇數 

count = 0
while count < 100:
    count += 1
    if count % 2 == 1:
        print(count)
for count in range(1,101,2):
        print(count)

e. 使用 while 循環實現輸出 1-100 內的所有偶數

count = 0
while count < 100:
    count += 1
    if count % 2 == 0:
        print(count)
for count in range(2,101,2):
        print(count)

8.現有如下兩個變量,請簡述 n1 和 n2 是什么關系?

n1 = 123456
n2 = n1

給數據123456起了另外一個別名n2,相當於n1和n2都指向該數據的內存地址

9.制作趣味模板程序(編程題)

需求:等待用戶輸入名字、地點、愛好,根據用戶的名字和愛好進行任意顯示
如:敬愛可愛的xxx,最喜歡在xxx地方干xxx

#方法一:
name = input("請輸入姓名:")
address = input("請輸入地點:")
hobby = input("請輸入愛好:")

info = """
    敬愛可愛的%s,最喜歡在%s地方干%s
"""% (name,address,hobby)

print(info)

#方法二:
name = input("請輸入姓名:")
address = input("請輸入地點:")
hobby = input("請輸入愛好:")

info = """
    敬愛可愛的{0},最喜歡在{1}地方干{2}
"""

print(info.format(name,address,hobby))

10.輸入一年份,判斷該年份是否是閏年並輸出結果。(編程題)

注:凡符合下面兩個條件之一的年份是閏年。 (1) 能被4整除但不能被100整除。 (2) 能被400整除。

year = int(input("Please input the year:"))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    print(year,"is a leap year")
else:
    print(year,"is not a leap year")

11.假設一年期定期利率為3.25%,計算一下需要過多少年,一萬元的一年定期存款連本帶息能翻番?(編程題)

money = 10000
years = 0
rate = 0.0325
while money <= 20000:
    years += 1
    money = money * (1+rate)
print(str(years)+"年以后,一萬元的一年定期存款連本帶息能翻番")

作業

編寫登陸接口

基礎需求:

讓用戶輸入用戶名密碼
認證成功后顯示歡迎信息
輸錯三次后退出程序

#!/usr/bin/env python3
# -*- encoding: utf8 -*-
# 輸錯用戶名和輸錯密碼的次數總共最多為3次
import getpass

exit_flag = False
count = 0
while count < 3 and not exit_flag:
    user = input('\n請輸入用戶名:')
    if user != "wss":
        count += 1
        print("\n用戶名錯誤")
    else:
        while count < 3 and not exit_flag:
            pwd = getpass.getpass('\n請輸入密碼:')
            # pwd = input('\n請輸入密碼:')
            if pwd == "123":
                print('\n歡迎登陸')
                print('..........')
                exit_flag = True
            else:
                count += 1
                print('\n密碼錯誤')
                continue
    if count >= 3:  # 嘗試次數大於等於3時鎖定用戶
        if user == "":
            print("\n您輸入的錯誤次數過多,且用戶為空")
        elif user != "wss":
            print("\n您輸入的錯誤次數過多,且用戶 %s 不存在" % user)
        else:
            print("\n您輸入的錯誤次數過多")
#!/usr/bin/python3
#-*- coding:utf-8 -*-
# 輸錯用戶名和輸錯密碼的次數分別最多為3次
# import getpass

_username = "wss"
_password = "123"

count = 0
exit_flag = False
while count < 3 and not exit_flag:
    count += 1
    username = input("\nPlease input your username:")
    if username == _username:
        exit_flag = True # 當密碼正確時,跳過第一層循環,不再詢問用戶名
        count = 0
        while count < 3:
            count += 1
            password = input("\nPlease input your password:")
            # password = getpass.getpass("\nPlease input your password:")
            if password == _password:
                print("\nhello,%s" % username)
                break # 密碼正確,跳過第二層循環,不再詢問密碼
            else:
                print("\nYour password is wrong")
    else:
        print("\nYour username is wrong")
    if count >= 3:  # 嘗試次數大於等於3時強制退出
        print("\nYou try more than 3 times,be forced to quit")

升級需求:

可以支持多個用戶登錄 (提示,通過列表存多個賬戶信息)
用戶3次認證失敗后,退出程序,再次啟動程序嘗試登錄時,還是鎖定狀態(提示:需把用戶鎖定的狀態存到文件里)

#!/usr/bin/env python3
# -*- encoding: utf8 -*-
# 輸錯用戶名和輸錯密碼的次數總共最多為3次
import getpass

user_list = {
    "wss": "123",
    "alex": "456",
    "jay": "789"
}

f = open("deny_user_list.txt", "a", encoding="utf-8")  # 沒有此文件時創建
f.close()
with open("deny_user_list.txt", "r", encoding="utf-8") as deny_user_list_file:
    deny_user_list = deny_user_list_file.readlines()

exit_flag = False
count = 0
while count < 3 and not exit_flag:
    user = input('\n請輸入用戶名:')
    if user not in user_list:
        count += 1
        print("\n用戶名錯誤")
    elif user + "\n" in deny_user_list:
        print("\n用戶已被鎖定,請聯系管理員解鎖后重新嘗試")
        break
    else:
        while count < 3 and not exit_flag:
            pwd = getpass.getpass('\n請輸入密碼:')
            # pwd = input('\n請輸入密碼:')
            if pwd == user_list[user]:
                print('\n歡迎登陸')
                print('..........')
                exit_flag = True
            else:
                count += 1
                print('\n密碼錯誤')
                continue
    if count >= 3:  # 嘗試次數大於等於3時鎖定用戶
        if user == "":
            print("\n您輸入的錯誤次數過多,且用戶為空")
        elif user not in user_list:
            print("\n您輸入的錯誤次數過多,且用戶 %s 不存在" % user)
        else:
            with open("deny_user_list.txt", "a", encoding="utf-8") as deny_user_list_file:
                if user + "\n" not in deny_user_list:
                    deny_user_list_file.write(user + "\n")
            print("\n您輸入的錯誤次數過多,%s 已經被鎖定" % user)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 輸錯用戶名和輸錯密碼的次數分別最多為3次

# import getpass

user_dict = dict([("wss", "123"), ("alex", "456"), ("jay", "789")])  # 存儲用戶信息
deny_user_list = []  # 初始化拒絕用戶列表
f = open("deny_user_list.txt", "a", encoding="utf-8")  # 沒有此文件時創建
f.close()

with open("deny_user_list.txt", "r", encoding="utf-8") as deny_user_list_txt:
    for deny_user in deny_user_list_txt.readlines():  # 將文件內容轉換為列表
        deny_user = deny_user.strip()  # 去掉換行符
        deny_user_list.append(deny_user)
count = 0
exit_flag = False
while count < 3 and not exit_flag:
    count += 1
    username = input("\nPlease input your username:")
    if username in user_dict and username not in deny_user_list:
        exit_flag = True  # 當用戶名正確時,跳過第一層循環,不再詢問用戶名
        count = 0
        while count < 3:
            count += 1
            password = input("\nPlease input your password:")
            # password = getpass.getpass("\nPlease input your password:")
            if password == user_dict[username]:
                print("\nhello,%s" % username)
                break  # 當密碼正確時,跳過第二層循環,不再循環密碼
            else:
                print("\nYour password is wrong")
    elif username in deny_user_list:
        print("\n%s is locked,please contact the administrator" % username)
        break
    else:
        print("\nYour username is wrong")
    if count >= 3:  # 當嘗試次數大於等於3時強制退出並鎖定用戶
        if username not in user_dict or username == "":
            print("\nYou try more than 3 times,be forced to quit")
        else:
            with open("deny_user_list.txt", "a", encoding="utf-8") as deny_user_list_file:
                if username not in deny_user_list:
                    deny_user_list_file.write(username + "\n")
                    print("\nYou try more than 3 times,%s has been locked" % username)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM