我设法让这个函数遍历列表。我想要的是一种在输出字符串中包含当前列表元素的方法。即。显示星期一或星期二的(raw_input("Enter the number of hours the employee worked on : "))
或函数所在的元素。
# -*- coding: utf-8 -*-
day = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
def hours():
while True:
try:
hours = int(raw_input("Enter the number of hours the employee worked on : "))
if (hours >=0) and (hours <=24):
return hours
else:
print ("Please enter a whole number that is more than zero & less than 24")
except ValueError:
print ("Please enter a whole number that is more than zero & less than 24")
continue
for i in day:
print hours()
答案 0 :(得分:1)
如果您想在输出中使用工作日,可以使用format()
函数,如下所示:
"Enter ... worked on {0} : ".format(day)
并将day
传递到您的hours()
函数:
print hours(i)
当然,您必须定义您的函数以接受一个新参数:
def hours(day):
...
所以你的功能有点清理,如下所示。请注意,工作日列表具有convention for constants的大写名称,并且range check已简化。此外,通常,如果您必须多次键入相同的代码行,则可能需要重新考虑代码的结构:
def hours(day):
while True:
try:
prompt = "Enter the number of hours the employee worked on {0}: ".format(day)
hours = int(raw_input(prompt))
if 0 <= hours <= 24:
return hours
except ValueError:
pass # Silently catch failure.
print "Please enter a whole number that is more than zero & less than 24"
WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
for day in WEEKDAYS:
print hours(day)
答案 1 :(得分:0)
如果您正在使用python 3.只需将其设为hours = int(input("Enter the number of hours the employee worked on: "))