我是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.我该怎么解决呢?
发布于 2013-09-06 14:37:07
定义您自己的功能:
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.发布于 2013-09-06 14:38:07
您可以简单地做这样的事情:
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."希望它能帮上忙
发布于 2013-09-06 14:50:46
你可以:
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。
https://stackoverflow.com/questions/18660303
复制相似问题