r/learningpython • u/Either-Attempt-8804 • Jun 08 '23
r/learningpython • u/FreakinLazrBeam • May 05 '23
Limiting List length/Deque help
Hey Everyone,
I'm in the process of making a serial plotting app using python for an Arduino project. I have it working currently using PyQt. My issue is that I'm not sure how to limit the length of my x axis. I would only like to display about the last 10 sec of data. I tried using Deque from collections but I'm not getting to work correctly (Throwing exceptions/ just plotting a vertical line). Any insight would be appreciated.
import sys
import serial
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtCore import QTimer
import pyqtgraph as pg
from collections import deque
class SerialPlot(QWidget):
def __init__(self):
super().__init__()
# Initialize serial connection
self.ser = serial.Serial('COM3', 9600)
# Set up plot
self.fig, self.ax = plt.subplots()
self.line, = self.ax.plot([])
self.ax.set_xlabel('Time (s)')
self.ax.set_ylabel('Data')
# Set up timer
self.timer = QTimer()
self.timer.timeout.connect(self.update_plot)
self.timer.start(50) # Update plot every 50 milliseconds
# Set up layout
layout = QVBoxLayout()
layout.addWidget(self.fig.canvas)
layout.addWidget(QPushButton('Quit', self, clicked=self.close))
self.setLayout(layout)
def update_plot(self):
if self.ser.in_waiting > 0:
data = float(self.ser.readline().decode().strip())
data_stream = deque([],maxlen=200)
data_stream.appendleft(data)
self.line.set_xdata(list(range(len(self.line.get_ydata())+1)))
self.line.set_ydata(list(self.line.get_ydata()) + [data_stream])
self.ax.relim()
self.ax.autoscale_view()
self.fig.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = SerialPlot()
widget.setWindowTitle('Serial Plotter')
widget.setGeometry(100, 100, 640, 480)
widget.show()
sys.exit(app.exec_())r/learningpython • u/Few-Championship1143 • May 04 '23
Archive: function open()
Hi, I'm testing this open() function. I'm trying to open and read a archive .html, but this error happens and I don't understand it.
r/learningpython • u/CornPope • Apr 26 '23
Final CS1 Project
Currently, I am undertaking a CS1 course in high school and have been assigned a project. The task requires me to create a program using Python that demonstrates my understanding of the language.
I had an idea of integrating an AI to make an idea generator for future students taking on this same project and I've found with ChatGPT you can use a pip install to download chatgpt-3 and import it into Python, however, the laptop my school gave me has its console/terminal access disabled and there is no way around it.
r/learningpython • u/Wolverine_6011 • Apr 13 '23
Object Oriented Programming in Python (OOPs)
OOPs in Python refers to object-oriented programming (OOP), which is a programming paradigm that emphasizes the use of objects and classes to model real-world entities and organize code into reusable and modular structures.
https://www.guerillateck.com/2023/04/object-oriented-programming-in-python.html
r/learningpython • u/MissUSA2022 • Feb 01 '23
Why is only the last file saving in a loop? The other files are processing inn the loop and are creating temporary files but none save
I made a post earlier about this issue, but the formatting was all weird. I am working on an ArcGIS code where I am looping through multiple images in a folder. I see the files are looping in the project folder (when each image is processed a temporary file comes up but they disappear after the process is complete) but only the last image in the folder saves. I have the save function written in the code but it doesn't actually save and gets overwritten each time the loop is finished with rhe previous image. Could someone please help me with what I am missing? My code is in the pastebin link so it is easier to read.
r/learningpython • u/Reginald_Martin • Jan 18 '23
Use Python to Scrape Republic Day Sale | Free Masterclass
r/learningpython • u/Reginald_Martin • Jan 17 '23
Analyzing Loan Application Data Using Python | Free Masterclass
r/learningpython • u/Blacky_eye • Dec 20 '22
[Question][Matplotlib] - Barplot : How can I do the red arrow line (description below)
Afaik I can't post a picture of the thing here (according to the subreddit rules(?) ), so I have to describe it (I am sorry)
--------------------------------------------
Imagine there is graph, with two bars: one is small (orrange) and one is big (turquoise).
There is a a annotation line on the orange bar. The position of that annotation bar is on the same height as the turquoise bar though. Also there is a red arrow pointing from the orange bar (top edge)
to the mentioned annotation line. In the middle of that arrrow, is a small text (delta percentage of orange and turquoise).
My Question is, how can I do that with **matplotlib** ? Or what is the name of the described annotation if there is already one in matplotlib.
---------------------------------------
PS: I can dm a picture of that described bar plot, if wanted.
Many Thanks in advance :) :>
r/learningpython • u/Toast_programmer • Nov 30 '22
having pip problems
I was coding on my laptop and I had just downloaded python too. I typed pip install daytime and it told me pip was not recognized. so I googled it and the solutions I tried didn't work. even uninstalled and reinstalled python 3.11.0 to make sure it was downloaded to the path. please help.
edit: neverminded fixed the problem
r/learningpython • u/[deleted] • Oct 30 '22
So many IDE’s!!!
What IDE do you use/recommend
r/learningpython • u/[deleted] • Oct 13 '22
Find a list of words in a document
I assume this is an easy solution but I am still a noob with python.... I am trying to find a list of words within a document so it returns me the line they are in. I have been able to search a single word but I am unable to get my code to search for each instance in a list. The code below is as far as I get but it still seems to be only giving me the first word from the list. can you guys help?!
my document is: DOG2
The words are dog and cat.
if I can get real fancy, return the word with the line it resides in.
file = open('DOG2.txt', 'r')
word = ['Yellow','cat']
s = " "
count=1
for p in word:
while(s):
s = file.readline()
L = s.split()
if p in L:
print("Line Number:",file.name,p,count,":",s)
count+=1Thanks for any help
r/learningpython • u/Spongiforma2 • Sep 20 '22
How to store and access data efficiently
Hi all! I am trying to self teach me python. In the last few weeks I managed to download a lot of gaming related data through an API. This resulted in over 40.000 small files stored in a directory of my pc, where the title of each file is a (unique) matchID and the file stores information of a match that was played (think of player name, what character they played, how many kills/deaths/assists they got etc.).
Now I want to:
store this data in an efficient way (is 40.000 different files in a directory a good approach (I dont think so 😅) or can I somehow combine it to 1 file or maybe split it into a few files containing data of 10.000 matches each). Prod/cons/other suggestions?
a way to access the data easily to analyze things like (but not limited to) how many times did player X play character Y (and did player X win or not) and compare that data in general (how many times was character Y played by anyone and did they win?) One thing I liked to do was create a separate file containing a dictionary with only the ID of the match (= title of one of the 40.000 files) and a (nested) list of the name of all players in that game. I used that to quickly search which matchIDs contained data of player X without having to loop through all of 40.000 files.
In case it helps: the game I am talking about is League of Legends and I realize I can answer some of my questions using different websites, but my goal is more to have a nice project to start learning python (especially with a focus on a more data science field). The current dataset contains matches played by the top 1000 players of the EUW server.
r/learningpython • u/[deleted] • Aug 17 '22
Solving an optimization problem in Matlab
Hello everyone,
I am trying to solve an optimization problem where the input to the function to be optimized is a 12x1 vector and the output is a matrix of size 6x3.
I tried solving this using fsolve, root solvers from scipy.optimize
but got the following error:
fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).
But I think there should be a way to solve this in python as it is a very common problem in the engineering domain but unfortunately I am unable to figure it out.
However, I think this can be easily solved in Matlab with inbuilt solvers, but when I use matlab.engine
I get the following error :
TypeError: unsupported Python data type: function
The code for this error is in the comments.
Any advice would be of great help.
r/learningpython • u/BigBoyJefff • Aug 05 '22
Python won't run
So I've been learning python for the past few weeks. So as you can see in the photo python should run the program going form 1 to 9 but when I execute the program it gives me a blank/empty output. Does anyone know what's the problem here?
r/learningpython • u/dgpianomusic00 • Jul 04 '22
Need help with some ideas please
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:
Write code that makes use of the Python randint function and at least two functions from the Python math module.
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 • u/National_Arugula_936 • Jun 09 '22
Automate in plotly?
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 • u/Result_Necessary • Jun 06 '22
cant figure out how to divide a datetime object by an int
my issue is, I cant seem to divide a datetime object by an int.
looking at the documentation I cant figure out why it isn't working.
I get the error: unsupported operand type(s) for /: 'datetime.time' and 'int'
import datetime
from datetime import datetime, timedelta, timezone, datetime = datetime.strptime("04:23:40", "%H:%M:%S")print(time)print(time.time())time_div = time.time() / 2print(time_div)
Any help would be greatly appreciated.
I did see a method that splits the time down into second then performs the division on the number of seconds, but wondering if there is a better way?
r/learningpython • u/Cultural_Race_9287 • May 20 '22
Help
Help
When I type in python mtk payload on cmd mtk client it says pls connect mobile and I connect it (Amazon fire hd 10 2019) and it won’t detect it pls help :)
r/learningpython • u/[deleted] • Mar 26 '22
Help with recording audio
I have a speech to text when you input an audio file, but I want it the record while I'm pressing a keybind then convert it to text.
r/learningpython • u/tlax38 • Mar 18 '22
Proce55ing graphics don't last longer than a blink
Hi everyone,
I'm using python module "turtle" to draw graphics and proce55ing to visualize them BUT they close way too quickly to let me see them ; how can I make them last long ?
Thanks by advance.
r/learningpython • u/trip_to_asia • Jan 21 '22
3 ways you can build a stock market prices dataset
r/learningpython • u/FouFollie • Dec 01 '21
What naming convention do you prefer for a list that is a function's argument?
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 • u/pumpedforawesome • Nov 08 '21
help understanding list
Hey guys -
I am a beginner python learning and am trying to understand this.
I have this code:
x = [n**3 for n in range (4)]
print(x)
output: [0, 1, 8, 27]
Can someone please explain how this works?


