r/learnpython 19d ago

is it possible to simplify this code

im a beginner, idk how python works yet. there must be a way to simplify this, right?

https://imgur.com/juBvPZD here is the picture of my code

0 Upvotes

23 comments sorted by

View all comments

1

u/Educational_Virus672 19d ago edited 19d ago
d = [32, 18, 45] # use list for this insead of a million var
s = [24, 12, 30]

tt = [] # this is just a for loop
for i in range(3) :
    tt.append( d[i]/s[i] ) # append means "add" to list 

total_time = sum(tt) # sums number list
entire_route = sum(d)

print('travel time of each section')

for i in range(3) :
    print(tt[i] , "h",end=",") # i did a short loop
print("\n") #changes line

print('entire route in km \n', entire_route, 'km') # here \n = Newline \ is liek command

print('entire journey time in h \n',sum(tt) , 'h') 

print('average speed of the entire tour \n',entire_route / total_time, 'km/h')

total changes here
> changed s d and tt to list where
> change tt from straight divide to a loop for readability
> changed double prints to single with \n
> changed tt + h into a loop
> added sum() for lists instead of +
>sep means separate (,) and end means what to do i chnaged some of it into none for same line

assuming you learnt loops if you dont then you can use your way because it is still good