我是Python的初学者。我希望将代码整理到每10个,例如。从33到30岁。
def roundoff(a, b):
b = round(b)
print str(a) + " you are around " + str(b) + " years old."
>>> roundoff("Bob", 33)
Bob you are around 33.0 years old.
我该如何解决?
答案 0 :(得分:2)
定义自己的功能:
def my_round(x):
return x - (x % 10) #or py2.x: (b/10)*10, py3.x: (b//10)*10
...
>>> my_round(33)
30
>>> my_round(333)
330
使用字符串格式代替使用连接和str()
转换:
>>> def roundoff(a, b):
... b = b - (b % 10)
... print "{} you are around {} years old.".format(a, b)
...
>>> roundoff('bob', 33)
bob you are around 30 years old.
>>> roundoff('bob', 97)
bob you are around 90 years old.
答案 1 :(得分:0)
您可以简单地执行以下操作:
def roundoff(name,age):
age = age - age%10 #the % operator will get the rest of the division by 10
#(so from 33 will get 3)
print str(name) + " you are around " + str(age) + " years old."
希望有所帮助
答案 2 :(得分:0)
你可以这样做:
def roundoff(name, age):
print '%s, you are around %d years old.' % (name, (age /10) * 10)
当/
运算符将int除以int时,它返回另一个int。因此,当您将33除以10时,结果将是3而不是3.3。在此之后,您只需将结果乘以10即可。