Placeholders in Python: placing multiple names in an array - python

I am a beginner in python and learning "Learn Python: The Complete Python Programming Course" using Udemy. I downloaded Python 3.8. All things were good until I reached placeholders:
for i in arr.
Print(sen%(ā€œiā€))
I just want to use the function of placeholders in python and complete the task by placing multiple names in an array. I cannot type any of this. May I know why?
I am stuck and can't move ahead in the learning of the course.

Try:
for i in arr:
print(sen%(i))
That is, replace arr. to arr:

It is a bit finicky and will throw an error if the statement isn't lined up correctly, if you hit return in the wrong spot, or put a space where there shouldn't be one.
As #Joshua Varghese suggested, first change arr. to arr:
Make sure there is no space in arr:print(sen%(i))
Put your curser just before print(sen%(i)), and hit return. (This will put your print statement on the next line with the correct spacing).
To have your program execute and iterate through the array of names, you need to have your curser on the next line, the line following print(sen%(i)), then hit return.
Note: using python 3.9.2 on Mac OS

Related

best way to execute a list of instructions (n=0 to n=20). stop, then return to line n

i'm not sure I was very clear the first time I posted this, so i'll try agian.
thanks for bearing with me.
I have a program for a procedure, the procedure incurs like a drying time overnight.
(i'ts for my machine shop but work with me here)
it's like this:
a1=input('enter 1 after cutting paper')
a2=input('enter 1 after gluing paper')
a3=input('enter 1 after drying all night')
a4=input('enter 1 after resuming the next day')
i would just write down: "stopped on line a3".
and I was planning on writing a "for loop" to "unpack the list".
it was recommended to me that I use a dictionary rather than list; however I don't really see the difference, especially since a list can be enumerated, while a dictionary cannot.
I was thinking I could use a for loop and somehow run each ith value of the list.
thoughts anyone?
edit:
okay sorry for not explaining it well:
maybe this will help:
"i'm looking for a way to store information in a list, where the information is executable."
then I want to run that list starting on line n.
so like a recipe, but can start at any line.
You can define a list of actions:
actions = [
'cutting paper',
'gluing paper',
'drying all night',
'resuming the next day',
]
And then iterate through them:
for action in actions:
answer = input('input 1 after ' + f'{action}')
... but I still don't know what your actual question is. What do you mean by "stop"? Are you saying that you can't leave the computer running overnight, and you need some way to resume your progress in the list when the computer starts again the next morning?
I created the instructions on a separate .txt file. Then was able to index each step in the Py code. This works. I can also pass Py code through from the .txt document by adding a special character for the Py script to search for, then run the lines

Sublime Text 3 : How to display the line numbers of the evaluated lines in REPL Python?

using Sublime-Text-3
When i evaluate some selected python code, in PEPL Python (with SublimeREPL), i get something like that:
*>>> print("thank you")
thank you*
(i already set, "show_transferred_text": true,)
Instead of send and see the whole code that evaluated, i would like to see the line numbers of this evaluated code. Have you any ideas about this ?
(for example to display sth like this: >>> evaluated lines (1:30))
Thanks!
Unfortunately this is not possible with the default install of SublimeREPL. Additionally, the project is no longer being maintained, so until someone steps forward to steward the project, this feature won't get added unless you add it yourself. It's all open-source and written in Python.

How to check if a number inside an IF statement has changed and only then execute a script?

I am creating a tool changer for a pen plotter that only makes a tool change every time the source file moves to read data from a new layer (inside inkscape). This script injects a certain piece of GCODE (code that a CNC-based machine needs to know what it should do) on each layer change.
I already have all the variables ready and only need to know how to see how long the layer number stays '1' until it changes to '2' so that the script knows when to inject the 'tool change gcode'.
After hours of searching through possible solutions, I haven't managed to get it working. I tried some while statements, but they all failed, I even made my software crash a few times. I've come so far as to now strip all layer data from it's characters with a 're.sub' and make the variable 'layer number' that contains the '1' or '2' or '3' (should be able to expand until like 9 or further).
try :
self.last_used_tool == None
except :
self.last_used_tool = None
print_("working on curve")
print_(curve)
if tool != self.last_used_tool :
layernumber = re.sub('[^0-9]','', layer.get(inkex.addNS('label','inkscape')))
g += ("Layer %s" % layernumber + "\n;(Change tool to %s)\n" % re.sub("\"'\(\)\\\\"," ",tool["name"]) ) + tool["tool change gcode"] + "\n"
This script works, but in this script 'self.last_used_tool' doesn't exist anywhere else so it's a dummy code I believe.
Right now the if statement outputs the tool change gcode each time it starts to work on a new path, causing multiple tool changes of the same tool in one layer. I need the tool change to only happen the first time it moves to a new layer.
I am looking for a way to make the if statement see if the layer number has gone up or down and change the tool accordingly only in that case. Later on I might not check for the layer number but for the tool number, however, for now, in the way that I'm working it was more clear for me to use the layer number since that number corresponds with the tool number anyway and intuitively it felt more clear to me to do it this way.
Thanks for your time and effort, I hope someone is able to help me find the solution. When the script is finished I will publish it online so that others can also make use of it. The script I'm working on is an old open source project that was abandoned and apparently lacks some functionality. I've already fixed most of the extension (including language) but the tool change has never worked.
It seems you are missing to set
self.last_used_tool = tool
at the end of your if-block. Without that, self.last_used_tool will always be None and never compare equal to tool.

Email parser work on individual data; breaks when used in loops list comprehensions, then breaks on original data as well... then works with map

There's some weird mysterious behavior here.
EDIT This has gotten really long and tangled, and I've edited it like 10 times. The TL/DR is that in the course of processing some text, I've managed to write a function that:
works on individual strings of a list
throws a variety of errors when I try to apply it to the whole list with a list comprehension
throws similar errors when I try to apply it to the whole list with a loop
after throwing those errors, stops working on the individual strings until I re-run the function definition and feed it some sample data, then it starts working again, and finally
turns out to work when I apply it to the whole list with map().
There's an ipython notebook saved as html which displays the whole mess here: http://paul-gowder.com/wtf.html ---I've put a link at the top to jump past some irrelevant stuff. I've also made a[nother] gist that just has the problem code and some sample data, but since this problem seems to throw around a bunch of state somehow, I can't guarantee it'll be reproducible from it: https://gist.github.com/paultopia/402891d05dd8c05995d2
End TL/DR, begin mess
I'm doing some toy text-mining on that old enron dataset, and I have the following set of functions to clean up the emails preparatory to turning them into a document term matrix, after loading nltk stopwords and such. The following uses the email library in python 2.7
def parseEmail(document):
# strip unnecessary headers, header text, etc.
theMessage = email.message_from_string(document)
tofield = theMessage['to']
fromfield = theMessage['from']
subjectfield = theMessage['subject']
bodyfield = theMessage.get_payload()
wholeMsgList = [tofield, fromfield, subjectfield, bodyfield]
# get rid of any fields that don't exist in the email
cleanMsgList = [x for x in wholeMsgList if x is not None]
# now return a string with all that stuff run together
return ' '.join(cleanMsgList)
def lettersOnly(document):
return re.sub("[^a-zA-Z]", " ", document)
def wordBag(document):
return lettersOnly(parseEmail(document)).lower().split()
def cleanDoc(document):
dasbag = wordBag(document)
# get rid of "enron" for obvious reasons, also the .com
bagB = [word for word in dasbag if not word in ['enron','com']]
unstemmed =[word for word in bagB if not word in stopwords.words("english")]
return [stemmer.stem(word) for word in unstemmed]
print enronEmails[0][1]
print cleanDoc(enronEmails[0][1])
First (T-minus half an hour) running this on an email represented as a unicode string produced the expected result: print cleanDoc(enronEmails[0][1]) yielded a list of stemmed words. To be clear, the underlying data enronEmails is a list of [label, message] lists, where label is an integer 0 or 1, and message is a unicode string. (In python 2.7.)
Then at t-10, I added a couple lines of code (since deleted and lost, unfortunately...but see below), with some list comprehensions in them to just extract the messages from the enronEmails, run my cleanup function on them, and then join them back into strings for convenient conversion into document term matrix via sklearn. But the function started throwing errors. So I put my debugging hat on...
First I tried rerunning the original definition and test cell. But when I re-ran that cell, my email parsing function suddenly started throwing an error in the message_from_string method:
AttributeError: 'list' object has no attribute 'message_from_string'
So that was bizarre. This was exactly the same function, called on exactly the same data: cleanDoc(enronEmails[0][1]). The function was working, on the same data, and I haven't changed it.
So checked to make extra-sure I didn't mutate the data. enronEmails[0][1] was still a string. Not a list. I have no idea why traceback was of the opinion that I was passing a list to cleanDoc(). I wasn't.
But the plot thickens
So then I went to a make a gist to create a wholly reproducible example for the purpose of posting this SO question. I started with the working part. The gist: https://gist.github.com/paultopia/c8c3e066c39336e5f3c2.
To make sure it was working, first I stuck it in a normal .py file and ran it from command line. It worked.
Then I stuck it in a cell at the bottom of my ipython notebook with all the other stuff in it. That worked too.
Then I tried the parseEmail function on enronEmails[0][1]. That worked again. Then I went all the way back up to the original cell that was throwing an error not five minutes ago and re-ran it (including the import from sklearn, and including the original definition of all functions). And it freaking worked.
BUT THEN
I then went back in and tried again with the list comprehensions and such. And this time, I kept track more carefully of what was going on. Adding the following cells:
1.
def atLeastThreeString(cleandoc):
return ' '.join([w for w in cleandoc if len(w)>2])
print atLeastThreeString(cleanDoc(enronEmails[0][1]))
THIS works, and produces the expected output: a string with words over 2 letters. But then:
2.
justEmails = [email[1] for email in enronEmails]
bigEmailsList = [atLeastThreeString(cleanDoc(email)) for email in justEmails]
and all of a sudden it starts throwing a whole new error, same place in the traceback:
AttributeError: 'unicode' object has no attribute 'message_from_string'
which is extra funny, because I was passing it unicode strings a minute ago and it was doing just fine. And, just to thicken the plot, then going back and rerunning cleanDoc(enronEmails[0][1]) throws the same error
This is driving me insane. How is it possible that creating a new list, and then attempting to run function A on that list, not only throws an error on the new list, but ALSO causes function A to throw an error on data that it was previously working on? I know I'm not mutating the original list...
I've posted the entire notebook in html form here, if anyone wants to see full code and traceback: http://paul-gowder.com/wtf.html The relevant parts start about 2/3 of the way down, at the cells numbered 24-5, where it works, and then the cell numbered 26, where it blows up.
help??
Another edit: I've added some more debugging efforts to the bottom of the above-linked html notebook. As you can see, I've traced the problem down to the act of looping, whether done implicitly in list comprehension form or explicitly. My function works on an individual item in the list of just e-mails, but then fails on every single item when I try to loop over that list, except when I use map() to do it. ???? Has the world gone insane?
I believe the problem is these staements:
justEmails = [email[1] for email in enronEmails]
bigEmailsList = [atLeastThreeString(cleanDoc(email)) for email in justEmails]
In python 2, the dummy variable email leaks out into the namespace, and so you are overwriting the name of the email module, and you are then trying to call a method from that module on a python string. I don't have ntlk in python 2, so I cant test it, but I think this must be it.

Python "for" inside "any" syntax error?

I have a piece of code that broke the other day and I can't find the problem. I need to do something if I find a coincidence between a user input and the first value of any element of a list of lists.
I had this code running in another computer, but somehow I can't make it run anymore:
if any(orderinput == x[0] for x in order):
orderinput is the user input and order is the list of lists. This worked once and should be working based on what I've read here on stackoverflow, but it throws a syntax error at the r in for.
I tried moving it between lines or adding spaces, but the error follows the r.
I'm working in Python 2.2. I don't remember the version in the machine I made the code.
Generator expressions are available since python 2.4. Try changing to a list comprehension:
if any([orderinput == x[0] for x in order]):
Python 2.2 is twelve years old. A lot of things were different.

Categories

Resources