我正在尝试使用raw_input从用户那里获取输入,我想捕获用户可以输入数字的实例。我一直在搜索堆栈溢出和各种其他网站,我没有遇到任何对我有意义的东西。由于raw_input总是返回一个字符串,所以甚至可以捕获这样的实例吗?
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
def __str__(self):
return self.name
@property
def weekly_total(self):
return sum(self.hours)
@classmethod
def from_input(cls):
while True:
try:
name = raw_input("Enter new employee name\n")
except ValueError:
print("\n This is a integer ")
continue
else:
break
while True:
try:
pay = input("Enter pay rate ")
except ValueError:
print("You must enter a value ")
continue
else:
break
while True:
try:
hours = input("Enter a tuple for days monday through sunday ")
except ValueError:
print("use must enter a tuple with 7 integer values")
continue
else:
break
return cls(name,pay,hours)
employee = Employee.from_input()
print str(employee)
答案 0 :(得分:1)
我会把它分成不同的功能;有更简洁的方法来做到这一点,但我已经尽可能地使它们相似,所以你可以看到这个过程:
def get_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
print "Please enter an integer."
else:
return i
def get_non_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
return s
else:
print "Please don't enter an integer."