the problem that is occurring in my code is that any variable
(in this case time and option_1 ) written to a textfile outputs ' none ' as an outcome in the actual textfile.
time=print ("This is the time and date: "
,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
option_1=print("50p for 1 hour(S) stay")
with open("recipt.txt", "w") as recipt:
recipt.write("you time\n {}".format(time))
recipt.write("the time you stayed for and your payment\n
{}".format(option_1))
recipt.close()
thanks in advance
The print function returns None. You want to build a str object rather than use print.
time= "This is the time and date: " + datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
option_1= "50p for 1 hour(S) stay"
time=print ("This is the time and date: ")
In Python, every function returns a value. If a value is not specified, None is returned. The print function does not specify a return value, therefore it returns None. In your example, you are assigning the return value of print (which is None) to the time variable. Instead, set time equal to the current datetime.
time = datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
Then concatenate your print statement, and the current datetime.
print("This is the time and date: " + time)
Related
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 :)
I want to increment the variable inside the print statement, so it would not take 2 lines of code.
I have the following code:
yearCount += 1
print("Year ",yearCount,":",sep = "")
How can I do something like:
print("Year",yearCount+=1,":",sep = "")
For printing only, you can use f-strings, available in v3.6+:
print(f'Year {yearCount+1}:')
If you also need to increment the variable itself, I would stick with the two-liner; it's best to be clear and differentiate between calculations and printed output.
A not recommended answer to your question would be:
yearCount += 1; print(f'Year {yearCount}:')
Use format to format the string for printing and not actually incrementing the value
print("Year {}".format(yearCount+1))
You can go through official doc for print function Documentation.
a = 2
print("Sum is :", a+3)
output is :
Sum is :5
It is not possible to initialize variable(s) within print(). The best thing that you could do is call a function via f-string. Use that called function to increment the variable that you want.
yearCount = 2018
def yearInc():
global yearCount
yearCount+=1
return yearCount
print(f"Year {yearInc()}")
print(f'Year {yearCount}')
The output is:
Year 2019
Year 2019
This solution may be wasteful if you just to call this function once.
I have a created a function to print out the statistics of a tokenized text:
def print_statistics(text):
print("\nThe total number of tokens is " +str(number_of_tokens(ny))+".")
return ???
This function gives me two outputs (the second is "none"). But I want the function to give me the print output. Any idea how I can do this?
The function could return the string to print:
def get_statistics_string(text):
return "\nThe total number of tokens is " + str(number_of_tokens(ny)) + "."
Or print the statistics:
def print_statistics(text):
print("\nThe total number of tokens is " + str(number_of_tokens(ny)) + ".")
# note that it will still return None)
It is usually a good idea to decide that a function will either do something, or return something, not both.
If you want the function to print the required output, then do the following:
def print_statistics(text):
print("\nThe total number of tokens is " +str(number_of_tokens(ny))+".")
return
Else if you want your function to return the required output, do the following:
def print_statistics(text):
return "\nThe total number of tokens is " +str(number_of_tokens(ny))+"."
This function gives me two outputs (the second is "none").
You are executing the function in your Python shell (the builtin one, IPython or whatever). The Python shell always display the result of the last expression you eval'd. Since your function doesn't explicitely returns anything, it (implicitely) returns None, which is your "second output" - the first "output" being the function printing to sys.stdout. If you execute this function from a script, you will only see what the function prints.
What you mean by "I want the function to give me the print output" is quite unclear. If you want your function to print to sys.stdout then it's done, you have nothing to change. If you want it to instead return the formatted string (the one it currently prints) as a Python variable, then replace print('yourstringhere') by return 'yourstringhere'.
As a side note: learn to use proper string formatting, it's much easier to read and maintain:
nb_tokens = number_of_tokens(ny)
msg = "\nThe total number of tokens is {}.".format(nb_tokens)
# then either `print(msg)` or `return msg`
You can just have the function return the output, like:
def print_statistics(text):
return "\nThe total number of tokens is " +str(number_of_tokens(ny))+"."
I am trying to print the current time before my normal prints
global begtime
begtime = str(datetime.datetime.now()).split('.')[0]
global secondtime
secondtime = begtime.split(' ')[1]
global time
time = '[' + secondtime + ']' + ':'
print time
datetime.datetime.now returns in the format of :
year.month.date hour.minute.second
so I first split at the '.' to get the individual times, then I split at the space to get just the time.
then I formatted it as [hour:min:sec]
It works, but the time is not correct, it will print same time for all prints even if they happen minutes apart.
I want the exact time for every print.
For your code, you're probably setting the time earlier in your program and then accessing it later thinking it is generating a new time. It won't generate a new time every time you print it. It will only generate a new time every time you run begtime = str(datetime.datetime.now()).split('.')[0]
The better way to do this would be to use Date.strftime(format). I've included an example of this below.
import datetime
import time
now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))
time.sleep(10)
now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))
This will print the current time and then 10 seconds after the current time after 10 seconds.
Python Question:
I've been trying to get Python 3 to print the mean, sum/len of my dictionary.
I've been looking at methods on stack overflow of how to find the mean of values in a dictionary but every time I try to do it using the keys of values in a dictionary I am riddled with errors. I was able to get the len to work but dividing it doesn't work.
*TL:DR How do I print the mean of values from a Dictionary? on the commented line.
I have cleaned out my code and left an empty line to put in the correct code.
import operator
"Dictionary"
time = {
'Kristian':19,
'Alistair':27,
'Chris':900,
'Maxi':50,
'Jack':15,
'Milk Man':1
}
print(time)
print ("-------------------------------")
"Printing the List"
for xyz in time:
print ("-------------------------------")
print("\nStudent Name: ", xyz,"\n Time: ", time[xyz],"seconds\n")
"Printing the Results"
def results():
print ("-------------------------------")
print("\nThe Fastest Time is: ",(time[min(time, key=time.get)]),"seconds")
print("\nThe Slowest Time is: ",(time[max(time, key=time.get)]),"seconds")
print("\nNo. of Competitors: ",len(time))
"//////////Here is where I want to print the mean score\\\\\\\\\\"
results()
"Adding to the Results"
def question():
person = input("\nPlease enter the student's name: ")
secs = int(input("Please enter the student's time in seconds: "))
print("The results you have added are:")
print("\nStudent Name: ", person,"\n Time: ", secs,"seconds\n")
sure = input("Are you sure? ").lower()
if sure in ("no", "n", "nope"):
question()
else:
time.update({person:secs})
print("Student has been added successfully.")
results()
"Running the loop"
question()
you mean the values of the dictionary, not the keys, right? then this would work (using statistics.mean):
from statistics import mean
time = {
'K':19,
'Al':27,
'Chris':900,
'Max':50,
'Jack':15,
'Milk Man':1
}
print(mean(time.values())) # 168.66666666666666
using dict.values you could also easily get the maximal value a little simpler:
print(max(dct.values()))
maybe time is not the best name for the dictionary; there is a module in the standard library called time. you'd overwrite this module should you import it in the same file.
dict.values() returns the list of all the values in the Python dictionary. In order to calculate the mean, you may do:
>>> time_values = list(time.values())
# ^ Type-cast it to list. In order to make it
# compatible with Python 3.x
>>> mean = sum(time_values)/float(len(time_values))
# ^ in order to return the result in float.
# division on two `int` returns int value in Python 2
The value hold by mean will be:
>>> mean
168.66666666666666