I'm trying to create a program that will allow me to enter a value in minutes and the program will output those minutes as the sum of days, hours and minutes between them.
For example if I input 10000 minutes I should get the output, "10000 minutes is 6 days, 22 hours and 40 minutes"). This is how much I have now:
min = int(input("Enter a whole number of minutes: "))
days = min/1440
remainday = min%1440
print (days)
I'm only having one problem asides from it being unfinished, if the user inputs a number of minutes under 1440 then i get a decimal answer for the number of days (which is expected) but if the number of minutes is not sufficient to make a day, then I want the it to say "0 days" not ".153 days". How would I zero out the value for days in such a case?
You are using Python 3 so the operator / is true division, not integer division.
You can either use floor division which is similar to Python 2's integer division:
days = min//1440
Or use divmod to get both with a single command:
days, remaindays = divmod(min,1440)
You can use floor division (using a double // instead of a single / when dividing), which rounds down to the nearest integer:
min = int(input("Enter a whole number of minutes: "))
# Example input: 1000
days = min // 1440
remainday = min%1440
print (days)
# Output:
# 0
You essentially want to round down the result of the division (quotient) to the nearest integer.
This can be done in many ways:
days = int(min/1440)
Or
days = min//1440 # // is the integer division in Python 3, while / is float division`
Or
days = math.floor(min/1440) # after importing "math" module, using "import math"
Related
split(aTime), which accepts a parameter representing a time in 24-hour mode. The function will return the time as a tuple consists of two integers – the hour and minute of the parametric time.
from :
split(1240)
so aTime have 2 integer aTime(12,40)
like how we divide the 3/4 digit into two, so if the input 725 it will be 7,25 or 1234 it will be 12,34
Since it's unclear if the input is a string or an integer I took a generic approach.
def time_split(value):
normalized_value = f'{value:0>4}'
return int(normalized_value[:2]), int(normalized_value[2:])
Alternative version:
def time_split(value):
return divmod(int(value), 100)
If your time is given as an integer, then you can use divmod.
def time_split(time):
return divmod(time, 100)
my_time = time_split(1240)
print(my_time) # (12, 40)
If your time is given as a string, then you can use slicing.
def time_split(time):
return int(time[:-2]), int(time[-2:])
In basic shool you probably learned division like this: 13 divided by 5 is 2 with 3 remaining.
We have this concept in computer programming as well, but it is usually split in two operations:
Part 1: Integer division: 13 // 5 = 2 (gives you the result)
Part 2: modulo: 13 % 5 = 3 (gives you the remainder)
For your problem, you can use 100 for that division operation. 725 divided by 100 is 7 with 25 remaining (7 hours 25 minutes). 1234 divided by 100 is 12 with 34 remaining (12 hours and 34 minutes).
def time_split(number:int) -> tuple:
hours = number // 100
minutes = number % 100
return (hours, minutes) # A tuple holding both numbers
I'm trying to learn Python, with a project where I'm reading data from a bike power meter. Right now I'm just calculating the average power from start to finish, by adding each power reading to a total sum variable, and dividing it with the number of readings.
I'd like to calculate the average power for 20 minutes, and if possible, keep calculating the 20 minute average each 30 seconds after the first 20 minutes, comparing to the previous value and storing it if it's higher than the last, so in the end I could have the higher 20 minute average power that I held during a one hour workout, no matter where it happened in that hour, for example.
Data from the power meter is event based, as far as I can tell it's not a regular intervals, but definitely once a second or faster.
This is the base of my code so far:
def average_power(power, count):
global PM1_sumwatt
global PM1_avgwatt
PM1_sumwatt = PM1_sumwatt + power
PM1_avgwatt = PM1_sumwatt / count
PM1_avgLog = open(PM1_avgFile, 'w')
PM1_avgLog.write("<div id=\"pwr\"> %d W</div>" % (PM1_avgwatt))
PM1_avgLog.close()
def power_data(eventCount, pedalDiff, pedalPowerRatio, cadence, accumPower, instantPower):
global PM1_avgcount
if WCORRECT1: calibpower = instantPower+(CF1w)
else: calibpower = instantPower*(CF1x)
power_meter.update(int(calibpower))
PM1_avgcount = PM1_avgcount + 1
average_power(int(calibpower), PM1_avgcount)
power = BicyclePower(readnode, network, callbacks = {'onDevicePaired': device_found,
'onPowerData': power_data})
# Starting PM readings
power.open(ChannelID(PM1, 11, 0))
Not quite sure how to tackle this! Any help or pointer is much appreciated!
if you are reading data in real time, I assume you are reading the data in a while loop:
sum = 0
number_of_readings = 0
while True: # forever
new_value = input() # here I read from the console input
sum += new_value
number_of_readings += 1
average = sum/number_of_readings
print(average)
Here I type a number in the console and press enter to simulate your bike power meter.
>>> 1
1.0
>>> 3
2.0
>>> 4
2.6666666666666665
>>> 2
2.5
Now, if you wants to make a moving average, you must store the readings that you wants to average. This is because you want to remove them later, when they will be too old. A list is perfect for that:
Here is a solution averaging the last n readings:
n = 2
Last_n_readings = []
while True: # forever
# add a new reading
new_value = int(input()) # here I read from the console input
Last_n_readings.append(new_value)
# discard an old one (except when we do not have enough readings yet)
if len(Last_n_readings) > n:
Last_n_readings.pop(0)
# print the average of all the readings still in the list
print(sum(Last_n_readings) / len(Last_n_readings))
Which gives:
>>> 1
1.0
>>> 3
2.0
>>> 4
3.5
>>> 2
3.0
Note that lists are not very efficient when removing elements near the start, so there are more effective ways to do this (circular buffers), but I try to keep it simple ;)
You could use this by guessing how many readings/seconds you have and choose n so you average over 20 minutes.
If you want to truly average all the result which are less than 20 minutes ago, you need to not only record the readings but also the times when you red them, so you can remove the old readings wen they get more than 20 minutes old. If this is what you need, tell me and I will expand my answer with an example.
You can use pandas dataframe to store the power output for each instance.
Considering that you receive a value each 30 second, you can store them all in data frame.
Then calculate a 40 data point moving average using rolling function in python.
Take the max value you get after the rolling function, this would be your final result.
refer this for doc : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 months ago.
I'm a programming beginner trying to learn Python. I'm trying to complete the following exercise:
Write a program to prompt the user for hours and rate per hour to
compute gross pay.
Here's what I came up with:
hours = input("Enter number of hours worked\n")
rate = input("Enter pay rate per hour\n")
print(hours * rate)
Of course, I receive the error:
TypeError: can't multiply sequence by non-int of type 'str'
How can I tell Python that the results of the input should be regarded as integers rather than strings?
Any input from the input function is stored as string, you have to convert them both to integers before multiplying like this:
hours = input("Enter number of hours worked\n")
hours = int(hours)
rate = input("Enter pay rate per hour\n")
rate = int(rate)
print(hours * rate)
Of course you need to convert to appropriate type before multiplication, since input("") returns string of user input.
The conversion is as follows:
rate -> float
hours -> int
This is to make sure that you don't loose decimal points where user enter rate with decimals eg 2.2
So from your code you can add the following
hours = int(input("Enter number of hours worked\n"))
rate = float(input("Enter pay rate per hour\n"))
print(hours * rate) # int * float gives float
Problem solved:
hours = int(input("Enter number of hours worked\n"))
rate = int(input("Enter pay rate per hour\n"))
I figured the int function had to be placed in there somewhere.
This question already has answers here:
What is the difference between '/' and '//' when used for division?
(16 answers)
Closed 6 years ago.
I'm having some trouble running the code I wrote.
meal = float(raw_input("How much did your meal cost? "))
tax = 6.75 / 100
tip = 15 / 100
total = (meal * tax) * tip
print total
You can see above that I made this "tip calculator". Whenever I enter a number, it returns with zeros. It seems like it's skipping the entire calculation part.
Any solution?
If it is python 2.7 you are doing integer division, which means your tip is calculating as 15/100 = 0.
from __future__ import division
At the the top of the program will solve this.
In python 2, / is integer division. Thus, 15 / 100 = 0, and you miltiply by that. Just replace 15 with 15.0
The problem is on this line:
tip = 15 / 100
Dividing an int by an int will result in an int. In this case 15 / 100 gives you 0, and the complementary modulo operation 15 % 100 gives the 15 remainder.
If you change 15 to a float it will work because precision is preserved and tip will be a float instead of an int. Try:
tip = 15.0 / 100
def main():
#Get amount of principal, apr, and # of years from user
princ = eval(input("Please enter the amount of principal in dollars "))
apr = eval(input("Please enter the annual interest rate percentage "))
years = eval(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0:5d} {0:5d}'.format(years, princ))
I'm trying to print the years and the principal value in a table, but when I print all that comes out is two columns of 10.
So you have several problems. The first problem is a display issue.
Your output statement print('{0:5d} {0:5d}'.format(years, princ)) has several issues.
printing years instead of i, so it's always the same value instead of incrementing
the 0 in the format statement{0:5d} means the 0'th element out of the following values, so you're actually printing years twice, the second one should be 1 instead of 0
you're using d to print what should be a floating point value, d is for printing integers, you should be using something along the lines of {1:.2f} which means "print this number with 2 decimal places
Once you've corrected those you'll still see incorrect answers because of a more subtle problem. You're performing division with integer values rather than floating point numbers, this means that any decimal remainders are truncated, so apr / 100 will evaluate to 0 for any reasonable apr.
You can fix this problem by correcting your input. (As a side note, running eval on user input is usually an incredibly dangerous idea, since it will execute any code that is entered.) Instead of eval, use float and int to specify what types of values the input should be converted to.
The following is corrected code which implements the above fixes.
#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0} {1:.2f}'.format(i, princ))