我正在嘗試制作一個簡單的程式,該程式使用 for 回圈、if-elif-else 陳述句和輸入來獲取三個“員工”的薪水并比較它們以查看 A,他們中的任何一個是否具有相同的薪水。或 B,如果他們沒有相同的薪水。到目前為止,這就是我得到的,但我嘗試過的兩種策略都沒有成功,我不明白為什么:(。感謝所有幫助,請原諒我,因為我還是編碼新手,我嘗試通過這些練習自學。謝謝!
salarylist = []
salarylist = list(map(int, salarylist))
maxLengthList = 3
while len(salarylist) < maxLengthList:
salary_of_employee = int(input("Enter your salary: "))
salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
print('non of the salaries are the same.')
############################################################################
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]
if empOne == salarylist[0]:
print("these are the same salary.")
elif empTwo == salarylist[1]:
print('these are the same salary')
elif empThree == salarylist[2]:
print('these are the same salary')
else:
print('non of the salaries are the same.')
uj5u.com熱心網友回復:
當你有工資串列時,從該串列中創建一個集合并比較長度,如果長度相同,那么工資將是唯一的,否則將至少有一個共同工資
lst2 = set(salarylist)
if(len(lst2) == len(salarylist)):
print("Non of the salaries are the same.")
else:
print("Same salaries found")
要找到相同的薪水,請遍歷串列中元素的集合并檢查計數,如果大于一,則重復。
for sal in lst2:
if(salarylist.count(sal) > 1):
print("Duplicate here")
uj5u.com熱心網友回復:
我試過運行你的代碼,它給出了一個可怕的錯誤。我清楚地理解你的愿望。你的大部分邏輯都不符合它。所以我決定根據您的要求重新編碼所有內容{for loops, if, elif, else statement, 3 employees etc..}
MAX_LEN = 3
COUNTER = 1
LIST_SAL = []
while MAX_LEN >= COUNTER:
ASK_SAL = int(input('Enter your salary :'))
LIST_SAL.append(ASK_SAL)
COUNTER =1
print(LIST_SAL)
for check in LIST_SAL:
if LIST_SAL.count(check)>1:
print('Same salaries presented in the list')
break
else:
print('Salaries of employees are unique!')
break
好的,所以.. 我創建了一個變數max_len = 3,它是員工總數,然后我將變數初始化COUNTER為 1,以便它在 while 回圈中迭代并每次遞增 1。Therafter 一個名為的變數ask_sal向用戶詢問薪水 {3 次},并將每個輸入附加到LIST_SAL變數 {a list}。然后我列印了串列以進行可視化。
在我使用變數訪問串列 { list_sal} 中的元素之后for loop,該變數check在 count() 函式的幫助下查找元素在串列中重復的次數,如果大于則列印“提供相同的薪水”或者列印“唯一工資”..
您可能想知道為什么我使用了 2 個 break 陳述句。嗯,它們用??于中斷進一步的迭代,因為if or else在第一次迭代中滿足條件。如果您嘗試洗掉 break 陳述句,列印函式將在串列中出現相同薪水的次數。
希望我對你有所幫助。我也是編程新手,但我喜歡它并且經常練習。繼續打磨,努力作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407315.html
標籤:
