The Wayback Machine - https://web.archive.org/web/20241202064918/https://www.reddit.com/r/pythontips/
Skip to main content

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores
r/pythontips icon
r/pythontips icon

r/pythontips

members
online



Advice • Advice
Python3_Specific

hello everyone, im someone who has freshly started learning python. i daily sit myself down to watch programming with mosh and learn python. i spend a good 2 hours everyday.

my method of approach is i listen and then i type the same code as practice on PyCharm and then i write it down in a notebook.

if some of you dont know, there are certain challenges or exercises in between topics and i have been finding it hard to code a solution for that which has left me feeling like im not fit for this.

so i wanted to ask the community if "me not being able to write a code by myself right of the bat" is normal or am i doing something wrong? any help/advice is greatly appreciated.

tell me what i can do better or what i can change so that i can learn python efficiently and be able to write my own code and execute.



JSON int64 and dropping rows in pandas? • JSON int64 and dropping rows in pandas?
Syntax

I’m getting errors when trying to delete rows in a PANDAS data frame and when trying to output my data into a json file.

Pandas: Trying to drop rows where the value in one column = the value of a variable just outright isn’t working at all. I don’t know if I’m doing the wrong syntax or what, but it just never works? Can someone point me in the right direction?

JSON: I’m getting the error “Object of type int64 is not JSON serializable”. Pretty sure this is something to do with taking my data out of the dataframe and using sum() on it, but I don’t know how to fix it. Then again I could completely be misinterpreting the cause since it’s near impossible to find a simple, comprehensive fix for this anywhere online.

SOS!!


What's wrong with this? • What's wrong with this?
Module

from data.functions import * eatHalf_follows = get_user_follower_count("eatHalf")

Evilcorp_follows = get_user_follower_count("Evilcorp")

flyGreen_follows = get_user_follower_count("flyGreen")

if eatHalf_follows > Evilcorp_follows & eatHalf_follows > flyGreen_follows: print("eatHalf has the most followers with:") print(eatHalf_follows) print("followers!")

elif flyGreen_follows > Evilcorp_follows & flyGreen_follows > eatHalf_follows: print("flyGreen has the most followers with:") print(flyGreen_follows) print("followers!")

elif Evilcorp_follows > flyGreen_follows & Evilcorp_follows > eatHalf_follows: print("Evilcorp has the most followers with:") print(Evilcorp_follows) print("followers!")

Note: This program doesn't generate an output ————————————————————————

Written in Brilliant to determine which social media user has the most followers


Paramiko Help Please..... • Paramiko Help Please.....
Syntax

Hi folks,

I'm just learning and trying to connect and issue commands to a server I have on my bench.. If I putty into it via SSH , I can see my code does log onto and authenticate with the unit, but none of my commands seem to do anything (I tried reboot and nothing happened). After finding this out, it explained why I'm getting no responses to any commands I try. In a nutshell, it appears none of my commands are being sent over to the server despite being logged in.

Code:

import paramiko


responses = []
host = '192.168.0.32'
username = input('Enter Username: ') or 'admin'
password = input('Enter password: ')

try:
    session = paramiko.SSHClient()
    session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    session.connect(hostname=host, username=username, password=password)
    while True:
        try:
            cmd = input('> ')
            if cmd == 'exit': break
            stdin, stdout, stderr = session.exec_command(cmd)

            for line in stdout:
                responses.append(line.strip('\n'))

            for i in responses:
                print(i.strip())

        except KeyboardInterrupt:
            break
    session.close()

except Exception as err:
    print(str(err))

If I do the commands via putty I get the expected response so I'm not sure whats going on.. Any tips please? Am I doing this totally wrong? I'm scratching my head as I'm doing not much different to an putty session - only diff is I'm not typing, but instead sending commands over the connection. Could it be how the server is set up?

Thanks in advance....


Having trouble with Vending Machine assignment • Having trouble with Vending Machine assignment
Module

Hallo, for my python course we have to make a virtual vending machine which i have successfully done and now the final step is "Convert my program to Client-Server Model with Socket Communication" which has left me confused and stressed as i cant really understand how to do that. If anyone could help please dm me and i'll provide alot more info on my problem as this subreddit doesn't allow images and idk how to explain my problem in words. Thank you.




Quick on local, hours of delay on server • Quick on local, hours of delay on server
Algorithms

Hey guys, looking for some thoughts on this!

I have a program with a few components but basically how it works is simple.

It’s a chatbot that connects to my business line.

Basically it does the following: •Stores texts that come into the server via webhook •Retrieves the users profile in my crm based on their phone number •Pulls the last 10 or so messages with them •Submits request to OpenAI api to generate a response

Now the problem is that on local, it works and runs very smoothly. On the server, it seems to breeze through the storing of the messages but stops about there and then takes hours before I get a response.

Started off as just a few mins, then an hour or so and then the most recent was like 12 hours later, and in writing this im now thinking maybe I forgot to close the session somewhere in the code.

Other details: Using mssql for the server and pymssql with sqlalchemy for the ORM.

Pythonanywhere for the server, with a function to auto add the ip to mssql of the session since I know it’s dynamic with PA.

Any thoughts? I appreciate any insight you guys might have, TIA!


Python giving me trouble • Python giving me trouble
Module

Hello So i am very new to programming and don't know much and was facing some trouble with it and wanted to know what I can do. So basically when I install a library through pip on cmd say matplotlib, the query goes through and the module is installed but when I go to pycharm and import the module there it shows me the ModuleNotFoundError. I even reinstalled the library but still nothing and this problem persists with several modules. Does someone know what could be the issue and how I could fix it?


text based adventure game project • text based adventure game project
Module

Hey there, I am a student planning to go into a computer science course in uni next year and I am on a foundation program that includes a computer science / coding course which is teaching python.

While I am familiar with coding I am still at beginner level knowledge.

Our professor has assigned a project of creating a text based adventure game, which is a creative and effective way to learn how to code if you are a beginner.

While I have a plan in mind of how I want to structure my game, I am having trouble identifying which would be a more suitable way to go about it.

I want to create rooms / scenes so the character can move around the map, but I am not very sure if I should do it by creating different modules and fucntions to call them in to my main program or if I should include those scenes/map inside of my main function using dictionaries.

I'd appreciate any advice given, or any tips.


Tips for filtering data with given attributes. • Tips for filtering data with given attributes.
Algorithms

Hello, I'm a computer engineering freshman. I am taking a course (Programming Logic and Design). We have an assignment about filtering a data which we will create a python code that filters a data that follows the criteria.

The criteria:
- Age >= 18
- emain_verified == False
- status == "pending"

The data is this:
user_id | name | age | email_verified | status (assume that these are the columns that represents the value; it is not included in the users.txt file)

This will be the included strings or data that are in the users.txt file

1 JohnDoe 25 True Active
2 AliceSmith 18 False Pending
3 BobJohnson 30 True Active
4 EveDavis 19 False Pending
5 CharlieBrown 40 True Suspended
6 DavidWilson 22 False Pending

I've created this code:

def main():
    user_file = "users.txt"
    output_file = "filtered_users.txt"
    file = check_exist(user_file)
    filtered = filter_users(file)
    write_filtered(output_file, filtered)
    print_filtered(output_file, filtered)


def check_exist(name):
    try:
        with open(name, "r") as file:
            return file.readlines()

    except FileNotFoundError:
        print("Error: File not found")
        exit()


def filter_users(file):
    filtered = []

    for line in file:
        list = line.split()

        if len(list) == 5:
            user_id, name, age, email_verified, status = list
            age = int(age)
            email_verified = email_verified.lower() == 'true'

        if age >= 18 and not email_verified and status.lower() == 'pending':
            user = [user_id, name, str(age), str(email_verified), status]
            filtered.append(user)
    
    
    return filtered
        

def write_filtered(output, filtered):
    with open(output, 'w', encoding='utf-8') as file:
        for line in filtered:
            file.write(" ".join(line) + "\n")
            

def print_filtered(output, filtered):
    print(f"Filtered data has been written to {output}")
    print("-----Filtered Users Report-----")
    print(f"Total users that meet the criteria: {len(filtered)}")
    for line in filtered:
        user_id, name, age, email_verified, status = line
        print(f"User ID: {user_id}, Name: {name}, Age: {age}, Status: {status}")


main()

The console output would look like this:
Filtered data has been written to filtered_users.txt
-----Filtered Users Report-----
Total users that meet the criteria: 3
User ID: 2, Name: AliceSmith, Age: 18, Status: Pending
User ID: 4, Name: EveDavis, Age: 19, Status: Pending
User ID: 6, Name: DavidWilson, Age: 22, Status: Pending

The created file which is the filtered_users.txt contain:
2 AliceSmith 18 False Pending
4 EveDavis 19 False Pending
6 DavidWilson 22 False Pending

I have finished the assignment but I'm still looking for a better way to code this problem. Can someone suggest or give advice as to how I can improve this code? Thank you!




Pathfinding AStarFinder sometimes works but sometimes doesn't? • Pathfinding AStarFinder sometimes works but sometimes doesn't?
Module

I'm using the pathfinding module to find whether 2 rooms in my 2d dungeon are connected, on the grid 1 means a floor, 0 means empty, which aligns with the pathfinder algorithm, and sometimes it does find a path so it CAN work, but i see a lot of the time it can't find the path between 2 coordinates which obviously have one, example:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0

0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0

0 0 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0 0 1 0 0 1 0 0 0 1 1 1 1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0

0 0 0 0 1 0 0 1 0 0 0 1 1 1 1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0

0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

_______________________________

[] 423 (18, 27) (17, 7)
[] means there was no path found, 423 is the number of runs it did, the 2 () are coordinates of start and end.

Now, I would get if it didn't run all the time, but sometimes finding a path and sometimes not? i don't get it.

parts of the code:

grid = Grid(matrix=mdungeon)
start = grid.node(center_coords[x][0], center_coords[x][1])
end = grid.node(center_coords[y][0], center_coords[y][1])
p, runs = finder.find_path(start, end, grid)
print(p, runs, center_coords[x], center_coords[y])

from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
finder = AStarFinder()

how to do it ? Im confused ?
u/[deleted] avatar[deleted]
•
how to do it ? Im confused ?
Module

so I made a calculator that shows if you are eligible drive or not but I'm not getting the output I want . what's wrong with my project ? I have tried everything . See I'm getting the output that you cannot drive if, you are above 18 and if you are below 16 your guardians have to pay 3000 , this is the output I want but when I'm typing 22 or 23 it is still showing that you cannot drive ???

if a>18:
    print("you cannot drive and you have to pay 2000")

elif a<16:
    print(" your guardians have to pay the fine of 3000")

elif a>21:
    print("you can drive,you don't have to pay")

else:
    print("you can't drive and you have to pay 2000")


Problem with intuitive understanding of zero-based indexing, how did you work it out? • Problem with intuitive understanding of zero-based indexing, how did you work it out?
Meta

Title says it all. Should I just try to memorize the rules, or are there any tricks to intuitively understand it?

Every time I have to work with indexes, I say to myself "Ah shit, here we go again". A couple of indented loops + lists - and I am already checked out. Just now, I failed to utilize an iteration with a negative step.


The Dangers of Misusing __dir__ and @property in Python: An Anti-Pattern Exposed • The Dangers of Misusing __dir__ and @property in Python: An Anti-Pattern Exposed
Meta

I've seen a recurring anti-pattern where developers use these constructs to perform heavy operations, such as making network or gRPC calls. While it might seem like a clever shortcut, this practice often leads to subtle bugs, performance issues, and an unpleasant developer experience.

read the full article:

https://technotes.blog/2024/11/20/the-dangers-of-misusing-__dir__-and-property-in-python-an-anti-pattern-exposed/


Recieving windows notifications on phone • Recieving windows notifications on phone
Module

Hey guys, i wanted to ask, how can i make it possible with python to recieve notifications on my phone whenever windows recieves one. I tried and i came close. I used telegram bot to send me messages of activity. Firstly i tested the bot with sending messages to my account and it works. The issue i came accross is winrt is outdated and i can't run the code. Is there any other alternative? Please if anyone has an answer, write to me.


Python Crash Course Notebook for Data Engineering • Python Crash Course Notebook for Data Engineering
Long_video

Hey everyone! Over the last 2 weeks, I put together a crash course on Python specifically tailored for Data Engineers. I hope you find it useful! I have been a data engineer for 4+ years and went through various blogs, courses to make sure I cover the essentials along with my own experience.

Feedback and suggestions are always welcome!

📔 Full Notebook: Google Colab
🎥 Walkthrough Video (1 hour): YouTube

💡 Topics Covered:

  1. Python Basics

    • Syntax, variables, loops, and conditionals.

  2. Working with Collections

    • Lists, dictionaries, tuples, and sets.

  3. File Handling

    • Reading/writing CSV, JSON, Excel, and Parquet files.

  4. Data Processing

    • Cleaning, aggregating, and analyzing data with pandas and NumPy.

  5. Numerical Computing

    • Advanced operations with NumPy for efficient computation.

  6. Date and Time Manipulations

    • Parsing, formatting, and managing date time data.

  7. APIs and External Data Connections

    • Fetching data securely and integrating APIs into pipelines.

  8. Object-Oriented Programming (OOP)

    • Designing modular and reusable code.

  9. Building ETL Pipelines

    • End-to-end workflows for extracting, transforming, and loading data.

  10. Data Quality and Testing

  • Using unittest, great_expectations, and flake8 to ensure clean and robust code.

  1. Creating and Deploying Python Packages

  • Structuring, building, and distributing Python packages for reusability.

Note: I have not considered PySpark in this notebook, I think PySpark in itself deserves a separate notebook!


CSC 125 - Python Final HELP NEEDED • CSC 125 - Python Final HELP NEEDED
Python3_Specific

Hello! Im about to take a python final in the upcoming weeks for uni and I'm pretty okay with python, seeing as though I've come from knowing absolutely jack diddly about it at the start of the semester, but the professor doesn't really teach well. Anyways, i digress, heres the dilemma:

For our final, one part of it is applying the "basics" of what we've learned in the class and to create the following using python:

"A python app that presents the user with a few menu options, asks them to choose an operation, collects data for calculation, does the math, presents the answer, and shows the menu again. the app loops until the user chooses the menu option to quit"

My thought process goes immediately to inputs, strings, if, else, and then statements, but whats the best way to go about actually preparing for this final? Do i watch videos on strings and practice inputs for users to answer, etc? How do i break this down into smaller chunks so that I can ace the exam ?


Making a quiz with coding • Making a quiz with coding
Module

Hey all, sorry i'm practically a begginer on using python, i wanted to ask is there any way i can make a quiz with no wrong answers but each answer to give set amount of points, in the end for the people doing the quiz i want them to recieve grading(with words depending what the quiz is about, example: if the quiz is about fear the grading to show Fearless, Slightly fearful, Afraid of everything). And a description of the grade they got. And ofcourse for them to know the points.

To explain it again more clearly 22 questions

After answering them

Results: 68 You are "Fearless"

(Description of how you are and why below it)

Now that i explained how i want it to be, is it possible at all to make a quiz with coding and send it to people for them to answer it?

I know there are online quizzes but all the ones i searched satisfy the things i need in the quiz. If anyone has idea on how to make the quiz with python or if anyone knows a quiz site where i can add all my things respond here or DM.