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))+"."
Related
I have the following python code which is supposed to use brute force to decrypt secret message. The encryption technique is Ceasarean subsitution i.e. every letter in the alphabet is moved by a certain number of places. My main function is supposed to return the decrypted message with the letters moved by all 26 possible number of places (I hope it makes sense but its basically like ROT13 but we don't know the number. It could be ROT13, ROT5, ROT20 etc.)
The problem is my main function doesn't print out the result from the caesarBreak function.
Thanks in advance!
import sys
def caesarBreak(cipheredMsg):
alphabet = "abcdefghijklmnopqrstuvwxyz "
shift = 1
plainText = ""
for ch in cipheredMsg:
idx = alphabet.find(ch) - shift
plainText = plainText + alphabet[idx]
shift = shift + 1
return plainText
def main():
print("We will now try to break the msg: 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'\n\n")
secretmsg = 'we ovugpzghugpu lylz pungwyvnyhttpungshunahnl'
caesarBreak(secretmsg)
main()
Because you didn't ask your main function to print it.
print(caesarBreak(secretmsg))
it did return the result, if you find a place to store it then later you could print it out or do whatever you want with it.
result = caesarBreak(secretmsg)
print(result)
Agree with Yunkai Xiao, you have to use print() to print out your result.
print(#your function here)
Also, there might be other error for you to check just a fyi.
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)
I am completely new to any coding at all.
As one of my first little tasks I tried to design a program comparing numbers. I wanted to add a function that distinguishes "pi" and "e" entries and converts them into respective floats. This function, however, doesnt work fine.
# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", (number))
elif pismeno == "e":
number= float(2.71)
print ("word e converted to number:", (number))
else:
number = float(pismeno)
print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*
I guess that it has something to do with the output being stored inside the function and not "leaking" outside to the general code. Please keep in mind that I have literally NO experience so stick to a child language rather than the usual professional speech.
If you are writing a function, you need a return statement. A simplified example of your code:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", number)
return number
else:
....
....
input1=input("insert a number:")
print(convert(input1))
I really suggest you to study basic concepts of programming. You may start here: https://www.learnpython.org/. More about functions: https://www.learnpython.org/en/Functions
The number you chose is: pi" instead of "The number you chose is: 3.14"
Your current final print just prints the input you originally gave it (input1)
You need to provide a way to return a value from the function and then set that to a variable where you call it
def convert(pismeno):
... Code ...
return number
# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )
Question: write a program which first defines functions minFromList(list) and maxFromList(list). Program should initialize an empty list and then prompt user for an integer and keep prompting for integers, adding each integer to the list, until the user enters a single period character. Program should than call minFromList and maxFromList with the list of integers as an argument and print the results returned by the function calls.
I can't figure out how to get the min and max returned from each function separately. And now I've added extra code so I'm totally lost. Anything helps! Thanks!
What I have so far:
def minFromList(list)
texts = []
while (text != -1):
texts.append(text)
high = max(texts)
return texts
def maxFromList(list)
texts []
while (text != -1):
texts.append(text)
low = min(texts)
return texts
text = raw_input("Enter an integer (period to end): ")
list = []
while text != '.':
textInt = int(text)
list.append(textInt)
text = raw_input("Enter an integer (period to end): ")
print "The lowest number entered was: " , minFromList(list)
print "The highest number entered was: " , maxFromList(list)
I think the part of the assignment that might have confused you was about initializing an empty list and where to do it. Your main body that collects data is good and does what it should. But you ended up doing too much with your max and min functions. Again a misleading part was that assignment is that it suggested you write a custom routine for these functions even though max() and min() exist in python and return exactly what you need.
Its another story if you are required to write your own max and min, and are not permitted to use the built in functions. At that point you would need to loop over each value in the list and track the biggest or smallest. Then return the final value.
Without directly giving you too much of the specific answer, here are some individual examples of the parts you may need...
# looping over the items in a list
value = 1
for item in aList:
if item == value:
print "value is 1!"
# basic function with arguments and a return value
def aFunc(start):
end = start + 1
return end
print aFunc(1)
# result: 2
# some useful comparison operators
print 1 > 2 # False
print 2 > 1 # True
That should hopefully be enough general information for you to piece together your custom min and max functions. While there are some more advanced and efficient ways to do min and max, I think to start out, a simple for loop over the list would be easiest.
So first let me say that I am a novice at Python and functions seem to be out of my comprehension for the moment but where I am having trouble is having 3 functions be able to call each other. Here is my code(yes I know it is terribly wrong but you should see where I am going):
def menu():
count=gearboxes
cost=subtotal
return subtotal
def quantity():
gearboxes=raw_input("How many gearboxes would you like to order? ")
return menu()
def subtotal(cost):
if (gearboxes<=10):
cost=gearboxes*100.0
print cost
elif (gearboxes>10 and gearboxes<20):
cost=(gearboxes-10)*80.0+1000.0
print cost
elif (gearboxes>20):
cost=(gearboxes-20)*70.0+1000.0+800.0
print cost
else:
print "wtf m8"
return menu()
def summary():
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
print quantity()
print subtotal(menu)
print summary(menu)
There is it and any help would be greatly appreciated if you could explain also kind of how functions call on each other.
Thanks!
fixed version(still working)
def quantity():
motors=raw_input("How many motors would you like to order? ")
gearboxes=raw_input("How many gearboxes would you like to order? ")
sensors=raw_input("How many sensor boards would you like to order? ")
return int(motors),int(gearboxes),int(sensors)
def subtotal(motors,gearboxes,sensors):
if motors<=10 and gearboxes<=15:
motorCost=motors*100
gearboxCost=gearboxes*50
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
if motors>10 and motors<=20 and gearboxes>15 and gearboxes<=30:
motorCost=(motors-10)*80+1000
gearboxCost=(gearboxes-15)*40+750
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
elif motors>20 and gearboxes>30:
motorCost=(motors-20)*70+1000+800
gearboxCost=(gearboxes-30)*30+750+600
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
def summary(motors,gearboxes,sensors,motorCost,gearboxCost,sensorCost):
print "="*80
print "%60s %20d %20d" % ("motors",motors,motorCost)
print "%60s %20d %20d" % ("gearboxes",gearboxes,gearboxCost)
print "%60s %20d %20d" % ("sensor boards",sensors,sensorCost)
print "="*80
def menu():
a,b,c=quantity()
d,e,f=subtotal(a,b,c)
summary(a,b,c,d,e,f)
return
menu()
I made some changes to your code. Treat a function like a question. When you call the function; you're asking the question. What you pass to return is the answer to the question. So when someone asks for the subtotal of some number of gearboxes; we return cost, whatever that may be.
We can then store the return values (the answers) in variables and use them later. For example, to pass to another function. Try to follow how information flows through the program.
def quantity():
count=raw_input("How many gearboxes would you like to order? ")
return int(count)
def subtotal(count):
if count<=10:
cost=count*100.0
return cost
elif count>10 and count<20:
cost=(count-10)*80.0+1000.0
return cost
elif count>20:
cost=(count-20)*70.0+1000.0+800.0
return cost
def summary(count, cost):
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
def menu():
items = quantity()
sub = subtotal(items)
summary(items, sub)
if __name__ == '__main__':
menu()
"subtotal" already calls menu() so I'm not sure what you are asking since you are already calling one function within the other.
Also, I can't see what your program is supposed to do - if your function names would be verbs (print_menu, get_menu, set_menu, throw_menu_on_moon, calculate_subtotal, ...) it would be better to understand for humans.
Also, the names you use (on the right hand side of =) within a function must be known there, so for example
def menu():
count=gearboxes
makes no sense (because "gearboxes" is unknown - on the other hand, "count" is fine since it defines new variable - since it is on the left hand side of =)...
Note that variables are only known within the function you defined them in, so
def f():
gearboxes = 2
def menu():
count=gearboxes
would make no sense either.
But
def f():
return 2
def menu():
gearboxes=f()
count=gearboxes
would make perfect sense.
Read the
def calculate_subtotal(gearbox_count):
as "to calculate subtotal of gearbox count do".
If you then say anywhere outside:
calculate_subtotal(5)
^^^^^^^^^^^^^^^^^^^^^
then the underlined part will be replaced by the result returned.
Otherwise, in Python the lines (in a block) are executed one after another - if you want to do multiple things in sequence, you can just write them one line each, one after another.
"return" is not "goto", "return" gives back the result - and control - to the caller of the function. Then the result is placed into the program "instead of the call".