/r/pythontips

Photograph via snooOG

A place to get a quick fix of python tips and tricks to make you a better Pythonista.

Enter a python tip or trick.

  • Can be basic or advanced.
  • Should be explained with formatted code.
  • Not a place for asking for help. (Do that at r/learnpython).
  • However, discussion about tips and tricks are encouraged in the comment section.
  • Do not link to a list or blog of python tips.
  • A post should center around one main tip.

 

Other related Python subs:

  • /r/python: News and discussion about Python.
  • /r/learnpython: Ask for help with your code or for explanations of things.
  • /r/django: News about django (Python Web Framework).

/r/pythontips

127,768 Subscribers

7

Instant analytics for fastAPI

I recently discovered www.apianalytics.dev

It's a very simple way to add analytics to a fastAPI
They give you an API key, you add 1 line to your python app, and you've got a monitoring dashboard online.
It's not my tool, but I'm using it in production for a small project I host and it's great

0 Comments
2024/11/30
04:22 UTC

4

Python Online IDE

This project integrates Streamlit, the Ollama model, and a local Python environment to dynamically generate and execute Python code. Users can interact with the Llama2 model for code generation and execution, providing a seamless experience for both input handling and file management.

Code: https://github.com/MuhammadMuneeb007/PythonOnlineIDE/

0 Comments
2024/11/29
17:45 UTC

2

Advice

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.

9 Comments
2024/11/29
11:06 UTC

2

Music21 help

Hey I am an aboslute beginner in using python. I was trying to install Music21 through python using the command: Pip install music21 But I get syntax Error. I've tried asking chatGPT, but nothing works. Anyone that has a new approach to this problem?

5 Comments
2024/11/29
09:19 UTC

1

JSON int64 and dropping rows in pandas?

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!!

2 Comments
2024/11/29
03:31 UTC

0

What's wrong with this?

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

7 Comments
2024/11/29
02:03 UTC

1

Paramiko Help Please.....

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....

0 Comments
2024/11/28
11:10 UTC

0

Python

I've started learning python with python for everybody can u gimme any suggestions

7 Comments
2024/11/28
10:32 UTC

0

NameError: name 'f_name' is not defined

def intro(f_name, l_name):

print("Hello, my name is", f_name, l_name)

f_name = input("What is your first name?")

l_name = input("What is your last name?")

intro(f_name, l_name)

10 Comments
2024/11/28
07:07 UTC

0

Having trouble with Vending Machine assignment

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.

1 Comment
2024/11/28
06:59 UTC

2

Quick on local, hours of delay on server

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!

2 Comments
2024/11/25
14:21 UTC

1

Python giving me trouble

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?

3 Comments
2024/11/25
08:26 UTC

4

text based adventure game project

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.

8 Comments
2024/11/24
11:53 UTC

2

Tips for filtering data with given attributes.

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!

5 Comments
2024/11/23
13:33 UTC

0

Python not running program

In the console I wrote a guess the number game and when I hit enter to run it it just creates another line.

6 Comments
2024/11/22
14:35 UTC

2

Python Screening on outlier

can anyone tell me what I need to be prepared of to pass this test on outlier ai? They told me it'll be 2-3 tasks and I need to score a pass mark but I don't know what to expect.

0 Comments
2024/11/22
10:27 UTC

0

how to do it ? Im confused ?

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")
11 Comments
2024/11/22
07:32 UTC

6

Extract pdf data from budget table into usable data (python, VBA)

Hello, What type of library or script do you use to convert (numerous) budgetary documents into usable data for statistical, econometric analysis, etc. If you have ideas for a manual/video/forum to explore the subject in more depth ;) Beautiful evening

4 Comments
2024/11/20
22:06 UTC

9

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

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.

13 Comments
2024/11/20
14:20 UTC

2

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

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/

0 Comments
2024/11/20
13:24 UTC

2

Recieving windows notifications on phone

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.

1 Comment
2024/11/20
11:08 UTC

0

CSC 125 - Python Final HELP NEEDED

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 ?

6 Comments
2024/11/18
16:29 UTC

21

Python Crash Course Notebook for Data Engineering

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 unittestgreat_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!

2 Comments
2024/11/18
12:24 UTC

2

Making a quiz with coding

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.

4 Comments
2024/11/17
14:57 UTC

7

Python Dictionary Quiz - Guess The Output

What is the correct way to define a dictionary with the following data:

  • Key: "name", Value: "Alice"
  • Key: "age", Value: 25

A) dict1 = {"name" = "Alice", "age" = 25}
B) dict1 = {name: "Alice", age: 25}
C) dict1 = {"name": "Alice", "age": 25}
D) dict1 = {"name": Alice, "age": 25}

Thanks

5 Comments
2024/11/17
06:35 UTC

2

help me understand, how this code works, can't understand the 'if numbers[x] < 20:' part

nums = [1,35,12,24,31,51,70,100]

def count(numbers):

total = 0

x = 0

while x < len(numbers):

if numbers[x] < 20:

total += 1

x += 1

return total

count(nums)

20 Comments
2024/11/16
08:58 UTC

2

PyInstaller not able to export project to .exe

the cmd command was:

pyinstaller --onedir --windowed --icon=Roulette-Bot.ico --add-data "src/*.json;." --add-data "src/assets;assets" --add-data "src/data;data" --add-data "src/tesseract;tesseract" src\gui.py

but it seems to be unable to work with the jsons properly. If I open the .exe the jsons can't be found

Structure:
Roulette-Bot-Code/
├── .idea/
├── .venv/
├── build/
├── config/
├── dist/
├── logs/
│ └── app.log
├── src/
│ ├── assets/
│ ├── data/
│ ├── tesseract/
│ ├── betting_logic.py
│ ├── calibration.json
│ ├── calibration.py
│ ├── capture.py
│ ├── chip_calibration.json
│ ├── gui.py
│ ├── number_recognition_calibration.json
│ ├── progression_table.py
│ ├── recognition.py
│ ├── series_calibration.json
│ └── settings.json
├── Tesseract OCR/
├── tests/ │
├── test_calibration.py │
├── test_capture.py
│ └── test_recognition.py
├── .gitignore
├── gui.spec
├── README.md
├── README - Kopie.md
└── Roulette-Bot.ico

I tried different --add-data commands but nothing works. Always [name].json can't be found for any of the jsons in the src folder

2 Comments
2024/11/15
16:43 UTC

0

Anyone know how to change font for curses or if there are other terminal modules that allows you to change the font?

I'd like to make a terminal environment, preferably in the actual terminal to emulate the bulletin boards of the 80s, but I'd like to use some cryptic fonts as well. Anyone know if it's possible to change the font with curses or if there's another library that allows this?

4 Comments
2024/11/15
08:41 UTC

15

I am sharing Python Data Science courses and projects on YouTube

Hello, I wanted to share that I am sharing free courses and projects on my YouTube Channel. I have more than 200 videos and I created playlists for learning Data Science. I am leaving the playlist link below, have a great day!

Data Science Full Courses & Projects -> https://youtube.com/playlist?list=PLTsu3dft3CWiow7L7WrCd27ohlra_5PGH&si=6WUpVwXeAKEs4tB6

Data Science Projects -> https://youtube.com/playlist?list=PLTsu3dft3CWg69zbIVUQtFSRx_UV80OOg&si=go3wxM_ktGIkVdcP

4 Comments
2024/11/15
04:21 UTC

0

What's the problem?

nr = 1

('fr') + str(nr) == (opo)[:1]

nr = (nr) + 1

print (fr2)

print (fr3)

It says fr2 doesn't exist

Thank you

7 Comments
2024/11/14
22:28 UTC

Back To Top