as you can probably tell, I am a python beginner. In this program, I am trying to use a function but instead of determining a value for minutes, I want the user to input a value. For the return command of my function, I first used a comma to separate the variables from the string, however, this literally printed the commas in the result. So instead, I used a + operation but had to turn my erstwhile integer values into strings. Is there any way I could have printed the values without turning them to strings while also avoiding the type error?
here's my code
def minutes_to_hours (minutes):
hours = minutes/60
seconds= minutes*60
return str(minutes) + " minutes is equivalent to " + str(hours) + " hours" + ". This is also equivalent to " + str (seconds) + " seconds."
m= int((input ("please enter the value of minutes you want to convert ")))
print(minutes_to_hours(m))
You can also do this:
def minutes_to_hours (minutes):
hours = minutes/60
seconds= minutes*60
return "{} minutes is equivalent to {} hours. This is also equivalent to {} seconds.".format(minutes, hours,seconds)
m= int((input ("please enter the value of minutes you want to convert ")))
print(minutes_to_hours(m))
No, to print integers you need to convert them to strings before, so your code is correct.
Yes you can use comma between variables and strings but it requires changes
def func(m):
s=m*60
h=m/60
return s,h
m= int((input ("please enter the value of minutes you want to convert ")))
s,h=func(m)
print(m,"minutes are equivalent to",s,"seconds and",h,"hours)
One of the approach out many other approaches will be to let your function return a list and you print the list by specifying its index.
def minutes_to_hours (minutes):
hours = minutes/60
seconds= minutes*60
return [minutes, hours, seconds] ## return your calculated value as list
m= int((input ("please enter the value of minutes you want to convert ")))
result = minutes_to_hours(m)
print(f"{result[0]} minutes is equivalent to {result[1]} hours. This is also equivalent to {result[2]} seconds.")
Hope this helps :)
Related
I really need help on this. Trying to create a code that determines the average temperature for an inputted amount of days. I have the input statement correct and converted to int. However, in the loop, I need it to ask the user each time
What temp was it on day X, with X being the the first day and it repeating and increasing the value each time it loops. Please help me anyone.
Here is the code below:
#Determine average temperature
days = input("How many days are you entering temperatures for:")
days = int(days)
sum = 0
for i in range(days):
temperature = input("What temp was it on day?")
temperature= int(temperature)
sum = sum + temperature
average_temperature = sum/int(days)
print("Average temperature:", average_temperature)
You can use a formatted f-string to include a variable in a string as suggested by #JohnGordon:
temperature = input(f"What temp was it on day {i + 1}? ")
It's usually a good idea to separate input/output and calculations. It usually also more intuitive to terminate input as you go along instead of asking for a count upfront. In this case I use enter (i.e. empty string as input) to signify that you are done asking for input:
import itertools
temperatures = []
for i in itertools.count(1):
temperature = input(f"What temp was it on day {i}? ")
if not temperature:
break
temperatures.append(int(temperature))
average_temperature = sum(temperatures) / len(temperatures)
print(f"Average temperature: {average_temperature}")
You can use built-in method str to convert int to str.
temperature = input("What temp was it on day "+ str(i+1) + " ? ")
I am trying to write a simple calculator to calculate how fast my battery will drain from 100% to 0% by taking a time and percentage for start and subtracting it from the finish time and percentage.
I was able to make a quick and dirty script to accomplish this, but I am learning OOP, and I would like some feedback on how to improve my code and implement OOP for this task. I added in some verbose print statements to make it easier for me to remember what everything is when I run it, and I intend to wrap it up into a simple bash script or maybe implement tkinter for GUI.
Any thoughts or suggestions will help! My main environment is python 3, but I added the error handling for those who run with python2 because it doesn't like a preceding 0 in the time number.
from datetime import timedelta
# Getting inputs for time and percentage
try:
start_time = str(input('What is the starting time in 24 hour time? Format: HHMM >> '))
start_time_hr = start_time[:2]
start_time_min = start_time[2:]
except SyntaxError:
print('Try entering the time again without the preceding 0. \n')
start_time = str(input('What is the starting time in 24 hour time? Format: HHMM >> '))
start_time_hr = start_time[0]
start_time_min = start_time[1:]
start_perc = int(input('What is the starting battery percentage? >> '))
try:
end_time = str(input('What is the finish time in 24 hour time? Format: HHMM >> '))
end_time_hr = end_time[:2]
end_time_min = end_time[2:]
except SyntaxError:
print('Try entering the time again without the preceding 0. \n')
end_time = str(input('What is the finish time in 24 hour time? Format: HHMM >> '))
end_time_hr = end_time[0]
end_time_min = end_time[1:]
end_perc = int(input('What is the ending battery percentage? >> '))
# Turning numbers into times for calculation
start = timedelta(hours=int(start_time_hr), minutes=int(start_time_min))
end = timedelta(hours=int(end_time_hr), minutes=int(end_time_min))
# Calculating and printing the results
perc_difference = float(-(end_perc - start_perc))
time_difference = end - start
time_difference_minute = time_difference.total_seconds() / 60
discharge = (100.0 * time_difference_minute / perc_difference) / 60
print()
print()
print('*****')
print('Percentage Difference = ' + str(perc_difference))
print('Minutes Passed = ' + str(time_difference.total_seconds() / 60))
print('100% to 0% in ~' + str(round(discharge, 2)) + ' hours.')
print('*****')
print()
print()
print()
I don't think this program will benefit from using OOP.
That said; I do have a few notes on style and lack of defensive programming.
First; You do not need to wrap an input call with str, since it returns a string by default.
Second; You have wrapped a couple of your input calls with int, which is perfectly fine, but these need to be wrapped in try blocks as any input that cannot be converted to an integer will raise a ValueError.
Third; You should NEVER be handling a syntax error in that way. If you're getting syntax errors, fix the code, don't try to wrap it with a bandaid.
Fourth; You do not need to write that many print statements.
The entire print block could be rewritten as follows:
print('*****\nPercentage Difference = ' + str(perc_difference) + 'Minutes Passed = ' + str(time_difference.total_seconds() / 60)) + "\n100% to 0% in ~' + str(round(discharge, 2)) + ' hours.\n' +
*****')
Or, in my opinion; the much more readable fstring variant:
msg = f"*****\nPercentage Difference = {perc_difference}\nMinutes Passed = {time_difference.total_seconds() / 60}\n100% to 0% in ~{round(discharge,2)} hours.\n"
print( msg )
I need to make a simple program which converts a 24 hour time which is input, into 12 hour time, which produces an error if an incorrect time is put in. I currently have the code below, however, I have a few issues. One issue is that if "0924" is input, it outputs "924 am", when I need it to produce "9:24am" (the space isn't hugely important but it's preferred). Also, I'm not entirely sure where to start for doing 0001-0059, because "0001" for example produces "1 am", which is obviously incorrect.
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = (time - 1200)
print (int(normal), ("pm"))
elif (time<1200):
normal = time
print (int(normal), ("am"))
Thanks in advance for any help!
Try this
import time
timevalue_24hour = "1620";
timevalue_24hour = timevalue_24hour[:2] + ':' + timevalue_24hour[2:]
print (timevalue_24hour)
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )
print (timevalue_12hour)
Take input as a string. Assign it to timevalue_24hour and rest will work
When printing, normal is just a number. The 0s disappear because you don't write 0s in front of numbers normally. I would suggest doing something like this
def normal_check(num):
if num < 10:
return "000"+str(num)
elif num < 100:
return "00"+str(num)
elif num < 1000:
return "0"+str(num)
else:
return str(num)
print("Enter a time in 24 hour time, e.g. '1620'")
time = (int(input("Time: ")))
normal = 0
if (time == 0000):
normal="12:00am"
print (normal)
elif (time>1200):
normal = normal_check(time - 1200)
print (normal, ("pm"))
elif (time<1200):
normal = normal_check(time)
print (normal, ("am"))
The best way to do this will be to take the input as an str rather than int. Take it in as str and split it into two int values of two digits.
Then the first string if less than 12 will be hour else subtract 12 from first str and use PM. Also, the second str will just be minutes.
Edit: Apparently I was using python 2. Switching to 3 fixed the issue and now I am getting the proper results without the parentheses/commas. Thanks for the replies - problem solved :D
Beginner at Python and coding in general. Struggling with my first project assignment, but I've gotten so close on my own.
My assignment is to create a code in python that counts the number of coins from a given value i.e. quarters, nickels, dimes, pennies.
My initial code looks like this:
coins=input('Enter amount of change: ')
print("Quarters", coins//25)
coins = coins%25
print("Dimes", coins//10)
coins = coins%10
print("Nickles", coins//5)
coins = coins%5
print('Pennies', coins//1)
Which prompts something like, "Enter amount of change: 86"
('Quarters', 3)
('Dimes', 1)
('Nickles', 0)
('Pennies', 1)
These are the correct values, but my instructor wants it to look like this:
Enter amount of change: 86
Quarters: 3
Dimes: 1
Nickles" 0
Pennies: 1
I can get the colon in there, but how can I remove the parentheses and commas? Thanks
You can use str.format() to produce the required output. For example for quarters:
print('Quarters: {}'.format(coins//25))
This will work in both versions of Python.
The simplest solution I've always used to print values in Python 2, which is the Python version you appear to be using, is the following:
coins=int(input('Enter amount of change: '))
print "Quarters: %i" % (coins//25)
coins = coins%25
print "Dimes: %i" % (coins//10)
coins = coins%10
print "Nickles: %i" % (coins//5)
coins = coins%5
print 'Pennies: %i' % (coins//1)
The % symbol, when used with strings, allows whatever value you want to be printed to be substituted in the string. To substitute multiple values, you separate them with commas. For example:
someInt = 1
someStr = 'print me!'
print "The values are %i and %s" % (someInt, someStr)
This code will substitute in someInt and someStr for %i (used for integers) and %s (used for strings), respectively.
However, the % symbol also functions as the modulus operator, so it does 2 different things when it is being used with strings and when it is being used among two numbers.
Please check :
coins=input('Enter amount of change: ')
print "Quarters:",coins//25
coins = coins%25
print "Dimes:",coins//10
coins = coins%10
print "Nickles:",coins//5
coins = coins%5
print "Pennies:",coins//1
To use the print() syntax on python2 add this to the top of your program:
from __future__ import print_function
otherwise python will interpret the argument to print as a tuple and you'll see ().
I am using Python 3 and the following lines exactly give what your instructor wants:
coins=float(input("Enter amount of change: "))
print("Quarters:", round(coins//25))
coins = coins%25
print("Dimes:", round(coins//10))
coins = coins%10
print("Nickels:", round(coins//5))
coins = coins%5
print("Pennies: %.0f" % coins)
It seems like you are using Python 2. I think you intended to use Python 3 given your use of input() and print() methods, but the code will work in Python 2 by changing print() methods to print keywords. Your code would look like the following in "proper"* Python 2:
coins = input('Enter amount of change: ')
print 'Quarters: ' + str(coins // 25)
coins = coins % 25
print 'Dimes: ' + str(coins // 10)
coins = coins % 10
print 'Nickles: ' + str(coins // 5)
coins = coins % 5
print 'Pennies: ' + str(coins)
Hope this helped!
Footnote: Using % is preferred over using string concatenation, but I still believe that it is easier to read for beginners this way.
The objective is to write a program that will increase the population every 7 and 35 seconds and decrease every 13 seconds. I am trying to use a loop for this program and I am having some problems with getting the right casting for each variable. Here's the code:
#(1)There is a birth every 7 seconds (2)There is a death every 13 seconds (3)There is a new
immigrant every 35 seconds.
#CURRENT POP: 307,357,870
populationCurrent = input("What is the current population")
x=0
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
x=x+1
elif (x%13==0):
populationCurrent=populationCurrent-1
x=x+1
elif (x%35==0):
populationCurrent+=1
x=x+1
else:
x=x+1
print("The population will be "+int(populationCurrent)+".")
Thank you for your time.
I think you are confused in python2 and python3, there's a difference in input() function of python 2.x and python 3.x, where input() function gives an integer value in python 2 and str in python 3
input() is str by default so, this should be converted to int
populationCurrent = str(input("What is the current population"))
You cannot concatenate string and int
print("The population will be "+str(populationCurrent)+".")
Its easier to do this than iterate through 100 times
populationCurrent += 100//7 + 100//35 - 100//13
You need to convert populationCurrent to an integer immediately after you read the string.
populationCurrent = int(input("What is the current population"))
Note that if you don't enter a string that is a valid integer representation, this will raise a ValueError. You might want to consider how to handle that (catch it and use a default value? catch it and try to read another value? Let the exception propagate?)
With this change, you'll have to convert the integer value back to a string for the output:
print("The population will be "+str(populationCurrent)+".")
or using any of the various string formatting tools available. It's better to have populationCurrent as an integer, since there are more places in your code that assume it to be an integer than assume it to be a string.
The only thing you need to do is convert populationCurrent from string to int:
populationCurrent = int(input("What is the current population?"))
The more concerning stuff is that your code doesn't do what it's supposed to: when x is 35 you will only have one birth, since 35 % 7 is 0, but no immigrant will arrive. Do something like this, removing the elif statements which do not make the code that more efficient anyway:
while x!=100:
if (x%7==0):
populationCurrent=populationCurrent+1
if (x%13==0):
populationCurrent=populationCurrent-1
if (x%35==0):
populationCurrent+=1
x=x+1
print("The population will be ", populationCurrent, ".")
Though still note that the loop will stop after x gets to 100. You could reset it but I don't know for how long you want it to run.
def intInput(prompt):
while 1:
try: return int(input(prompt))
except ValueError: print("Invalid Input!")
def YearToModifier(x):
if x%35 ==0 or x%7 ==0: return 1
if x%13 == 0: return -1
return 0
populationCurrent = intInput("What is the current population?") #ensure you get an int
n_years = intInput("How Many Years?") #ensure you get an int
#in this case populationChange is independent of initial population (this is rarely the case in reality)
populationChange = sum(YearToModifier(x) for x in range(n_years))
#the population in the future is the initialPopulation + population Change ... duh...
populationFuture = populationCurrent + populationChange
print("The Population will be %d!"%populationFuture)
there you go
WRT #martjinpeters comment on OP you could change YearToModifier to
def YearToModifier(x):
return sum([x%35 ==0,x%7 ==0,-1*int(x%13 == 0)])
of coarse as #AshokaLella points out you can calculate the total births/immigrations/deaths for a given number of years without actually visiting each year
births = n_years//7
immigrations = n_years//35
deaths = n_years//13
populationChange = births + immigrations - deaths