Any ideas for why two side by side print statements in python would not execute? - python-2.7

I have a class defined as this:
class decider(object):
def __init__(self, brain):
self.brain = brain
##stuff
## brain is an object
In a class function I have two print statements, right next to each other, like so:
def somefunction(self, someParam):
print "Something First"
print "Another something: " + self.brain.aVariable + ", " + self.brain.anotherVariable
# more stuff
# execution continues as normal
# the object called in brain exists (ive checked)
In another function (in the same class) I call this function.The first print statement is printing, the second one is not. No exceptions are raised and the code just skips that line. No crashes either. I find this pretty bizarre and had not happened to me until now. Is there a reason for why this could possibly be happening?
If it matters, I'm running python 2.7 on an embedded system with an ATOM Z530 processor.

Could be buffered? Does anything print after the second call?
Add another print after the second call to force to clear the buffer

Related

How to fix a loop with boolean variable

I'm doing a project for a class, and I opted to make a text based game in python. I'm trying to set it up so that the question will loop until the player confirms their choice, and I'm having problems with the while loop in this section.
def pc_cls_sc(x):
# code does some stuff
print "You are sure about" + str(x)
exVar = raw_input("Right?")
if exVar == "y":
print "Alright!"
conf_Class = True
else:
print "Ok then."
conf_Class = False
while conf_Class is False:
pc_Class = raw_input(#asks some question)
pc_cls_sc(pc_Class)
The rest of this code functions properly, but the loop continues after the conf_Class variable is supposed to be set to true. I have a similar loop earlier in my code, which works just fine. I've tried moving the variable reassignment outside of the pc_cls_sc function, but all it did was cause double output. Can anyone tell me how to fix this?
You can use break to exit the loop. The code below will keep asking a user for input until they say 'y'.
while True:
x=input("Right? " )
if (x=='y'):
break

in_round() function in oTree

Consider a game with 3 rounds. In every round the player makes a choice (stored in the variable choice).
Now, in the 3rd round I want to call someFunction and thereby access the choice made in the 2nd round.
Unfortunately someFunction returns None. I do not understand why. If I place the function call in a template file, everything works out fine.
Help would be appriciated - I ve been searching for hours.
class Subsession(BaseSubsession):
def before_session_starts(self):
if self.round_number == 3:
for player in self.get_players():
player.participant.vars['someKey'] = player.someFunction()
class Player(BasePlayer):
choice = models.CharField(initial=None,
choices=['A','B','C'],
widget=widgets.RadioSelect())
def someFunction(self):
return self.in_round(2).choice
Why is this happening?
the before_session_starts function is executed before the session starts (hence its name). Thus, when it is executed the player has not done his/her choice yet. That is why someFunction returns None.
You can set player.participant.vars['someKey'] = self.player.choice in the end of 2nd round, which will give you result you are looking for.
class Choice(Page):
def before_next_page(self):
if self.player.round_number == 2:
player.participant.vars['someKey'] = self.player.choice

Python 2.7: How to make a function print an undetermined amount of strings from a tuple

I'm making a text-based adventure game, and would like to have a universal 'look' function that uses an algorithm to tell the player how many and what objects are in a room instead of me having to write individual descriptions for each room. So it would work roughly like this:
lookround(things.bedroom)
You see:
a bed, which is the last on the right, across from Jacob's and to the left of Steve's,
and
a calendar, which is on a nail driven into the wall to the left of your bed
The objects are stored in the class 'things', which has a format that organises them with the object name first, and then the description of its location, then it repeats. That way, all the function has to do is print the first two tuples, then the next two, then the next two, and so on.
So, how would I get it to print out a number of tuples which have not been spoon fed to it?
Right now, I'm trying to use this:
def lookround(room):
print '''You see:'''
for len(room) % 2:
print ('{}, which is {},'.format(room))
The problems I'm having are that I'm getting a syntax error which points to the colon after len, and I'm not sure what I should put in .format() .
I've tried messing around with the syntax, but nothing's working.
class room(object):
things = ('a bed', 'to sleep in',
'a calendar', 'to look up the date',
'a clock', 'to wake up')
def lookround(room):
print '''You see:'''
for i in range(len(room.things)):
if not (i%2):
print ('{}, which is {},'.format(room.things[i], room.things[i+1]))
if i != len(room.things) - 2:
print 'and'
This should work with your current format. It might be a better idea to store things as a tuple of tuples, so you don't deal with the modulus business...

Python how to batch printing x lines at a time in a for loop

I tried all sorts of for loops but just can't seem to figure out how to print "n" number of lines from a dictionary at a time. I am new to programming so please pardon my terminology and expressions...
Example source:
{'majorkey1': [{'name':'j','age':'3','height':'6feet'},
{'name':'r','age':'4','height':'5feet'},
{'name':'o','age':'5','height':'3feet'}],
'majorkey2':[{'name':'n','age':'6','height':'4feet'},
{'name':'s','age':'7','height':'7feet'},
{'name':'q','age':'7','height':'8feet'}]}
This prints everything at once (undesired):
for majorkey in readerObj.keys():
for idx, line in enumerate(readerObj.get(majorkey)):
print line
{'name':'j','age':'3','height':'6feet'}
{'name':'r','age':'4','height':'5feet'}
{'name':'o','age':'5','height':'3feet'}
{'name':'n','age':'6','height':'4feet'}
{'name':'s','age':'7','height':'7feet'}
{'name':'q','age':'7','height':'8feet'}
I have gutted a lot of code to make this easier to read. The behaviour I would like is to print according to the number of lines specified. For now I will just use lines_to_execute=2. I would like to keep code as close as possible to minimize me rewriting this block. From this answer once working I will modify code so that it performs something chunks at a time.
Code block I want to stay close to:
Ill mix psudo code here as well
for majorkey in readerObj.keys():
lines_to_execute = 2
start_idx_position = 0
range_to_execute = lines_to_execute
for idx[start_idx_position:range_to_execute], line in enumerate(readerObj.get(majorkey)):
print line
increment start_idx_position by lines_to_execute
increment range_to_execute by lines_to_execute
time.sleep(1)
For this example if I want to print two lines or rows at a time, output would look like the below. Order is not important as same 2 don't get executed more than once:
Desired output:
{'name':'j','age':'3','height':'6feet'}
{'name':'r','age':'4','height':'5feet'}
One second delay...
{'name':'o','age':'5','height':'3feet'}
{'name':'n','age':'6','height':'4feet'}
One second delay.
{'name':'s','age':'7','height':'7feet'}
{'name':'q','age':'7','height':'8feet'}
I hope this is enough information to go on.
from pprint import pprint
import time
for key in obj.keys():
lines_to_execute = 2
pprint(obj[key][:lines_to_execute]) # that's all you need
time.sleep(1)
Keep it as simple as possible.

Can you translate this debugging macro from C++ to python?

I use this very helpful macro when developing in C++:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
Could you help me implement the same idea in python? I don't know how the #a could be implemented with a python function...
As #Andrea Spadaccini and #adirau point out, it is not possible to reliably map values back to Python variable names. You could trawl through all namespaces looking for some variable name that references the given value, but that would be fighting the system and liable to return the wrong variable name.
Much easier it is to just pass the variable name:
import inspect
def pv(name):
frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
inspect.currentframe())[1]
# print(frame,filename,line_number,function_name,lines,index)
val=eval(name,frame.f_globals,frame.f_locals)
print('{0}: {1}'.format(name, val))
a=5
pv('a')
yields:
a: 5
You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable.
import inspect
import re
def dd(value):
calling_frame_record = inspect.stack()[1]
frame = inspect.getframeinfo(calling_frame_record[0])
m = re.search( "dd\((.+)\)", frame.code_context[0])
if m:
print "{0} = {1}".format(m.group(1), value)
def test():
a = 4
dd(a)
test()
Output
a = 4
I think that this cannot be done.
The debugging macro that you posted works because it is expanded before compilation, during pre-processing, when you know the variable name. It is like you write all those couts by yourself.
Python does not have a pre-processor (AFAIK), there are external tools that do a similar thing (pyp and others), but you can not define a macro with the standard language.
So you should do your trick at run-time. Well, at run-time you don't know the "name" of the variable because the variable is just a reference to an object, when you call a method you call it on the object, not on the "variable". There can be many variables that point to that object, how does the object know which variable was used to call the method?
You can't get a variable (well, object)'s name in python. But you can pass the object's name to get its value (kinda the opposite of what you do with that macro)
>>> a=4
>>> locals()['a']
4
EDIT: a detailed explanation may be found here
import sys
def DD(expr):
frame = sys._getframe(1)
print '%s = %s' % (expr, repr(eval(expr, frame.f_globals, frame.f_locals)))
GLOBAL_VAR = 10
def test():
local_var = 20
DD('GLOBAL_VAR + local_var')
>>> test()
GLOBAL_VAR + local_var = 30
The Rod solution is perfectly usable.
It could be even extended to handle many vars.
But you can get close to that with much less magic:
def dd(**kwargs):
print ", ".join(str(k) + "=" + str(v) for k, v in kwargs.iteritems())
a = 1
dd(a=a,b=3)
output:
a=1, b=3