[英]Can't seem to figure out how to write a Loop in Python
我必須計算員工的總工資並顯示結果。 您的程序將接受員工的姓名,工作時間和員工的工資率。 該程序還將需要計算加班時間。 加班費的定義是,超過40小時的工資是正常工資的1.5倍。 該程序應打印雇員的姓名,總工資金額,並且只有在加班的情況下,才應打印加班工資金額。 最后,程序應根據需要重復執行,直到用戶輸入標記值。
print("Payroll Calculator")
EmployeesName = input("Please enter employees Name or 0 to quit:")
WeeklyHours = int(input("Please Enter Hours Worked:"))
PayRate = int(input("Please Enter Pay Rate:"))
print("Normal Pay Rate is:", 40 * PayRate)
if(WeeklyHours > 40):
Overtime = PayRate * 1.5
if(WeeklyHours > 40):
print("Your Overtime Hours are:", WeeklyHours - 40)
print("Your Overtime Rate is:", Overtime * 1.5)
GrossPay = WeeklyHours * Overtime
print("Your Gross Pay is:", WeeklyHours * Overtime)
那就是我所擁有的,程序中沒有循環。 我似乎無法弄清楚這個東西,我在這里瘋了。 我只希望有人幫我分解一下。 謝謝!
您可以做的是將所有要重復的代碼循環多次。 它看起來像:
while True:
# code you want to repeat
if some_condition:
break
要么:
flag = False
while not flag:
# code you want to repeat
if some_condition:
flag = True
您可以使用如下所示的for循環:
print("Payroll Calculator")
count = 2
for i in range(count):
EmployeesName = input("Please enter employees Name :")
WeeklyHours = int(input("Please Enter Hours Worked:"))
PayRate = int(input("Please Enter Pay Rate:"))
print("Normal Pay Rate is:", 40 * PayRate)
if(WeeklyHours > 40):
Overtime = PayRate * 1.5
if(WeeklyHours > 40):
print("Your Overtime Hours are:", WeeklyHours - 40)
print("Your Overtime Rate is:", Overtime * 1.5)
print("Your Gross Pay is:", WeeklyHours * Overtime)
finish = input('Would you like to continue? (y/n) :')
if finish == 'n':
count = 0
elif finish == 'y':
count += 1
另外,您的變量GrossPay未被使用。
而不是在True時使用,我會先將“前哨變量”設置為不間斷值。 使老師高興。 給定例如sentinel變量將寫為“ 0”作為EmployeeName,您將執行
print("Payroll Calculator")
EmployeesName = None
while EmployeesName != '0': # 0 in python2
EmployeesName = input("Please enter employees Name or 0 to quit:")
If EmployeesName != '0':
WeeklyHours = int(input("Please Enter Hours Worked:"))
PayRate = int(input("Please Enter Pay Rate:"))
print("Normal Pay Rate is:", 40 * PayRate)
if(WeeklyHours > 40):
Overtime = PayRate * 1.5
if(WeeklyHours > 40):
print("Your Overtime Hours are:", WeeklyHours - 40)
print("Your Overtime Rate is:", Overtime * 1.5)
GrossPay = WeeklyHours * Overtime
print("Your Gross Pay is:", WeeklyHours * Overtime)
但您也可以定義一些自定義變量來處理此問題:
stop = False
while not stop:
...
# check now if if we should stop
if (EmployeesName == '0'):
stop = True
您始終可以使用while True:break方法,但是我不推薦這樣做,因為該任務要求在while條件下使用變量,並且應避免在true循環之前使用imho while循環,直到您真正了解循環為止。
while True:
...
# check now if if we should stop
if (EmployeesName == '0'):
break # exits loop.
在這個例子中有道理。
注意:Python2將為input()返回一個整數,Python3將返回一個字符串。 將示例編輯為python3。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.