I've got a function, displayHand() which looks like this:
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print # print an empty line
It was provided for me (from the 600x class). As described, it takes a dict of string->ints and prints out the "hand".
What I'm having troubles with is getting this to show up properly. When I try
print('Current Hand: ', displayHand(hand))
This is what I get:
a d d m o q y
('Current Hand: ', None)
Since this was provided by the instructor, I'm sure there's a reason the code was written this way and that there's something I'm not getting.
What I'd like to get is output like this:
Current Hand: a d d m o q y
I'm absolutely brand new to this stuff so I don't even know what questions to ask.
My assessment: As far as I can piece together, displayHand() doesn't return anything and that's what's screwing it all up. But how do I catch the print output of this function and present it the way I want? I was thinking I should try to catch it in a string and have that returned, but assuming
the instructor was trying to demonstrate something, how would I do it without changing the displayHand() method?
If my assessment is off, what's going on?
Edit: This function was given to me by the class, and I'll have to use it as such. I understand changing it to return a str would be much easier, but how could I accomplish the correct output without doing that?
Further Edit: I'm dealing with an autograder that demands the output exactly as I've written. Sorry to be so fussy, I appreciate the answers and would use them if it wasn't for this.
Final Edit: Thanks for the clarification -- I'm going to use your idea and make a helper function inside this function that does what I need it to do!
FINAL final Edit: I figured it out! All I had to do was,
print('Current Hand:'),
displayHand(hand)
For real final edit:
Hah! you got it too! thank you so much for the help, I appreciate it!
Your function already prints, it does not return anything.
Don't try to 'catch' the printed output, simply change the function to return the hand, formatted to a string:
def displayHand(hand):
letters = []
for letter, count in hand.iteritems():
letters.extend([letter] * count)
return ' '.join(letters)
which gives:
>>> hand = {'a': 1, 'q': 1, 'd': 2, 'y': 1, 'm': 1, 'o': 1}
>>> displayHand(hand)
'a q d d y m o'
>>> print 'Current Hand:', displayHand(hand)
Current Hand: a q d d y m o
If you are not supposed to change the displayHand() function, then use the same trick using in the function and do not print a newline by adding a comma to the end of the print statement:
print 'Current Hand:',
displayHand(hand)
You can do this if you must use the provided function and must not try to fix it:
print('Current Hand: ', end='')
displayHand(hand)
I'm confused, do you use python 2 or 3?
In python 2:
print 'Current Hand" ',
displayHand(hand)
First, your displayHand function doesn't return anything so when you try to print its result you get None. You probably need to remove those print statements from the function and return the string instead.
Second, you try to use print as a function which is possible obly in python 3 while you seem to be using python 2. If that's the case you need to remove parentheses around the print statement arguments.
If you really can't modify that function then you might want to redirect the standard output to a string before calling the function and setting it back to normal afterwards.
This post explains how to do it: Can I redirect the stdout in python into some sort of string buffer?
Related
I wanted to generate unique variable using iteration. I tried writing a code using globals() function but for some reason its not working.
for i in (range(0,7)):
for v in range(0,7):
globals()['element%s' % (i,v)] = []
You honestly just shouldn't play with globals (reading material). But your error comes from the fact that the arguments you're trying to turn to a string (i, v) have size 2, and there's a single place where you demanded a conversion: the %s. If you want it to work there needs to be 2X %s in your string:
for i in (range(0,4)):
for v in range(0,3):
print('%selement%s' % (i,v))
0element0
0element1
0element2
1element0
1element1
1element2
2element0
2element1
2element2
3element0
3element1
3element2
The problem comes with the text formating.
Try globals()[f'elements{i,v}'] = [] instead.
You can use something like this. Note that modifying globals() is rarely a good idea, have a look at this instead.
for i in range(5):
globals()['myvar'+str(i)] = i**2
print(myvar2)
print(myvar3)
Output:
4
9
Let's say I have a list 'mylist'. For example, I prepared it like this:
mylist = ['AB', 'CD', 'EF']
I need to print out each element of 'mylist' on a new line.
However, I am not allowed to use loops (as in 'for i in mylist...') and I can't say:
print(*mylist, sep = "\n")
Although the last command gives exactly the output I need.
No, I have to somehow create/prepare 'mylist' in such a way that the desired print output is achieved based on the following command:
print(mylist)
Is it even possible?
Notice, it's not a duplicate post - it's more about how to format the list to begin with, not about printing per se.
Really simple:
print ("\n".join(mylist))
The method str.join uses the string to join an iterable.
The standard list type has a number of built-in behaviors, including a representation with brackets around the list and commas between (reprs of) the items. There's no way to get the behavior you desire, from the statement you specify (print(mylist)), and use the standard list type.
You may define a class MyList whose __str__() method generates the desired format:
class MyList(list):
def __str__(self):
return "\n".join(self)
mylist = MyList(['AB', 'CD', 'EF'])
print(mylist)
Or you may redefine print():
def print(*args, print=print, **kwargs):
if type(args[0]) is list and len(args) == 1:
args = ["\n".join(args[0])]
print(*args, **kwargs)
Either way is just hiding the code away somewhere else in order to stick to some arbitrary rule about what you're allowed to write. If you're going to do that, in a class is probably the more acceptable spot to put it.
You can print each element separated too on a new line such as:
print(mylist[0]), print(mylist[1])
I found the solution.
'mylist' shouldn't be a list, it should be created as a string like this - then it prints as desired:
mylist = 'AB\nCD\nEF'
print(mylist)
This question already has answers here:
python: get the print output in an exec statement
(7 answers)
Closed 6 years ago.
I am writing a python script which contains a list containing python print statements as a string. In my function, I am using a for loop to run exec function to run those statements.
Here is my function:
g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
def run_statements():
for item in g_list:
exec(item)
When I run run_statements() function, I get the following output:
Wow!
Great!
Epic!
Basically, I want to save the output as a string so that later, I can save it to my database.
Does anyone have any idea how can I do it?
EDIT: At the following question: python: get the print output in an exec statement He is trying to get output, My question is different in a way that I am trying to get output as a string
If you really need a print statement in the list of strings (as opposed to a print-like function with a different name, as suggested in another answer), you can reassign the name print to your own function, after carefully, carefully, carefully saving the old print function so you can carefully, carefully, carefully restore the name print to its proper definition. Like this:
>>> g_list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
>>> old_print = print
>>> def print(s): # redefining the built-in print function! terrible idea
... global catstr
... catstr += s
...
>>> catstr = ""
>>> for s in g_list: exec(s)
...
>>> catstr
'Wow!Great!Epic!'
>>> print = old_print # Don't forget this step!
This is completely immoral, and I did not advise you to do it. I only said you can do it.
To stress the inadvisability of this plan: exec should be used rarely; it is dangerous; reassigning the names of built-in functions to different functions should be done very rarely; it is dangerous. Doing both in the same code could really ruin your day, especially after a maintenance programmer edits your code "just a little," without realizing the potential impact.
If you want to save what you print, you could create a custom command, and save the output to a variable. For example
output_bin = ""
def printsave(string):
print string
if len(string) > 1:
if string[-2] == "\n":
output_bin = output_bin + string
else:
output_bin = output_bin + string + "\n"
else:
output_bin = output_bin + string + "\n
Then, whenever you call printsave() it is saved to the string output_bin. And if you want it to be saved to an array...
output_bin = []
def printsave(string):
print string
if len(string) > 1:
if string[-2] == "\n":
output_bin.append(string)
else:
output_bin.append(string + "\n")
else:
output_bin.append(string + "\n)
I am kinda new to Python, and I would like to ask a question :
def spam(a):
a = 1 + a
return a
spam(21)
print(spam)
input()
After running it, the output is function spam at 0x021B24F8. Shouldn't the output be 22? Any help will be appreciated.
The problem is that your function, i.e. spam is returning a value. You need to accept the value returned by the function and store it in a different variable as in
s = spam(21)
print(s)
Here, you will store the returning value in the variable s which you will print it out.
After making the correction, the program will print as expected as in
22
Note - As mentioned, having a single statement print(spam(21)) also works as spam(21) will return 22 to the print function which will then print out the value for you!
I was in my computer science class today and the teacher put a piece of python coding on the board and said he couldn't figure out why it wasn't working. He was showing us functions and said:
def app(x):
x.append(" ")
print(x)
def ext(x,y):
x.extend(y)
print(y)
nums = [1,2,3,4,5,6]
numbers = [7,8,9,10]
app(nums)
ext(nums,numbers)
print("End of program")
The code was meant to show how when you don't type
return x
in the function then the variable doesn't change when you return to the main program however when he ran the program, the first function added the space and kept it there when it returned resulting in the following text being printed...
['1','2','3','4','5','6',' ']
['1','2','3','4','5','6',' ','7','8','9','10']
End of program
Please help me out.
You say that the point was to demonstrate that a list won't be changed unless it is returned. That is false. The list is a mutable object. When you pass it (by name) to a function and change it, it will be changed. If you don't want the change, you need to work with a copy.
def app(x):
return x + [" "]
def ext(x,y):
return x + y
might be what you are trying to do ... im not sure, this will not alter either of the original lists, but will return a new list as the result