下面的代码按预期工作,但是有更优雅的方法来完成这个吗?
如果我不使用int()将raw_input更改为整数,则会将它们添加为字符串(即' 10 + 10' =' 1010' )。
另外,我似乎无法将int()添加到与raw_input相同的行中(即。
user_cheeses = raw_input("How many cheeses do you have?:\n> ").int()
),因为我收到了错误 - ' str'对象没有属性' int'。
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %r cheeses!" % cheese_count
print "You have %r boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can put in inputs from you as well!:"
user_cheeses = raw_input("How many cheeses do you have?:\n> ")
user_cheeses_number = int(user_cheeses)
user_crackers = raw_input("How many boxes of crackers do you have?:\n >")
user_crackers_number = int(user_crackers)
cheese_and_crackers(user_cheeses, user_crackers)
print "You can also add even more cheeses and more crackers!:"
more_cheeses = raw_input("How many more cheeses do you now have?:\n> ")
more_cheeses_number = int(more_cheeses)
more_crackers = raw_input("How many more crackers do you now have?:\n> ")
more_crackers_number = int(more_crackers)
cheese_and_crackers(user_cheeses_number + more_cheeses_number, user_crackers_number + more_crackers_number)
答案 0 :(得分:0)
int()
不是字符串的方法。 int()
是(内置)函数,因此您需要将其应用于raw_input()
的结果:
user_cheeses = int(raw_input("How many cheeses do you have?:\n> "))
您可以通过将其应用于代码中的user_cheeses
来间接执行此操作:
user_cheeses_number = int(user_cheeses)
其中user_cheeeses
是raw_input()
返回的字符串。