Week3 Exceptions
Fuel Gauge
題目描述:
輸入分數字串,判斷并輸出相應的百分數;特例不足1%輸出E,超出99%輸出F
思路:
1,從字串中取出x,y;
2,按題中要求計算輸出;
題解:
while True:
try:
## 取出x,y
x, z, y= input("Fraction: ")
x, y = int(x), int (y)
##防止出錯
if y == 0:
raise ZeroDivisionError
if x > y:
raise ValueError
break
except(ValueError, ZeroDivisionError):
pass
## 模擬題
if 0 < x/y < 0.99:
print(f"{round(x/y*100)}%")
elif x/y >= 0.99:
print("F")
else:
print("E")
Felipe’s Taqueria
題目描述:
根據用戶輸入的資訊,匹配選單價格,最終算出最終價格,
題解:
## 選單資訊
menu = {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00,
}
##total:結果
total = 0
## 計算輸出
while True:
try:
## title(): 首字母大寫其余小寫
item = input("Item: ").title()
if item in menu:
total += menu[item]
print(f"Total: ${total:.2f}")
except EOFError:
print()
break
Grocery List
題目描述:
記錄用戶輸入商品,最終輸出已輸入的商品以及商品數量;
題解:
## 存盤商品資訊
list = {}
while True:
## 輸入處理
try:
## upper():字串大寫
item = input("").upper()
except EOFError:
print()
break
## 記錄商品
if item in list:
list[item] += 1
else:
list[item] = 1
## 輸出結果
for item, cnt in sorted(list.items()):
print(f"{cnt} {item}")
Outdated
題目描述:
用戶輸入9/8/1636,September 8, 1636形式,系統轉換輸出1636-09-08;若用戶輸出其他形式拋例外,
題解:
## 月份記錄
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
##思路:分情況討論
while True:
date = input("Date: ")
month,day,year = "", "", ""
try:
## 9/8/1636
if len(date.split("/")) == 3:
date = date.split("/")
month, day, year = map(int, date)
## September 8, 1636
else:
date = date.split(",")
if len(date) == 2:
month, day = date[0].split()
month = months.index(month)+1
day, year = int(day), int(date[1])
##輸出
if 1<=int(month)<=12 and 1<=int(day)<=31:
print(f"{year:04}-{month:02}-{day:02}")
break
except ValueError:
pass
Week4 Libraries
Emojize
題目描述:
練習python呼叫庫操作;
題解:
from emoji import emojize
print("Output:", emojize(input("Input: ")))
Frank, Ian and Glen’s Letters
題目描述:
The documentation for pyfiglet isn’t very clear, but you can use the module as follows:
from pyfiglet import Figlet
figlet = Figlet()
You can then get a list of available fonts with code like this:
figlet.getFonts()
You can set the font with code like this, wherein f is the font’s name as a str:
figlet.setFont(font=f)
And you can output text in that font with code like this, wherein s is that text as a str:
print(figlet.renderText(s))
題解:
from pyfiglet import Figlet
import random
import sys
fonts = Figlet().getFonts()
# Zero if the user would like to output text in a random font.
# Two if the user would like to output text in a specific font, in which case the first of the two should be -f or --font, and the second of the two should be the name of the font.
if len(sys.argv) == 1:
font = random.choice(fonts)
elif len(sys.argv) == 3:
if sys.argv[1] in ["-f", "--font"] and sys.argv[2] in fonts:
font = sys.argv[2]
else:
sys.exit("Invalid arguments.")
else:
sys.exit("Invalid number of arguments.")
## 輸出
text = input("Input: ")
print("Output:\n", Figlet(font=font).renderText(text))
Adieu, Adieu
題目描述:
用戶輸入名字,將所有名字按照inflect中的操作輸出;
題解:
import inflect
p = inflect.engine()
names = []
while True:
try:
names.append(input("Name: ").strip())
except EOFError:
print()
break
print(f"Adieu, adieu, to {p.join(names)}")
Guessing Game
題目描述:
用戶選擇猜數等級,然后進行競猜,競猜程序中會提示用戶資訊,直到猜中為止;
題解:
from random import randint
## 選擇猜數等級
while True:
try:
n = int(input("Level: "))
if n < 0:
raise ValueError
break
except ValueError:
pass
## 生成競猜的數
rand = randint(1, n)
## 用戶判斷
while True:
try:
guess = int(input("Guess: "))
if guess < rand:
print("Too small!")
elif guess > rand:
print("Too large!")
else:
print("Just right!")
break
except ValueError:
pass
Little Professor
題目描述:
用戶選擇等級進行隨機式子生成,最后根據算式正確結果算取所得分數;
題解:
import random
def main():
level = get_level()
score = 0
for _ in range(10):
x = generate_integer(level)
y = generate_integer(level)
## 計算score
tries = 0
while tries < 3:
try:
tries += 1
answer = int(input(f"{x} + {y} = "))
if answer == x+y:
score += 1
break
else:
print("EEE")
except ValueError:
pass
print(f"{x} + {y} = {x+y}")
print("Score", score)
## 獲取等級
def get_level():
while True:
try:
level = int(input("Level: "))
if level in [1, 2, 3]:
return level
except ValueError:
pass
## 在范圍內生成數字
def generate_integer(level):
if level == 1:
return random.randint(0, 9)
return random.randint(10 ** (level - 1), 10**level - 1)
if __name__ == "__main__":
main()
Bitcoin Price Index
題目描述:
Expects the user to specify as a command-line argument the number of Bitcoins n, that they would like to buy. If that argument cannot be converted to a float, the program should exit via sys.exit with an error message.
Queries the API for the CoinDesk Bitcoin Price Index at https://api.coindesk.com/v1/bpi/currentprice.json, which returns a JSON object, among whose nested keys is the current price of Bitcoin as a float. Be sure to catch any exceptions, as with code like:
import requests
try:
...
except requests.RequestException:
...
Outputs the current cost of Bitcoins in USD to four decimal places, using , as a thousands separator.
題解:
import sys
import requests
try:
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
data = https://www.cnblogs.com/sinowind/p/response.json()
current_price = data["bpi"]["USD"]["rate_float"]
except requests.RequestException:
sys.exit()
try:
n = float(sys.argv[1])
except IndexError:
sys.exit("Missing command-line argument")
except ValueError:
sys.exit("Command-line argument is not a number")
print(f"${n * current_price:,.4f}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549232.html
標籤:Python
