Class instance error whilst printing - python

Here is essentially what I am trying to do:
Class MyClass():
def __init__(self):
self.name="Bob"
person=MyClass()
print " hello {1} how are you?".format(1=person.name)
This gives an error saying keyword cant be an expression
I know there are many ways around this for example:
print "hello " + person.name
But for longer sentences I prefer the first format as it is easier to understand, if anyone knows how to fix it, or even just explain to me why it is wrong that would be greatly appreciated.

print " hello {} how are you?".format(person.name)
if you want to use position, it begin at 0
print " hello {0} how are you?".format(person.name)
0 means the first element inside format function
print " {0},{1},{0}".format('a', 'b')
a,b,a

Related

How can I tell my function to do something specific thing when it receives no parameters?

So, I have the following function which should resemble the already implemented " print " function in Python. ( I know it is silly to make a function that only uses a pre-defined function but I am practicing with different things ) The thing that I want to do with my function is: make it act the same as the pre-defined one. That is, when the print function is called with no parameters, I would like it to print an empty line just as " print() " does. How do i do that ?
def print_str( string, how_many_times, tail ):
print ( string * how_many_times, end = tail )
print doesn't take a single string, it takes 0 or most strings as argument. end has a reasonable default. You can imagine a (simplified) definition of
def print(*args, end='\n'):
...
You need to do the same for yours. A reasonable default for how_many_times would be 1. If you don't want print_str to take multiple arguments, "" would be a reasonable default for string.
def print_str(string="", how_many_times=1, tail='\n'):
print(string * how_many_times, end=tail)
You can do something like this:
def myfunc(a=None):
if a == None:
print()
else:
print("hi")
If no arguments are presented it prints nothing, but if an argument is given it prints 'hi'.

Is it possible to call a function that needs a parameter, without it? On python

I'm learning to code on Python 3.x using Exercism. I have to code a conditional (on a secondary file) to return a string depending on a word sent from a main function:
User function:
def two_fer(name):
if name:
string = "One for " + name + ", one for me."
else:
string = "One for you, one for me."
return string
Main function:
class TwoFerTest(unittest.TestCase):
def test_no_name_given(self):
self.assertEqual(two_fer(), 'One for you, one for me.')
def test_a_name_given(self):
self.assertEqual(two_fer("Alice"), "One for Alice, one for me.")
def test_another_name_given(self):
self.assertEqual(two_fer("Bob"), "One for Bob, one for me.")
The problem is that, for the first condition in the main function, it calls two_fer() with no conditional, which results on a fail.
Main function is supposed to not be modified, is it any way to solve the problem only by the user function?
Thanks in advance.
You can change:
def two_fer(name):
to:
def two_fer(name=None):
which will make name None by default
If you give name a default value of "you", you can call the function without an explicit argument and get rid of the if statement altogether.
def two_fer(name="you"):
return "One for " + name + ", one for me"
or better yet,
def two_fer(name="you"):
return "One for {}, one for me".format(name)
You can use a default parameter i.e None and check whether the function received any parameter or not.
User Function:
def two_fer(name = None):
if name != None:
string = "One for " + name + ", one for me."
else:
string = "One for you, one for me."
return string
The above code will execute the else part if the method two_fer is called without any parameters.
Use a default parameter like following
def two_fer(name=None):
if name:
s = "One for " + name + ", one for me."
else:
s = "One for you, one for me."
return s
Also a tip, avoid assigning variable names as keywords for e.g. string in your case as it is a standard library and it is just a good practice to avoid it.

How to get execution of python print statements as a string? [duplicate]

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)

Why is `print(object)` displaying `<__main__. object at 0x02C08790>`?

I keep getting
<__main__.Camera object at 0x02C08790>
and I don't know why.
I would like the code to go from Calc_Speed to Counter and then back to Calc_Speed basically in a loop.
class Camera():
distance = 2
speed_limit = 20
number_of_cars = 0
def Calc_Speed(self):
registration = input("Registration Plate: ")
Speeding_List=[]
start = float(input("Start time: "))
end = float(input("End Time: "))
speed = self.distance/(end-start)
print(("Average Speed: ") + str(round(speed, 2)) + (" mph"))
if speed > self.speed_limit:
list3= [str(self.registration)]
Speeding_List.append(list3)
print("Vehicles Caught Speeding: " + str(Speeding_List))
return(program.Counter())
else:
print("Vehicle Not Speeding")
return(program.Counter())
def Counter():
self.number_of_cars = self.number_of_cars + 1
print("Number Of Cars Recorded: " + str(self.number_of_cars))
return(program.Calc_Speed())
program = Camera()
print(program)
When you just print an object, it shows the object id (like <__main__.Camera object at 0x02C08790>), which is totally indecipherable to us mortals. You can get around this by defining a __str__ or __repr__ function to display the data for the instance in a custom way.
In your case:
def __repr__(self):
return "<__main__.Camera: distance = " + str(self.distance) + "; speed_limit = " + str(self.speed_limit) + "; number_of_cars = " + str(self.number_of_cars) + ">"
If there were an instance of Camera with the starting variable values, it would return
"<__main__.Camera: distance = 2; speed_limit = 20; number_of_cars = 0>".
The <__main__.Camera object at 0x02C08790> is the how the system remembers it, but aside from showing what type of object it is, it's mostly useless.
Rather than printing the object itself, you would want to print a function of that object. If you replaced the last line with:
print(program.Calc_Speed())
The program would work more similarly to what you seem to be looking for.
I wrote this answer for a linked closed duplicate. Since it goes into more detail about why the output looks like this, and this is apparently the canonical question, I'm putting it here.
Because you are printing an object, and that object doesn't have a __repr__ or __str__ method explaining how to print it.
Implementing these methods will let you print a 'description' of your object.
Background
When you call print(thing) in python, print looks to see if thing has a __str__ method, and calls it if it does. If it doesn't, it looks to see whether thing has a __repr__ method, and calls that if it does. If not, it keeps looking up the class hierarchy,* until it ends up with object, from which all user defined classes inherit (nowadays...). That's the method you're seeing here.
We can try this out:
>>> "I am a string".__str__()
"I am a string"
>>> "I am a string".__repr__()
"'I am a string'"
Yes! strings are objects in python. In fact, everything is an object.
>>> obj = object() # base class for all classes
obj.__str__()
'<object object at 0x7a87787987979877>'
So it's the fallback .__str__, which just prints that it's a thing at such and such a ram address.
*alright, it'll apply MRO, but I was keeping it simple.
I found with Dash:
print(InputData.marker_value)
>>> <dash._callback.NoUpdate object at 0x7f52b29fdfa0>
print(InputData().marker_value)
>>> "value expected"
I agree with Sandford Basset
You can try as well
program.Calc_Speed()

Print formatting a string and function call in python

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?

Categories

Resources