/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about your python code.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

799,712 Subscribers

1

Textual/CSS Library: Scrolling

I'm attempting to create a Weather API program, which features an interface using the 'textual' library. Currently, I have code that accepts user input, and then proceeds to add widgets to the screen that displays what will soon be weather info for the input (the location)- this display includes the input string. If the API does not find any data on the location given by the user, the program adds a widget that displays "invalid input". While I was building this code up, the textual screen would add a scroll bar once there were too many widgets on the screen to be displayed all at once. However, once I added the if/else code that checks whether the response code is valid, this auto-scrolling no longer occurred. Does anyone have any ideas as to why the if/else would break the scrolling feature? Here is the main file of my code that deals with the interface building:

from textual import on
from textual.app import App, ComposeResult 
from textual.widgets import Input, Static
from textual.validation import ValidationResult, Validator 
from textual.containers import Vertical, Horizontal
from data import Location, Data import requests

class Bar(Static): 
    pass

class Validate(Validator):
    def validate(self, input_string: str) -> ValidationResult:
        """Check a string is equal to its reverse."""
        if self.has_numbers(input_string):
            return self.failure("Invalid input: No numbers are allowed! :/")
        else:
            return self.success()
    
    @staticmethod
    def has_numbers(input_string: str) -> bool:
        return any(char.isdigit() for char in input_string)

class WeatherApp(App):
    CSS_PATH = "app.tcss"
    
    def compose(self) -> ComposeResult:
        input = Input(value="",placeholder="Enter a location...",
                     validators=[Validate()],validate_on=["submitted"])
        yield input
    
    def action_report_forecast(self, input_string: str) -> None:
        location = Location(input_string)
        loc = location.get(input_string)
        data = Data(loc)
    
        url = data.getURL(loc)
        response = requests.get(url)
        # response = data.response
    
        if response.status_code == 200:
            bar0 = Bar("Current Forecast for " + input_string + ":", classes="general")
            bar1 = Bar("Time Info:", classes="time")
            bar2 = Bar(input_string, classes="general")
            bar3 = Bar("Wind Info:", classes="air")
            report = Vertical(bar0,Horizontal(bar1,bar2,bar3))
        else:
            invalid = "Invalid Input: Location '" + loc + "' not found!"
            report = Vertical(Bar(invalid, classes="error"))
    
        self.mount(report)
        self.call_after_refresh(self.screen.scroll_end, animate=False)
    
    
    @on(Input.Submitted)
    def show_invalid_reasons(self, event: Input.Submitted) -> None:
        if event.validation_result.is_valid:
            location = Location(str(event.input.value))
            loc = location.get(str(event.input.value))
            self.action_report_forecast(loc)
        else:
            self.action_report_forecast("Invalid Input!")

if __name__ == "__main__":
app = WeatherApp()
app.run()

0 Comments
2024/04/06
03:16 UTC

2

Project based learning?

Hi guys, Ive been dabbling in python for a while and recently I just jumped head first into a python / flask app w an api, it went somewhat well and I’m almost done. The only issue is that I feel like although I was able to build my app “from scratch” with no tutorials, I’m noy really learning because I keep having to refer to the internet every 5 minutes.. I had VERY basic knowledge of python when I started my project and tbh I feel like I still do. I know I learn best when I do projects so I’m wondering if you guys know any websites like frontend mentor but for python?

7 Comments
2024/04/06
02:32 UTC

2

How should I perform a brute force API request?

Hi, I'm a full stack dev putting together a project to demonstrate some OWASP security concepts for my coworkers.

I have a vulnerable backend login endpoint (that I made) and script that uses requests to try to login until it cracks the password (which is password, it's like number 6 in the file).

Right now, it makes a request and waits to get a response, which is very slow. That's okay for that use case but I know I have more in the demo that will have to run more than 6 times. I figured I should do this asynchronously to speed it up, but I'm not sure what the best way to go about doing that is. Does anybody know?

1 Comment
2024/04/06
01:35 UTC

0

How do I extract a url which is hidden (ie cant be accessed from dev tools) without clicking on it or going to that page using python?

I have a page A which has images 1,2,3,4,...100 and if i click on each image, I can go to the corresponding page of the image which has few other details. But those links of those images are not visible in the DOM or through dev tools. Ideally I wanna build a script using python where I can extract those links of the images without actually clicking on the image itself or loading the image detail page. How do I do it? I was thinking of using the network payload or using a proxy. Is it possible? if yes how? Which tools?

7 Comments
2024/04/06
01:14 UTC

1

Why I get following error when I run code in vscode? But python is already installed as u can see?

In vscode when run code: python -u "/home/neon/ Programming/python/some.py" Command 'python' not found, did you mean: command 'python3' from deb python3 command 'python' from deb python-is-python3

Cmd: python3 --version Output: Python 3.11.6

Cmd: python3 Output: Python 3.11.6 (main, Oct 8 2023, 05:06:43) [GCC 13.2.0] on linux Type "help", "copyright", "credits" or "license" for more information.

4 Comments
2024/04/06
00:24 UTC

1

Saving database password in script!

So I’m looking to automate some task with python. Basically every morning we would extract some data from an Oracle database and do some analysis with it.

However, the password and username would be typed into the script. Reading up on that it says it’s a security concern. However, I don’t see an alternative since it needs to be automated. Specifically I created a class to connect to our database, do extract data from the database and close the connection.

I did this since we plan on doing multiple automations like this so I figured it was easier, limits error and try to do as many exception handling as possible there.

So the password would be stored only in the script where that class is located.

However, I don’t see an alternative with the password as it’s automated. Our team all shares the same password/username for the database no one gets their own.

However, all our scripts are saved on a shared drive via a network. To connect you need to be connected to the vpn. So unless you’re connected to the vpn you can’t access that drive. Similarly you can’t run sql automations unless connected to said vpn.

Not much of an it guy, so don’t know much about data security. But I’m failing to see a better solution. If there’s concerns about someone accessing the password that’s means they’re on the vpn and knowing the password would be the least of our concerns.

4 Comments
2024/04/05
23:30 UTC

0

Is it possible to scrape text data from a video game in Python?

Hi, I'm very new to Python. I'm still learning the fundamentals but I have a few ideas for projects I would like to try out sooner or later. One would involve taking text from a video game with some sort of chat (Like Overwatch or TF2 where players can type in the chat and everyone else can read it). I'm learning that I can use Python to scrape web data and was wondering if it was at all possible for a Python program to somehow take the text from a video game (For instance, the data I'm expecting to get is stuff like "Spy behind you Sniper!" or "Switch off Hanzo you are terrible" and be able to use that data as part of a larger program in real time like a text to speech app. (OW already has something like this but I want to see if I can make it myself.)

5 Comments
2024/04/05
23:06 UTC

1

Intel i7 8th gen?

Sorry if this is not relevant for this sub but it seemed suitable to me. I am a 16 year old learning coding (I know decent amounts of python and want to try learning other languages) and am thinking about buying my first laptop that isn’t a shared family hp from 2014. I was looking at a thinkpad t480 with an intel i7 8th gen core and 16gb of RAM and was wondering if this was good enough to learn coding on over the next few years or if I should save up for a newer more up to date model. Any help is greatly appreciated :)

9 Comments
2024/04/05
23:04 UTC

0

Haven't been able to have python(with pycharm) working ever since adding new HD and reinstalling

Image with error codes. Doesn't seem to recognise any packages and I can't install them.

https://postimg.cc/sM9Y5GWx

1 Comment
2024/04/05
22:41 UTC

15

Most effective way to keep a python script always "running" on a server?

Let's say I have a script that listens to data that comes from some connection. For example, data comes from the chat of a Youtube stream.

Based on the received data, the script will do something, such as send a response somewhere else.

What is the most effective and simplest way to just keep this thing running? nohup, the linux tool?

77 Comments
2024/04/05
21:58 UTC

0

LOOONg list of errors when running my reddit bot

I get this long list of error when running my reddit bot. i gather its an authentication error but any idea how to fix???

Traceback (most recent call last):
******\python\redditbot\bot2.py", line 10, in <module>
print(reddit.user.me())
^^^^^^^^^^^^^^^^
****python\Lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
******\python\Lib\site-packages\praw\models\user.py", line 168, in me
user_data = self._reddit.get(API_PATH["me"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
******\python\Lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*******\python\Lib\site-packages\praw\reddit.py", line 712, in get
return self._objectify_request(method="GET", params=params, path=path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
******python\Lib\site-packages\praw\reddit.py", line 517, in _objectify_request
self.request(
*******\python\Lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*******python\Lib\site-packages\praw\reddit.py", line 941, in request
return self._core.request(
^^^^^^^^^^^^^^^^^^^
********python\Lib\site-packages\prawcore\sessions.py", line 328, in request
return self._request_with_retries(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
********\python\Lib\site-packages\prawcore\sessions.py", line 234, in _request_with_retries
response, saved_exception = self._make_request(
^^^^^^^^^^^^^^^^^^^
*******\python\Lib\site-packages\prawcore\sessions.py", line 186, in _make_request
response = self._rate_limiter.call(
^^^^^^^^^^^^^^^^^^^^^^^^
********\python\Lib\site-packages\prawcore\rate_limit.py", line 46, in call
kwargs["headers"] = set_header_callback()
^^^^^^^^^^^^^^^^^^^^^
*********python\Lib\site-packages\prawcore\sessions.py", line 282, in _set_header_callback
self._authorizer.refresh()
********python\Lib\site-packages\prawcore\auth.py", line 425, in refresh
self._request_token(
*****python\Lib\site-packages\prawcore\auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request

1 Comment
2024/04/05
21:48 UTC

2

I need help with curses

Hi, I tried to work on TUI to my project using curses library(first time using it) but when I try to open this file thru cmd in the same directory as file with

python TUI.py

it goes to next line waits a bit and I can type next command

Same code works perfectly on android python emulator when I tested it

import curses
from curses import wrapper

def main(stdscr):
    stdscr.clear()
    stdscr.addstr(10, 10, "Hello World")
    stdscr.refresh()
    stdscr.getch()
curses.wrapper(main)
4 Comments
2024/04/05
21:47 UTC

11

Why is print() behaving this way?

from time import sleep

string = "1234"
delay = 0.5

for char in string:
    print(char)
    sleep(delay)

for char in string:
    print(char, end='')
    sleep(delay) 
print()

First loop did what I expected: printed a character, waited a half second, repeat, each char on a new line.

The second loop, however, sits for two seconds and then prints "1234" all at once, rather than one character at a time.

What's going on? Is it just some under-the-hood quirk of print() or stdout or something? Is there a way around it in order to have a string print slowly along a single line as though it's being typed in real time?

12 Comments
2024/04/05
21:20 UTC

1

gspread Error

Hello!

Pretty new to Python, and been using gspread a bit.

All of a sudden i get this error.

ImportError: cannot import name 'Client' from 'gspread.client' (C:\Users\SQUARED2_io\AppData\Local\Programs\Python\Python312\Lib\site-packages\gspread\client.py)

And I have no idea what happened - The script has been working all week, and now it just wont do anything but give me this error.

Any tips on what to do?

Br, SQ2

1 Comment
2024/04/05
21:06 UTC

3

Want to write a program to encourage/remind me to do basic daily tasks. Any pointers?

Trying to organise my basic daily life with Python. Any pointers?

Hi. I’m neurodivergent and have some adhd related difficulties with basic daily tasks. I need reminders and encouragement from others to manage my daily life. For example, if someone doesn’t gently encourage me to eat then sometimes I just won’t eat, same with things like washing, grocery shopping, drinking enough water etc. I can do all of these things but remembering or finding the motivation to actually do them is very difficult to maintain. It’s been frustrating because I have a job, pay my own bills etc but can’t maintain an organised daily life when it comes to the basics.

To develop more independence, I would like to use a simple program that encourages me and reminds me to do these basic things each day, ie having my desktop pop up each day checking I’ve had lunch rather than relying on another person to ask me if I forget. Then if I haven’t yet, having my desktop check in again a little later. I’ve tried some reminder apps but they’re not interactive enough to work for me.

So for example, say I’ve gone too long without a shower without realising. I would like to avoid this with a program where my desktop pops up to ask me when I last showered and encourage me to do so if it’s been beyond a certain timeframe, then check in again later to confirm I’ve done it or remind me I still need to do it. And have my desktop do that with all kinds of basic tasks eg checking in to confirm I’ve eaten, drank enough water, fed my pets etc.

I know this sounds really silly because who would ever forget to shower or eat but I do all the time and it’s really holding me back. I would like to be more independent and not rely on the encouragement of other people so often to do such basic things but I just can’t quite manage to do it consistently. I hold down a job, pay my bills etc but I just can’t quite get the hang of managing my own basic daily tasks day to day.

Am I right in thinking I could automate this with python so my computer can remind and encourage me to eat, drink, wash etc instead of other people having to remind and encourage me?

Any reference material or programming advice would be appreciated. I’d like to keep my program/project as simple as possible so I’m not trying to make it respond to my voice or talk to me like an Alexa or something. I just want my computer to ask me things like “have you made dinner yet?” And then send reminder messages if not.

Thank you

3 Comments
2024/04/05
20:34 UTC

0

type("hello" == "world") returns BOOL - How?

HELLO WORLD! I am a newbie to Python.
Came across this line of code which results in "Bool". Can you please tell me how this expression returns a boolean type -
type("hello" == "world")

35 Comments
2024/04/05
19:52 UTC

3

Converting list of integers into multi-line string

Say I currently have a list of integers - [90, 85, 80, 72, 68], and I want the output to be:

90

85

80

72

67

How would I go about this?

6 Comments
2024/04/05
19:40 UTC

1

What is the best way to increase proficiency within a topic?

I am currently trying to get better at classes within Python. Is it best to keep trying things out myself without other people's input or should I watch YouTube videos and look at what they do? etc. etc.

And does your advice apply to ALL of programing?

Thank you.

7 Comments
2024/04/05
19:24 UTC

2

Data Structures and Indexes

def bubble_sort(unordered_list):

iteration_number = len(unordered_list)-1

for i in range(iteration_number,0,-1):

    for j in range(i):

        if unordered_list[j] > unordered_list[j+1]:

            temp = unordered_list[j]

            unordered_list[j] = unordered_list[j+1]

            unordered_list[j+1] = temp

Anyone have helpful hints on what made using indexing easier for them? I've used pythontutor.com and the debugger and it makes some sense theoretically but when it comes to having to write them to hold and move values I get lost.

5 Comments
2024/04/05
19:14 UTC

2

Different Outcomes: Using 'or' vs ' | '

I am getting differences in my frequency table depending on if I use " or " vs " | ".

I am trying to generate a frequency table for how many rows contain the words "Web Developer" or "Mobile Developer".

Each row may contain a single entry or a list (i.e. [Front-End Web Developer, User Experience Designer, Data Engineer, Mobile Developer, Data Scientist]).

Code 1:

# Filter for Web Developer or Mobile Developer
web_or_mobile = interests_no_nan.str.contains("Web Developer|Mobile Developer")

# Frequency table
freq_table = web_or_mobile.value_counts(normalize=True) * 100

Code 1 Output:

JobRoleInterest
True     86.241419
False    13.758581

Code 2:

# Filter for Web Developer or Mobile Developer
web_or_mobile = interests_no_nan.str.contains("Web Developer" or "Mobile Developer")

# Frequency table

freq_table = web_or_mobile.value_counts(normalize=True) * 100

Code 2 Output:

JobRoleInterest
True     82.608696
False    17.391304

I'm not sure why there is a difference in output or which one is correct. Any insights?

10 Comments
2024/04/05
18:29 UTC

0

Need help for my AP Comp Sci project

My entire code is a clicker game that has various upgrades and unlocks, and for my final feature I’m implementing a rebirth button, which would reset the entire program and add an extra rebirth multiplier. Is there a command I can add that would restart the entire program, or do I have to individually reset all the values and set everything back to not visible and locked and what not, because that would be a lot of code. P.S. I’m using CS CMU academy for python coding because that is what’s required.

1 Comment
2024/04/05
18:25 UTC

0

Selenium can't interact with element

I'm using selenium to automatically fill out a form, but for some reason, it cannot interact with "field emphasis" classes. I believe the background being grey might have something to do with the issue (CSS).

I can't find a solution to this problem and any help is appreciated. Thanks !

0 Comments
2024/04/05
18:18 UTC

8

What's your process for updating python versions/packages while maintaining backwards compatibility?

Auditors have recently been hounding me to update my Python version from 3.7 since it's fallen out of support and apparently a few exploits exist that are significant enough to raise an eyebrow.

It was easy enough to get python 3.12 installed and I don't have any concern with the changes in regards to alterations to the syntax of basic python, however, when packages come into the picture quite a few of my commonly used packages have also received updates and undergone some form of deprecation that would require some revision.

The easy approach would be just to install the known working versions of the packages but if there are security concerns with python itself I can only imagine that there have to be some lurking in some of these packages that haven't been updated for 5+ years.

In the past I just had a single master venv that was more or less shared across all projects, which I'm aware is bad practice but with 30+ active projects that require more or less the same packages so creating individual virtual environments for all of them would have been a bit of a chore.

My first approach was to create a new master venv with only the new packages but tested it on a few small projects and (as expected) there were immediate conflicts that required some code adjustments.

Obviously I would rather avoid making changes across the whole code base if I can avoid it, so I'm kind of curious if anybody has a better approach. My first thought which seems easiest is just creating a secondary master venv for legacy code with old package versions and use the updated venv for any new code but I'm unsure if that's the "right" way to do things.

Thoughts?

12 Comments
2024/04/05
17:57 UTC

0

Is Python a good language for Blockchain development?

I'm actually a data scientist, currently a master student and doing a research in smart contract development and implementation. I know there are ways to use any language to build blockchain, despite that it's gonna be more complex than using javascript and the maturity of each blockchain environment, but is it that bad? Cheers!

5 Comments
2024/04/05
17:35 UTC

1

Hi why am I getting this error on my hand tracking system in python?

[ WARN:0@51.102] global cap_msmf.cpp:475 `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072875772

[ WARN:0@51.223] global cap_msmf.cpp:487 `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072875772

[ WARN:1@51.312] global cap_msmf.cpp:1768 CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072875772

Traceback (most recent call last):

File "c:\Users\DELL\Desktop\python\uhhh.py", line 7, in <module>

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

The code being:

import cv2

import mediapipe as mp

cap = cv2.VideoCapture(0)

hand_detector = mp.solutions.hands.Hands()

while True:

_, frame = cap.read()

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

output = hand_detector.process(rgb_frame)

hands = output.multi_hand_landmarks

print(hands)

cv2.imshow('Hand tracker', frame)

cv2.waitKey(1)

2 Comments
2024/04/05
17:09 UTC

1

Hi why am I getting this error on my hand tracking system in python?

[ WARN:0@51.102] global cap_msmf.cpp:475 `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072875772

[ WARN:0@51.223] global cap_msmf.cpp:487 `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072875772

[ WARN:1@51.312] global cap_msmf.cpp:1768 CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072875772

Traceback (most recent call last):

File "c:\Users\DELL\Desktop\python\uhhh.py", line 7, in <module>

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

The code being:

import cv2

import mediapipe as mp

cap = cv2.VideoCapture(0)

hand_detector = mp.solutions.hands.Hands()

while True:

_, frame = cap.read()

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

output = hand_detector.process(rgb_frame)

hands = output.multi_hand_landmarks

print(hands)

cv2.imshow('Hand tracker', frame)

cv2.waitKey(1)

0 Comments
2024/04/05
17:09 UTC

1

Yolov8 training

I want to train yolo v8 it seems like it takes forever, and my laptop is barely able to make it however, if i train the gpu is not active should i switch to gpu or should the cpu and gpu work on training also lets say if i only want the yolo software to detect objects can i just train the algorithm on all kind of items and ibjects or while i just make it not work at all if i do so

3 Comments
2024/04/05
16:23 UTC

1

Need Help: Emoji to Image Converter model?

I'm looking for something simple: a tool or model that can turn emojis into images. Know of any? Thanks!

2 Comments
2024/04/05
16:23 UTC

4

Learning fundamentals of Python, please help me understand why 'none' prints out after I ran my practice code.

def greet(lang) :
    if lang == 'es':
        print('Hola')
    elif lang == 'fr':
        print('Bonjour')
    else :
    print('Hello')

lang = input('Enter Language: ')
print(greet(lang))

After I run this code, and input 'es', 'fr', or anything else, it spits out the correct language, but adds 'none' at the end.

Enter Language: es

Hola

none

help.

7 Comments
2024/04/05
15:50 UTC

0

Any tutorial on how to create a ChatGPT app without using the ChatGPT API using a GPT-1, GPT-2 or GPT-3 model?

I don't want to train it, because I can't, my laptop is too slow (Intel 7), but I want to run a model and create a ChatGPT app with a worse or much worse model than GPT-3.5 just to learn.

2 Comments
2024/04/05
15:49 UTC

Back To Top