iT邦幫忙

1

python 成績查詢問題

建立一個字典記錄同學的成績
內容如下:
林小明:85
曾山水:93
鄭美麗:67

輸入一個同學的姓名,如果這位同學有在字典裡面的話則輸出他的成績
沒有的話則建立一個新的鍵,並讓使用者輸入其值

輸入:
輸入學生姓名:
---林小明

輸出:
林小明的成績為85

輸入:
輸入學生姓名:
---abc
輸入學生分數:
---100

輸出:
字典內容:{'林小明': 85, '曾山水': 93, '鄭美麗': 67, 'abc': '100'}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-11-22 11:12:49
$python score.py
輸入學生姓名(Q 可結束程式):林小明
輸入學生分數:85
輸入學生姓名(Q 可結束程式):曾山水
輸入學生分數:93
輸入學生姓名(Q 可結束程式):鄭美麗
輸入學生分數:67
輸入學生姓名(Q 可結束程式):林小明
林小明的成績為85
輸入學生姓名(Q 可結束程式):abc
輸入學生分數:100
輸入學生姓名(Q 可結束程式):q
字典內容:
[['\xe6\x9e\x97\xe5\xb0\x8f\xe6\x98\x8e', '85'], ['\xe6\x9b\xbe\xe5\xb1\xb1\xe6\xb0\xb4', '93'], ['\xe9\x84\xad\xe7\xbe\x8e\xe9\xba\x97', '67'], ['abc', '100']]
# -*- coding: UTF-8 -*-
main = list()
key = input("輸入學生姓名(Q 可結束程式):")
while key.upper() != "Q":
	existed = False	
	for item in main:
		if item[0]==key:
			existed = True
			print(item[0]+"的成績為"+item[1])
	if existed == False:
		person = list()
		person.append(key)
		score = input("輸入學生分數:")
		person.append(score)
		main.append(person)
	key = input("輸入學生姓名(Q 可結束程式):")
print("字典內容:")
print(main)
2
一級屠豬士
iT邦大師 1 級 ‧ 2021-11-22 16:36:20

另一種版本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
d = dict()
key = input("輸入學生姓名(Q 可結束程式):")
while key.upper() != "Q":
	if key in d:
		print(key+"的成績為"+d[key])
	else:
		score = input("輸入學生分數:")
		d[key] = score
	key = input("輸入學生姓名(Q 可結束程式):")
  
print("字典內容:", d)

https://ithelp.ithome.com.tw/upload/images/20211122/20050647aPFLYCqoND.png

我要發表回答

立即登入回答