Python編程 : 從入門到實踐 課後習題五

5-3 外星人顏色#1 :假設在遊戲中剛射殺了一個外星人,請創建一個名爲alien_color 的變量,並將其設置爲’green’ 、‘yellow’ 或’red’ 。 編寫一條if 語句,檢查外星人是否是綠色的;如果是,就打印一條消息,指出玩家獲得了5個點。 編寫這個程序的兩個版本,在一個版本中上述測試通過了,而在另一個版本中未通過(未通過測試時沒有輸出)。

color = ["green","yellow","red"]
for alien_color in color: 
    if alien_color =="green":
        print("Congratulations ! You will win Five points !")
Congratulations ! You will win Five points !
alien_color = 'green'

#編寫一條 if 語句,檢查外星人是否是綠色的;如果是,就打印一條消息,指出玩家獲得了 5 個點。
if alien_color == 'green':
    print('you win 5 points!')

#編寫這個程序的兩個版本,在一個版本中上述測試通過了,而在另一個版本中未通過(未通過測試時沒有輸出)。
alien_color = 'red'
if alien_color == 'green':
    print('you win 5 points!')

you win 5 points!

5-4 外星人顏色#2 :像練習5-3那樣設置外星人的顏色,並編寫一個if-else 結構。 如果外星人是綠色的,就打印一條消息,指出玩家因射殺該外星人獲得了5個點。 如果外星人不是綠色的,就打印一條消息,指出玩家獲得了10個點。 編寫這個程序的兩個版本,在一個版本中執行if 代碼塊,而在另一個版本中執行else 代碼塊。

alien_color = "green"
color = ["green","yellow","red"]
if alien_color in color:
        print("Congratulations ! You will win Five points !")
else:
        print("Congratulations ! You will win Ten points !")
Congratulations ! You will win Five points !
alien_color = "orange"
color = ["green","yellow","red"]
if alien_color in color:
        print("Congratulations ! You will win Five points !")
else:
        print("Congratulations ! You will win Ten points !")
Congratulations ! You will win Ten points !
# alien_color = 'green'

# if alien_color == 'green':
#     print('you win 5 points!')
# else:
#     print('you win 10 points!')
    
alien_color = 'red'

if alien_color == 'green':
    print('you win 5 points!')
else:
    print('you win 10 points!')

you win 10 points!

5-8 以特殊方式跟管理員打招呼 :創建一個至少包含5個用戶名的列表,且其中一個用戶名爲’admin’ 。想象你要編寫代碼,在每位用戶登錄網站後都打印一條問 候消息。遍歷用戶名列表,並向每位用戶打印一條問候消息。 如果用戶名爲’admin’ ,就打印一條特殊的問候消息,如“Hello admin, would you liketo seeastatus report?”。 否則,打印一條普通的問候消息,如“Hello Eric, thank you for logging in again”。

People = ["Toy","Jeck","Eric","Jean","admin","Rebot"]
for P in People:
    if P =="admin":
        print("Hello admin, would you like to seeastatus report?")
    else:
        print("Hello {}, thank you for logging in again !".format(P))
    
    
Hello Toy, thank you for logging in again !
Hello Jeck, thank you for logging in again !
Hello Eric, thank you for logging in again !
Hello Jean, thank you for logging in again !
Hello admin, would you like to seeastatus report?
Hello Rebot, thank you for logging in again !
name_list = ["Bob", "July", "Xiayu", "admin", "Cat"]
for i in name_list:
    if i == "admin":
        print("Hello %s, would you like to see a status report?" % i)
    else:
        print("Hello %s, thank you for logging in again" % i)

Hello Bob, thank you for logging in again
Hello July, thank you for logging in again
Hello Xiayu, thank you for logging in again
Hello admin, would you like to see a status report?
Hello Cat, thank you for logging in again

5-9 處理沒有用戶的情形 :在爲完成練習5-8編寫的程序中,添加一條if 語句,檢查用戶名列表是否爲空。 如果爲空,就打印消息“We need to find some users!”。 刪除列表中的所有用戶名,確定將打印正確的消息。

People = ["Toy","Jeck","Eric","Jean","admin","Rebot"]
while len(People)>0:
    print(People[-1] +"! You will not login !")
    People.pop()
if len(People)==0:
    print("We need to find some users!")
elif i == "admin":
     print("Hello %s, would you like to see a status report?" % i)
else:
    print("Hello %s, thank you for logging in again" % i)
      
Rebot! You will not login !
admin! You will not login !
Jean! You will not login !
Eric! You will not login !
Jeck! You will not login !
Toy! You will not login !
We need to find some users!
name_list = []
if len(name_list) == 0:
    print("We need to find some users!")
else:
    for i in name_list:
        if i == "admin":
            print("Hello %s, would you like to see a status report?" % i)
        else:
            print("Hello %s, thank you for logging in again" % i)

We need to find some users!

5-10 檢查用戶名 :按下面的說明編寫一個程序,模擬網站確保每位用戶的用戶名都獨一無二的方式。 創建一個至少包含5個用戶名的列表,並將其命名爲current_users 。 再創建一個包含5個用戶名的列表,將其命名爲new_users ,並確保其中有一兩個用戶名也包含在列表current_users 中。 遍歷列表new_users ,對於其中的每個用戶名,都檢查它是否已被使用。如果是這樣,就打印一條消息,指出需要輸入別的用戶名;否則,打印一條消息,指 出這個用戶名未被使用。 確保比較時不區分大消息;換句話說,如果用戶名’John’ 已被使用,應拒絕用戶名’JOHN’ 。

current_users = ["Bob","Linda","Tufei","Bob","Jean"]
new_users = ["Linda","Bob","Linda","Xiaxue","Tom"]
for i in current_users:
    for j in new_users:
        if i==j:
            print("{},已被使用,請更換用戶名 !".format(i.lower()))
            break
        else:
            print("{},沒被註冊,可以使用 !".format(i.lower()))
            
bob,沒被註冊,可以使用 !
bob,已被使用,請更換用戶名 !
linda,已被使用,請更換用戶名 !
tufei,沒被註冊,可以使用 !
tufei,沒被註冊,可以使用 !
tufei,沒被註冊,可以使用 !
tufei,沒被註冊,可以使用 !
tufei,沒被註冊,可以使用 !
bob,沒被註冊,可以使用 !
bob,已被使用,請更換用戶名 !
jean,沒被註冊,可以使用 !
jean,沒被註冊,可以使用 !
jean,沒被註冊,可以使用 !
jean,沒被註冊,可以使用 !
jean,沒被註冊,可以使用 !
current_users = ["Bob","Linda","Tufei","July","Jean"]
new_users = ["Linda","Bob","Tony","Xiaxue","Tom"]
for i in new_users:
    if i in current_users:
         print("{},已被使用,請更換用戶名 !".format(i.lower()))
    else:
         print("{},沒被註冊,可以使用 !".format(i.lower()))
linda,已被使用,請更換用戶名 !
bob,已被使用,請更換用戶名 !
tony,沒被註冊,可以使用 !
xiaxue,沒被註冊,可以使用 !
tom,沒被註冊,可以使用 !
current_users = ["bob", "jane", "jack", "admin", "tom"]
new_users = ["Bob", "james", "NIck", "JACK", "name"]
for i in new_users:
    if i.lower() in current_users:
        print("%s 已經被使用,請更換用戶名" % i)
    else:
        print("%s 沒被註冊,可以使用" % i)

Bob 已經被使用,請更換用戶名
james 沒被註冊,可以使用
NIck 沒被註冊,可以使用
JACK 已經被使用,請更換用戶名
name 沒被註冊,可以使用

5-11 序數 :序數表示位置,如1st和2nd。大多數序數都以th結尾,只有1、2和3例外。 在一個列表中存儲數字1~9。 遍歷這個列表。 在循環中使用一個if-elif-else 結構,以打印每個數字對應的序數。輸出內容應爲1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每個序 數都獨佔一行。

number = [1,2,3,4,5,6,7,8,9]
for n in number:
    if n ==1:
        print("{}st".format(n),end=" ")
    elif n ==2:
        print("{}nd".format(n),end=" ")
    elif n == 3:
        print("{}rd".format(n),end=" ")
    else:
        print("{}th".format(n),end=" ")
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 
list=[]
for numbers in range(1,10):
    list.append(numbers)
print(list)
for number in list:
    if number==1:
        print(str(number)+'st')
    elif number==2:
        print(str(number)+'nd')
    elif number==3:
        print(str(number)+'rd')
    else:
        print(str(number)+'th')

[1, 2, 3, 4, 5, 6, 7, 8, 9]
1st
2nd
3rd
4th
5th
6th
7th
8th
9th

尋找兩個列表中的相同元素
list1 = [‘張三’, ‘李四’, ‘王五’, ‘老二’]
list2 = [‘張三’, ‘李四’, ‘老二’, ‘王七’]

list1 = ['張三', '李四', '王五', '老二']

list2 = ['張三', '李四', '老二', '王七']

a = [x for x in list1 if x in list2] #兩個列表表都存在
b = [y for y in (list1 + list2) if y not in a] #兩個列表中的不同元素

print('a的值爲:',a)
print('b的值爲:',b)

c = [x for x in list1 if x not in list2]  #在list1列表中而不在list2列表中
d = [y for y in list2 if y not in list1]  #在list2列表中而不在list1列表中
print('c的值爲:',c)
print('d的值爲:',d)
a的值爲: ['張三', '李四', '老二']
b的值爲: ['王五', '王七']
c的值爲: ['王五']
d的值爲: ['王七']

利用Tkinter 創建窗口程序

import tkinter as tk  # 使用Tkinter前需要先導入
 
# 第1步,實例化object,建立窗口window
window = tk.Tk()
 
# 第2步,給窗口的可視化起名字
window.title('My Window')
 
# 第3步,設定窗口的大小(長 * 寬)
window.geometry('500x300')  # 這裏的乘是小x
 
# 第4步,在圖形界面上設定標籤
l = tk.Label(window, text='你好!很高心遇見你 !', bg='red', font=('楷體', 12), width=30, height=2)
# 說明: bg爲背景,font爲字體,width爲長,height爲高,這裏的長和高是字符的長和高,比如height=2,就是標籤有2個字符這麼高
 
# 第5步,放置標籤
l.pack()    # Label內容content區域放置位置,自動調節尺寸
# 放置lable的方法有:1)l.pack(); 2)l.place();
 
# 第6步,主窗口循環顯示
window.mainloop()
# 注意,loop因爲是循環的意思,window.mainloop就會讓window不斷的刷新,如果沒有mainloop,就是一個靜態的window,傳入進去的值就不會有循環,mainloop就相當於一個很大的while循環,有個while,每點擊一次就會更新一次,所以我們必須要有循環
# 所有的窗口文件都必須有類似的mainloop函數,mainloop是窗口文件的關鍵的關鍵。
import tkinter as tk  # 使用Tkinter前需要先導入
 
# 第1步,實例化object,建立窗口window
window = tk.Tk()
 
# 第2步,給窗口的可視化起名字
window.title('My Window')
 
# 第3步,設定窗口的大小(長 * 寬)
window.geometry('500x300')  # 這裏的乘是小x
 
# 第4步,在圖形界面上設定標籤
var = tk.StringVar()    # 將label標籤的內容設置爲字符類型,用var來接收hit_me函數的傳出內容用以顯示在標籤上
l = tk.Label(window, textvariable=var, bg='blue', fg='white', font=('楷體', 12), width=30, height=2)
# 說明: bg爲背景,fg爲字體顏色,font爲字體,width爲長,height爲高,這裏的長和高是字符的長和高,比如height=2,就是標籤有2個字符這麼高
l.pack()
 
# 定義一個函數功能(內容自己自由編寫),供點擊Button按鍵時調用,調用命令參數command=函數名= False
def 敲擊():
    globalif== False:= True
        var.set('您已點擊了按鈕!')
    else:= False
        var.set('')
 
# 第5步,在窗口界面設置放置Button按鍵
b = tk.Button(window, text='開始', font=('楷體', 12), width=10, height=1, command=敲擊)
b.pack()
 
# 第6步,主窗口循環顯示
window.mainloop()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章