I'm new to python and trying to build a 10k running calculator from the exercises in "Think Python"
what I'm trying to do is break down the input time ie:43.12 into 2 separate numbers ... then perform (43x60)- which gives the seconds and then add the remaining seconds +12 .. to give the accurate number to work from ..
below is running it if i hardcode 4312 in as a whole number - but what id like to to accept it dynamically ... can somebody help point me in the right direction
#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()
4 Answers 4
It's easier if you don't immediately call convert the user input to a float
. Strings provide a split
function, floats don't.
>>> 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
-
This will fail if the input has no seconds component.Burhan Khalid– Burhan Khalid01/08/2015 11:20:55Commented Jan 8, 2015 at 11:20
You are already converting the number into a float when you ask for it in the input; just accept it as a string and then you can easily separate it into its various parts:
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
I would have the user input a string in the format [hh:]mm:ss
then use something like:
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)
But if you really need a time then you could use time.strptime().
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."
Try this way.You can also add some error checking this way.
input
to get the time value.