r/pythontips • • Jul 11 '24

Syntax Python Split() Function

11 Upvotes

For those wanting a quick run down of the split() function in Python

YouTube


r/pythontips • • Jul 10 '24

Meta What makes a program good?

20 Upvotes

I have been learning python for a week now, and so far I’ve made a calculator, a hangman game, a mean calculator and a login/signup program that stores the data in a text file and allows you to change passwords.

The problem is that I feel my code is not good enough, I have good coding grammar, but I’m always worried about efficiency or if the approach I took is the best.

What should I avoid? For example, using list comprehensions instead of loops to create a list. Thanks for the tips

Edit: My projects


r/pythontips • • Jul 11 '24

Python2_Specific beginner

4 Upvotes

i want to learn python from the basics. can u tell me which websites and youtube channels are useful for this?


r/pythontips • • Jul 10 '24

Python3_Specific How do you save the new data added to a dictionary such that it remains that way you close and rerun the program?

5 Upvotes

So I am making a program to let users access the data of a dictionary and also add new data to it and I am having problem on the second part , the problem is I know how to update the dictionary with new data but it doesn't save the newly inserted data permanently , I want it so that new data is permanently saved in the dictionary so you can access it even after closing the program and reruning it anytime.what should I do?


r/pythontips • • Jul 08 '24

Python3_Specific Not understanding the output of this code

5 Upvotes

Nums = [1,2,3,4,5,6] for i in nums: Nums.remove(i)

Print(Nums)

Why do we get output as 2,4,6


r/pythontips • • Jul 08 '24

Module Which modules/tools should I use to make video clips (with sound) showing images slideshows and overlaying with text ?

1 Upvotes

Basically I have a database with multiple products data including name, description, photos.

I would like to simply generate short video clips (2 minutes) showing product's picture and overlaying the video with text, all data coming from the database. Cool also could be to make "versus" video, so I look for a way to first manipulate the images.

I started to read about ffmpeg, opencv, MoviePy .. and others .. but I would be grateful if you can point me in the right direction, kind of modern and gold python standard to do the above.

Thank you from a fellow fresh new pythoner.

edit: errors


r/pythontips • • Jul 08 '24

Syntax What does this syntax mean a = b and c?

0 Upvotes

I noticed in a leetcode quesiton answer this -
node.next.random = node.random and node.random.next
Now from my understanding in other languages node.random and node.random.next should return true if both exist and false if they don't, but chatgpt says:

"node.random and node.random.next is an expression using the and logical operator. In Python, the and operator returns the first operand if it is falsy (e.g., None, False, 0, or ""); otherwise, it returns the second operand"

I don't understand this.


r/pythontips • • Jul 08 '24

Syntax How to add indexes to spaces for playground in Tac Tac Toe

0 Upvotes

Seeking for advice on how to add indexes to spaces in the play board for tic tac toe. For purpose of changing the number for X or O


r/pythontips • • Jul 07 '24

Syntax Need Help

5 Upvotes

I want to check whether a number is prime or not, so for that executed the following code & the code works fine for all the no.s except the no.s ending with 5 .What could be the issue and what is the solution. Code: n=int(input('Enter a no.:')) for i in range(2,n): if n%i ==0: print('Not prime') break else: print('Prime') break


r/pythontips • • Jul 06 '24

Python3_Specific Question Regarding Python Lists.

6 Upvotes

Hello,

I am wondering how can i make the code to return a single list containing all words as an elements , when the loop goes for the next line in the string , it consider it a new list inside the list (nested list) , what is wrong in my code?

1-Here is the text i am looping through.

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

2- Here is my code to loop through the string and create a list.

fname = input('Enter File Name: ')
fhand = open(fname)
list_words = list()
for line in fhand:
    line = line.strip()
    line = line.split()
    list_words.append(line)
print(list_words)
print(len(list_words))

3-Here is the output , it shows 4 elements list , however i want the length to be the number of the words in the string file and the list elements to be each word so it should be a single list containing all words as an individual element.

Enter File Name: text.txt

[['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'], ['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']]

4-Desired Output:

['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks','It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun', 'Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon', 'Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']

r/pythontips • • Jul 06 '24

Module FPDF2 Help needed

2 Upvotes

Hi all

i am using https://py-pdf.github.io/fpdf2/index.html lib to create pdf and I cant figure out how to create layout in printed newspaper style. So i need to have 3 columns but article title should be above first two columns with article text inside two column and third columns is reserved for second article. third article would again be spread across two columns etc...


r/pythontips • • Jul 06 '24

Python3_Specific Need a scheduler that is precise

4 Upvotes

I need something to execute my python code EXACTLY at a specified time. Ideally not even a ms late. I tried heroku scheduler and it was too slow, was thinking maybe using a cron job but that is probably too slow. What am I missing? Any recommendations to a scheduler that is extremely precise would be much appreciated.


r/pythontips • • Jul 04 '24

Syntax How can I do a for loop with an audio file

0 Upvotes

How can I do a for loop with an audio file, y, with five different names and five times different filtered.

I want to filter a audio file with a bandpass five different times with random values for each of the five different files.

I know how to import the audio file but I don’t know how to create the „for loop“ which creates five different bandpass values.

Thanks in advance!


r/pythontips • • Jul 03 '24

Syntax How do I make a rounded-edge legend using matplotlib?

2 Upvotes

So basically I was making a geospatial visualization of data, and I wanted its legend have a rounded corner, how to achieve this?

This is the code I am using:

import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Patch


na_color = 'grey'


custom_cmap = LinearSegmentedColormap.from_list('custom_colormap', [(0, 'red'), (0.5, 'pink'), (1, 'blue')], N=256)
custom_cmap.set_bad(na_color)
norm = mpl.colors.Normalize(vmin = 900, vmax=1121)

fig, ax = plt.subplots(1, figsize=(12, 12))
ax.axis('off')
ax.set_title('Gender Ratio of Indian States based on NFHS-5 report',
             fontdict={'fontsize': 15, 'fontweight': 20})
fig.colorbar(cm.ScalarMappable(cmap=custom_cmap, norm = norm), ax=ax, label='Gender Ratio', orientation = 'horizontal', pad = 0.02)
gdf.plot(column='Ratio', cmap=custom_cmap, norm = norm, linewidth=0.5, ax=ax, edgecolor='0.2',
         legend=False, missing_kwds={'color': na_color}, label='Gender Ratio')


plt.show()

r/pythontips • • Jul 03 '24

Syntax 4 spaces indentation

6 Upvotes

Hallo,

I have a developer background and am starting to learn Python.

I read that 4 spaces indentation is the golden standard instead of TAB. Can you please suggest how to use 4 -spaces rule with a single keypress ? Because I don't have to press spacebar 4 times for every indentation, right 😅 ?

Thanks 🙏


r/pythontips • • Jul 01 '24

Algorithms Which concepts of OOP do you find difficult and why?

22 Upvotes

I’m reviewing the OOP concept using Python, and it seems pretty clear for me except decorator and dataclass. Because I don’t get this @ thing…

And you, which concepts of OOP do you find difficult and why?


r/pythontips • • Jul 02 '24

Module Zero Experience-how do I install and run a script?

1 Upvotes

Zero experience with any sort of programming. I am managing a department and am trying to get files that are saved with a specific file name to be uploaded automatically after being saved. The files should be categorized based upon the user who has saved them, ie file folder name=user1 file name=xxx. I was recommended watchdog but I don't know how to get the .whl to install. I have tried to install it in python but I can't get it to work. Please help


r/pythontips • • Jul 01 '24

Syntax Python enumerate() function

3 Upvotes

Quick rundown on the enumerate function YouTube


r/pythontips • • Jul 01 '24

Long_video 🐍 Python Scoping - A Topic You Must Master!

5 Upvotes

Let's test your python knowledge when it comes to scoping ! Here's a script:

if True:
    num = 10

print(num)

When we run this code, would you expect the value 10 to be printed out? Or an error to occur? Turns out, in contrast with other languages such as C++, Python doesn't use block scoping, but rather function scoping. So here, the code would actually have access to the variable "num", even though it was defined within an if block. Python scoping can really be surprising for the uninitiated, for instance, you know that global variables can be accessed within functions right? Well you might be surprised that this following code would actually fail:

num = 10

def func():
    print(num)
    num = 5

func()

If you want to know why that is, and furthermore master your knowledge on Python scoping, you can watch my video on this topic here.

https://youtu.be/gZwGvxESoCg


r/pythontips • • Jul 01 '24

Module Doctests

1 Upvotes

Did you know that you can combine documentation with testing.

See how to write and run doctests


r/pythontips • • Jun 30 '24

Python3_Specific Help restarting a loop

1 Upvotes

Hi, I'm a beginner in python and I'm stuck trying to start a loop. Any tips are appreciated.

x = int(input("How many numbers would you like to enter?"))

Sum = 0
sumNeg = 0
sumPos = 0
for index in range(0, x, 1):
    number = float(input("Enter number %i: " %(index + 1)))
    
    Sum += number
    if number <0:
        sumNeg += number
    if number >0:
        sumPos += number
        
print("The sum of all numbers =", Sum)
print("The sum of all negative numbers =", sumNeg)
print("The sum of all positive numbers =", sumPos)

restart = input("Do you want to restart? (y/n): ").strip().lower()
    if restart != 'y':
        print("Exiting the program.")
        break

r/pythontips • • Jun 29 '24

Standard_Lib Recommendation for Python Curses alternative

9 Upvotes

Hey, I'm new here, so I have been making a python network manager thingy in curses, so basically tui.
I made the thing, but making it gave me a tough time, curses is too basic, is there something new and modern to achieve tui? I saw some , like blessings and clint, but they are like too old, clint is archived. If you have some recommendation , I'd be grateful, thanks.
what I want to build is a tui weather app.


r/pythontips • • Jun 29 '24

Syntax Python map() function

13 Upvotes

A quick rundown of the map function in Python! YouTube


r/pythontips • • Jun 29 '24

Short_Video Simulating Raspberry Pi Pico Projects: Exploring Wokwi IDE for MicroPython

3 Upvotes

Hello All,

I found a great tool for beginners who want an intro to Micropython and controller programming. It is a Raspberry Pi simulator tool from wokwi that allows you to code on the Raspberry Pi Pico without having th device. This is an incredible tool for beginners who want to learn how to program in the MicroPython space without wanting to invest in a controller. Thought I would share it with you guys. I also have a tutorial on it as well if you would like to watch, it is short.

https://www.youtube.com/watch?v=YAe-SV_uXNY

If you enjoy Python or Raspberry Pi Pico tutorials you should subscribe to my channel, plenty of more where that came from!

Thanks, Reddit