我是python的新手,并尝试用#34; Think Python"
中的练习构建一个运行10k的计算器我尝试做的是将输入时间分解为:43.12分为2个单独的数字...... 然后执行(43x60) - 它给出秒数,然后加上剩余的秒数+12 .. 给出准确的数字......
下面的运行它,如果我将4312硬编码为一个整数 - 但是想要动态地接受它...我可以帮助我指出正确的方向
#python 10k calculator
import time
distance = 6.211180124223602
time = float(input("what was your time?"))
tenK = 10
mile = 1.61
minute = 60
sph = 0
def convertToMiles():
global distance
distance = tenK / mile
convertToMiles()
print("Distance equal to :",distance)
def splitInput():
test = [int(char) for char in str(4312)]
print(test)
splitInput()
答案 0 :(得分:2)
如果您不立即将用户输入转换为float
,则会更容易。字符串提供split
函数,浮点数不提供。
>>> time = input("what was your time? ")
what was your time? 42.12
>>> time= time.split('.')
>>> time
['42', '12']
>>> time= int(time[0])*60+int(time[1])
>>> time
2532
答案 1 :(得分:1)
当您在输入中询问时,您已将数字转换为浮点数;只需将其作为字符串接受,然后您就可以轻松地将其分成各个部分:
user_input = input('what was your time?')
bits = user_input.split('.') # now bits[0] is the minute part,
# and bits[1] (if it exists) is
# the seconds part
minutes = int(bits[0])
seconds = 0
if len(bits) == 2:
seconds = int(bits[1])
total_seconds = minute*60+seconds
答案 2 :(得分:0)
我希望用户输入格式为[hh:]mm:ss
的字符串,然后使用类似:
instr = raw_input('Enter your time: [hh:]mm:ss')
fields = instr.split(':')
time = 0.0
for field in fields:
yourtime *= 60
yourtime += int(field)
print("Time in seconds", yourtime)
但是如果你真的需要时间,那么你可以使用time.strptime()。
答案 3 :(得分:0)
import re
time = raw_input("what was your time? ")
x=re.match(r"^(\d+)(?:\.(\d+))$",str(time))
if x:
time= int(x.group(1))*60+int(x.group(2))
print time
else:
print "Time format not correct."
尝试这种方式。您也可以通过这种方式添加一些错误检查。