r/learningpython • • Aug 06 '22

Custom ContextManager

1 Upvotes

Hi all,

I found an exercise asking to write a class behaving as a custom ContextManager (and use it with the "with" statement).

I do not know from where to start.

I only know that I've to write some methods:

def __init__(self, *args, **kwargs):
pass

def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass

where I can find some good tutorial?

the example said ssomething like:

value = 0

with MyContextManager(argument):

value = function(a, b, c)

assert value.x == 12

assert value.name = "myname"


r/learningpython • • Jul 28 '22

Learning Python as a second language.

1 Upvotes

Learning Python as a second language.

Currently I am learning Python as a second programming language and I am having some difficulties.

I understand syntax, setting up functions, etc.

The problem I am having is that my primary language I have been developing automation instrumentation and control applications in is LabVIEW.

What is tripping me up in learning Python are some of the concepts that are native to LabVIEW parallel execution, queues, actors, asynchronous processes, etc.

I know it can be done in Python but after doing all my programming visually for the last 10+ years I am having trouble visualizing doing the same thing in a text based programming paradigm.

LabVIEW does a lot of the heavy lifting. Y setting up variables working with me or, etc. I realize that must be done “by hand” I’m Python and I am getting adept at that.

It is the multi process setup and execution that is throwing me for a loop (no pun intended).

Does anyone have any resources, suggestions, etc. on how I can retrain my brain to think in this manner with Python.

Everything I do in LabVIEW is object oriented so that I have no problem with.

TIA

-Steven


r/learningpython • • Jul 04 '22

Need help with some ideas please

1 Upvotes

Hello friends,

I am in my first semester of computer programming and am taking an intro course to Python. I am also a first time poster and am struggling to come up with some ideas for a program that I'm working on. The prompt is as follow:

  1. Write code that makes use of the Python  randint function and at least two functions from the Python  math module.

  2. Additionally, write at least one (user-defined) function definition and associated function call that makes use of Python's ability to return multiple values from a function.

I've come up with several other ideas but can't make use of the randint function along with what I've come up. Any help is appreciated.


r/learningpython • • Jun 09 '22

Automate in plotly?

1 Upvotes

Hi! I am relatively new to python, and I am trying to create a series of graphs (12) per institution (300) using a jupyter notebook and plotly. I created one set of graphs for one institution, and I am wondering if there is a possibility of writing a line of code that could automatically create the series of graphs for each institution, without me having to manually change the name of the institution each time.


r/learningpython • • Jun 08 '22

How to delete those peskey rows in a csv

1 Upvotes

how do i delete a row in csv? like for row in reader: if row == '\n': delete it

all solutions i see is make a ne file and selectevely copy the data over which seems a little redundent, any better methods? tya!


r/learningpython • • Apr 01 '22

Valueerror I can't solve

1 Upvotes

Hi everyone,

I'm trying to code a Greatest Common Divisor program but I'm meeting an error I don't understand.

PGDC is GCD in french.

Thanks by advance for your help.


r/learningpython • • Feb 28 '22

Random Non-Randomness?

1 Upvotes

I have a simulation app that I’ve written that measures performance of different agent classes.

One of the two classes I’ve written this far has no randomness in it. But the “score” is different each time it runs. I’ve attributed this to the fact that it uses a set at a few places, which when converted to a list may yield a different ordering than when the items went in. That’s not my problem.

My problem is this: my simulation script runs multiple iterations of the agents, so as to plot the variance in scores. The harness uses process-level parallelism to run agents in parallel. If I run the “simple” (non-random) agent 10 iterations, I will get the exact same score 10 times. But if I run the harness 10 times for 1 iteration each time, I’ll get 10 different scores. So there is something that is at least semi-random going on. Again, I suspect the sets thing. When the runs are all forked from the same parent, I get the same value.

Anyone know what could be causing this, and how to fix it?

Randy

Edit: I have found the cause. When I initialize the game engine with the list of words, I store it in a set. Each player agent gets the list of valid words from the game instance. So, at the start of the simulation the list is "slightly randomized" by being stored as a set. But everywhere else, it's either treated as a list or implicitly converted to a list for operations. Hence, each fresh run of the harness has a slightly different word-order, while each run of an agent within the harness uses that same word-order over and over. At least now I know why this is happening-- I had initially assumed that the "simple" agent would always produce the same score, and had been slightly surprised when it didn't.


r/learningpython • • Feb 20 '22

What's wrong here?

1 Upvotes

Hi! I'm new to Python and started learning it on my own with an app from Google Store. This error pops up when I click Run > Run Module. Any idea what I should do? Please explain as simply as possible :)

Edit: This shows up when I delete the 1st two lines:


r/learningpython • • Jan 20 '22

Problem when importing functions, all the code runs

1 Upvotes

Hi guys,

I was watching a lesson on how to import functions from a different file, and I replicated the logic on two files:

-moduliPackages.py : it's the file where I import and use functions,

-functions.py: is the file where I have defined the functions

In moduliPackages I am using the statement 'from functions import *', and after that I use print_time(), that is one of the functions imported.

The problem is that when I run moduliPackages it runs all the code that I have written in functions.py (so stuff like print statements ecc).

Any idea what I am doing wrong?

functions.py:

from datetime import datetime
print('Inizio lezione')
def print_time():
    print('task completed')
    print(datetime.now())

def print_task(task_name):
    print(task_name)
    print(datetime.now())

first_name= 'Joe' #input('Inserisci il tuo nome: ')
last_name= 'Jonetti' #input('Inserisci il tuo cognome: ')
first_initial= first_name[0:1]
last_initial= last_name[0:1]
print('the letters are: '+ first_initial + last_initial)

moduliPackages:

from functions import *
print_time()
print_task('test')

r/learningpython • • Jan 10 '22

Question about importing and translating CAN data

1 Upvotes

First and foremost I'm a newbie to programming in Python. My problem is as follows. I need to extract data from a battery using a Kvaser cable that converts the CAN messages into decimal code. When I have received the data I need to translate it into readable language.

In VBA I have already written a macro that can complete this process, but this is not in real time (this is a logging process). So the macro works like a dictionary. The process of the VBA looks like this. Using a Kvaser cable, the data is logged into a txt file. I import this txt file into the excel created. After this I run the macro and get useful info (SoC, SoH, Number of cycles, etc).

My question now is if anyone has an idea how this can be easily replicated in python and optionally in real time? What method would you guys use to tackle this problem? If I can narrow down to what specific field in Python I should be looking, it would help a lot. If additional info is required, just let me know.

Thanks in advance!


r/learningpython • • Dec 01 '21

What naming convention do you prefer for a list that is a function's argument?

1 Upvotes

You can just use `list` as a variable name. It works, but confusingly and dangerously. For example

def moving_window(n, list):
  return [list[i:i+n for i in range(0, len(list)-(n-1))]

works. But it seems like a terrible practice. Then there is no list() constructor so another seemingly equivalent list comprehension style simply TypeErrors

def moving_window(n, list):
  return list(list[i:i+n for i in range(0, len(list)-(n-1)))

unless we rename our list argument.

Maybe I'm just avoiding OOP too much and any generic utility function that is using a built-in type should be a method for a class.

TL;DR What variable naming do you use in a function that takes a list?


r/learningpython • • Nov 29 '21

code loading very slowly, how to optimize?

1 Upvotes

Hi there, I am trying to remove stopwords from my training data. The problem is that since the data is very big, the code is very slow. Is there any way to optimize it? Thank you in advance!

from nltk.corpus import stopwords
def stopwords_remove(data):
    stopwords_removed = []
    for parts in data:
        #print(parts[0])
        for word in parts[0]:
            #print(word)
            if word not in stopwords.words():
                #print(word)
                stopwords_removed.append(word)
    #print(stopwords_removed)
    return stopwords_removed
stopwords_remove(train_data)

r/learningpython • • Nov 16 '21

Printing Dictionary to .json file not working

1 Upvotes

So, I have a simple problem:

I am creating a simple database system for entirely personal use as a small project to better understand python and programming in general, I am storing objects as dictionaries containing their places, where they are stored within the place and the current status as a dictionary like so:

def StoreSomething():
Object = input("Object: ")
Place = input("Place: ")
Storage = input("Storage: ")
Status = input("Status: ")
n = 0
while Object in Stuff:
n = n + 1
Object = Object + str(n)
Stuff[Object] = {"Place": Place, "Storage": Storage, "Status": Status}
Menu()

This is then stored in the larger dictionary called "Stuff"(I am bad at variable naming).

I wish to save the Stuff dictionary in it's entirity to a JSON file for later use, I have tried almost every single permutation of:

def Save():
Data = Stuff
json.dump(Data, file, indent = 1)
Menu()

None have yet even been able to produce an empty file, no matter if I opened the file early on in the program or if I had opened it only for the saving function. In test runs this has worked however with:

import json

file = open("test.json", "w")
for i in range(0,500):
iDict = {i : i}
print(iDict)
json.dump(iDict, file, indent = 1)

However I cannot see the issue with my first iteration compared to my test program.

Any ideas?


r/learningpython • • Oct 10 '21

Organizing graph

1 Upvotes

Im attempting to show the results of a test in a graph and want it to display score, letter grade, and numeric grade. But I cant get numeric grade to line up correctly any recommendations?

def clalcAverage( score1, score2, score3, score4, score5):

average = (score1 +score2 +score3+ score4 + score5)

return average

def determine_grade(userScore):

if(userScore < 60):

return "F"

elif(userScore < 70):

return "D"

elif(userScore < 80):

return "C"

elif(userScore < 90):

return "B"

elif(userScore < 101):

return "A"

def askForScore():

score1= float( input("Enter Score 1: ") )

score2=float( input("Enter Score 2:") )

score3= float( input("Enter Score 3:") )

score4=float( input("Enter Score 4:") )

score5=float( input("Enter Score 5:") )

return score1, score2, score3, score4, score5

def printTableofResults(score1, score2, score3, score4, score5):

print("Score\tLetter Grade\tNumeric Grade")

print(str("Score 1:") + "\t" + determine_grade(score1) + "\t",

str(score1),

str("Score 2:") + "\t" + determine_grade(score2),

str("Score 3:") + "\t" + determine_grade(score3),

str("Score 4:") + "\t" + determine_grade(score4),

str("score 5:") + "\t" + determine_grade(score5),

sep = "\n")

def main():

score1, score2, score3, score4, score5= askForScore()

printTableofResults(score1, score2, score3, score4, score5)

main()


r/learningpython • • Aug 31 '21

Tree representation

1 Upvotes

I'm trying to make a picture like this to trace the historical development of a piece of software that has been modified many times over the years.

I didn't think it was going to be that hard, but... it is. After banging my head on Matplotlib for a while, I gave up. I found a few threads on Stack Overflow on how to plot trees using Networkx, but none of them seem to be focused on the dates, so nodes are "flattened" out depending only on their depth in the tree (and not on the actual date).

If anyone has advice on how to do something similar to the image attached, it would be great! Bonus points if it can do smooth splines like the ones in the image).

Thank you in advance.

(Source: https://en.wikipedia.org/wiki/List_of_Linux_distributions )


r/learningpython • • Jul 17 '21

Beginning Python in QuickStart bootcamp

1 Upvotes

Hello there. Is there any chance anyone here has taken the QuickStart data science course and would be able to hand hold me through small early projects? I am in the self paced course and am finding I need a bit more guidance than my instructor can provide now that we're into the Python sections and I just would really like to make it through this course! Thank you in advance.


r/learningpython • • Jun 28 '21

How to BeautifulSoup for <b title=""

1 Upvotes

How do I find <b title=""

The employee Sam S. is employee id 1234 that works at McDonalds.

I am not interested in all title's in the page, I am only interested in the div employee section

I would like to get the employee_number, store_number, and employee_name.

However, as it stands aa22 is empty, what am I doing wrong?

soup = BeautifulSoup(buffer, 'html.parser')

    # <div id="employee">
    # <h4><b title="1234">McDonalds #5678</b>Sam S.</h4>

    aa00 = soup.findAll("div", {"id": "employee"})
    for aa11 in aa00:
        aa22 = aa11.findAll("b", {"title" : lambda L: L and L.startswith('title')})
        for aa23 in aa22:
            str_ = aa23.text.replace('\n','')
            print(str_)

            employee_number =
            store_number =
            employee_name =

r/learningpython • • Jun 11 '21

How do I convert a bunch of leaf-nodes into a sub-graph and generate a DOT file for graphviz?

1 Upvotes

Libreoffice has a whole bunch of class-paths like so: com.sun.star.sheet. It's so huge that I'll be scrolling horizontally forever if I use the typical way of adding nodes to Graphviz and then doing dot.render(). (you can look at their classtree here https://pastebin.com/Z8kHEe0R)

I need to merge the leaf-nodes into a sub-graph and grow that vertically and Graphviz allows such things using rankdir=TB Which means that I need to locate all nodes with leaves >10 and sub-graph those leaves/node.

Can this be done using Graphviz (unlikely it seems more towards plotting DOT files) which means I tried using treelib but I can't find a method to subgraph on condition..

Any solution?? (currently I can generate a console tree using treelib.show() similar to command line tree but I need to grow the graph Top-->Down for printing on A4 and overall looking at)

Libreoffice Class Tree from treelib is here https://pastebin.com/Z8kHEe0R I need to present that clearly.

├── sheet
        │   ├── AddIn
        │   ├── Border
        │   ├── CellAnnotation
        │   ├── CellAnnotations
        │   ├── CellAnnotationsEnumeration
        │   ├── CellAreaLink
        │   ├── CellDeleteMode
        │   ├── CellFlags
        │   │   ├── ANNOTATION
        │   │   ├── FORMULA
        │   │   ├── OBJECTS
        │   │   └── STRING

r/learningpython • • May 30 '21

Python Exceptions | Youtube Keyword Planner series

Thumbnail
youtu.be
1 Upvotes

r/learningpython • • Apr 20 '21

What is doing something like xxxxx.upper or xxxxx.append called?

1 Upvotes

Noob here.

What is it called when you type your variable and add something like ".upper" - dot upper - to it to make it uppercase? To me, it kind of feels like you are "operating" on it, no?

And how is it different (or why is it different) than performing a function on something (which would be the parameter, technically, correct?)

Another example - and I'm not sure if this is a function or whatever the answer to my first question is:

"".join((rightlettersguessed))

this is coming from my Hangman that I wrote, copying from what I saw in another Hangman program. it's blank with a dot join, and then my variable.

I find it somewhat helpful to read other people's code, but I feel like I need to give this "operation" a name so I can process it in my head as to what the code is trying to do.


r/learningpython • • Mar 22 '21

Numpy array issue

1 Upvotes

I'm trying to define a function that takes as input a numpy array and 2 integers for the index, and it's supposed to add those two lists of the array.

But when I run it, it redefines the original array that I used as input, and that ruins the next time I want to run it, so how can I run it without redefining the original array?


r/learningpython • • Mar 20 '21

Question about numpy, matlib and .dot()

1 Upvotes

I am using eclipse to code and it is telling me i have errors with .dot being undefined. So i imported numpy as np and numpy.matlib. I still have an error with .dot() but also have an error with numpy.matlib. The error is Unresloved import and unused import for matlib and .dot says it is not defined. I am not very familiar with this and i am going off of a tutorial that does it the same way i have written. What am I missing?


r/learningpython • • Jan 17 '21

No module named 'request'

1 Upvotes

Hey guys I get the following Error Message.

No module named 'request'

My Code is the following

import panda as pd 

FCD_Data = pd.read_csv("D:\Python\Master\FCD_Export.xlsx")

print(FCD_Data.shape)

When I want to install 'requests' i get the following Output.

Requirement already satisfied: requests in c:\users\stabi\anaconda3\lib\site-packages (2.25.1)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\stabi\anaconda3\lib\site-packages (from requests) (2020.6.20)
Requirement already satisfied: idna<3,>=2.5 in c:\users\stabi\anaconda3\lib\site-packages (from requests) (2.10)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\stabi\anaconda3\lib\site-packages (from requests) (1.25.9)
Requirement already satisfied: chardet<5,>=3.0.2 in c:\users\stabi\anaconda3\lib\site-packages (from requests) (3.0.4)

So if I get this right already have the request installed?

What else can I do? Am I missing something?


r/learningpython • • Dec 09 '20

About lists, statement, instances and objects

1 Upvotes

first_lista = [ ]

first_lista.extend('123')

print(first_lista)

First I create a object, a empty list. In the second, I used the method .extend. Last, I used the variable first_lista as an assingmente to the statement print. It's that correct?

class Simple: 
	def s(self):
		count = 0 
		n = 1 
		while count  < 10 :
			print("Count is not 10")    
		count = n + 1 


s.self()

Here, I create a method inside the class which is called s.self. E o self refers to an instance of my class. It's this correct?

0 votes, Dec 12 '20
0 python3
0 python

r/learningpython • • Dec 08 '20

How do I get better at reading and UNDERSTANDING documentation?

1 Upvotes

I have tried in the past to read documentation when it comes to trying to figure something out. For example, Django; I would like to avoid resorting to tutorials as I would like to create a portfolio/blog website for myself. Additionally, I am still new to Python so I may be reaching to far since I don't have a full understanding of just Python. Anyway, how do I get better with understanding docs? Just keep reading them?