Andrew Mizuno
Andrew Mizuno

Reputation: 13

Convert time interval to seconds

Hi having trouble returning the value in seconds. Right now it is just returning mutiple 1's like this 1111111111111111111111111111111111111.

Should be returning 4220.

my input is 1 10 20 for example.

any help appreciated!

thanks

# File: WS01p1.py
# Write a program that prompt to read a time interval in hours,
# minutes and seconds and prints the equivalent time in just seconds.

x,y,z = input("Input: ").split()
print(x*3600 + y*60 + z)

Upvotes: 1

Views: 318

Answers (4)

Thesonter
Thesonter

Reputation: 300

x, y, z = map(int,input("Input:").split())

print(x,y,z)

Input: 1 10 20

Output = 4220

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881153

Your problem can be explained thus:

>>> print('1' * 7)
1111111

When you "multiply" a string s by an integer n, you get a string of n copies of s. What you need is an integer multiplied by an integer. You can convert a string with int(), such as:


vals = input('Input: ').split()
try:
    hrs  = int(vals[0])
    mins = int(vals[1])
    secs = int(vals[2])
    print(f'That is {hrs * 3600 + mins * 60 + secs} seconds')
except:
    print('Invalid input')

And, just as an aside, I don't know whether that's your real code or something you threw together to post here, but you should probably choose better variable names if the former. Anyone seeing x/y/z will almost certainly assume you're doing something with a 3D cartesian coordinate system rather than time-based stuff :-)

Upvotes: 2

Samwise
Samwise

Reputation: 71434

You need to apply the int function to each of the values you get from split() in order to turn them from base-10 str values to int values.

>>> h, m, s = map(int, input("Input: ").split())
Input: 1 10 20
>>> print(h*3600 + m*60 + s)
4220

Upvotes: 2

vht981230
vht981230

Reputation: 4480

You need to turn the input into int value instead of str, which is assigned tox, y, z after split(). You can convert a str object to int using int(<var>) function. So in this case, it would be

print(int(x)*3600 + int(y)*60 + int(z))

Upvotes: 3

Related Questions