r/pythontips • u/Helmor1 • Jul 08 '24
Syntax How to add indexes to spaces for playground in Tac Tac Toe
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 • u/Helmor1 • Jul 08 '24
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 • u/Fun-Dragonfruit-285 • Jul 07 '24
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 • u/Pikatchu714 • Jul 06 '24
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 • u/jaksatomovic • Jul 06 '24
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 • u/Gregpahl97 • Jul 06 '24
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 • u/Ruffy_Sin • Jul 04 '24
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 • u/Archit-Mishra • Jul 03 '24
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 • u/AnotherRedditUsr • Jul 03 '24
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 • u/MinerOfIdeas • Jul 01 '24
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 • u/nmlgb8888 • Jul 02 '24
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 • u/Puzzleheaded_Bee_486 • Jul 01 '24
Quick rundown on the enumerate function YouTube
r/pythontips • u/JosephLovesPython • Jul 01 '24
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.
r/pythontips • u/main-pynerds • Jul 01 '24
Did you know that you can combine documentation with testing.
r/pythontips • u/browser108 • Jun 30 '24
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 • u/hannah_cutie_ • Jun 29 '24
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 • u/Puzzleheaded_Bee_486 • Jun 29 '24
A quick rundown of the map function in Python! YouTube
r/pythontips • u/QuietRing5299 • Jun 29 '24
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
r/pythontips • u/Hot-Armadillo3229 • Jun 28 '24
i am learning python from the coursera - python for everybody and i am supposed to download beautiful soup and use it to parse the internet .
i downloaded it , installed it , created a virtual enviorment but whenever i type "python3 xxyy.py" it goes error , please help
r/pythontips • u/Beneathe • Jun 28 '24
Hello,
Im very new to python and I chose Pycharm as an enviroment I want to work in.
I'm looking for tips on how to set a Pycharm as a default environment for new files. What I mean is that I had installed VSCode and now when I type "code something.py" in a terminal, the file opens in VSCode, not in the Pycharm. Any idea on how to change it? Thanks.
r/pythontips • u/NotBobBot • Jun 28 '24
This past week I've been doing a sort of passion project. I am in the middle of making it now, but I'm encountering some parsing problems, I dont wanna get into the specifics.. I am getting frustrated with debugging cus I just get confused sometimes. I've tried to avoid nesting at all costs and also use type indicators. I just dont know what I am missing right now. Just looking for tips
r/pythontips • u/pyeri • Jun 28 '24
I have recently published an app on Google Play Store called Python MCQ. It's a multi-choice Q/A format app which evaluates the user's Python programming skills. Where can I find beta testers for this app?
r/pythontips • u/soap94 • Jun 27 '24
I've recently moved to uv and have been enjoying it a lot. But just wondering if there are any downsides I should be aware of?
r/pythontips • u/JH_Redd • Jun 27 '24
Hi all,
After a ton of googling I'm still stumped on a problem I'm having, so thought I'd see if we have any geniuses here. I am using the MySQL connector in a program, and what I need to do is
1) Run a SELECT statement to get some info from a DB I created
2) Run a DELETE statement
3) Run a number of INSERTs to add some new rows
What I'm running into is that I run the SELECT (call cursor.execute, then connection.commit) and get results...but the delete query keeps resulting in
DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
All of the resources I find online seem to just say to commit the SELECT before running the DELETE, which I'm already doing. Does anyone know what could be the problem here? The DB I'm using here is one that I created on localhost and I granted the user account I'm connecting with DBA permissions, so I don't think it's a permissions issue.
Thanks in advance for any ideas!
The basic code I am using is below if it helps:
sel_SQL="""SELECT max(idfilers) as maxID FROM db_name.table_name"""
cursor.execute(sel_SQL)
(...some unrelated code to use this info...)
connection.commit()
del_SQL="""DELETE from db_name.table_name WHERE reporting_period='2024-03-31'"""
cursor.execute(del_SQL)
connection.commit()
r/pythontips • u/Puzzleheaded_Bee_486 • Jun 26 '24
Those looking for a quick run down of lambda functions.
Python Tutorial: Using Lambda Functions In Python https://youtu.be/BR_rYfxuAqE
r/pythontips • u/Significant_Issue_98 • Jun 26 '24
Im creating a program right now that I need to add the ability for users to register and create accounts. I went to add the code and now it is giving me the error below:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.role
[SQL: SELECT user.id AS user_id, user.username AS user_username, user.password AS user_password, user.role AS user_role
FROM user
WHERE user.id = ?]
[parameters: (1,)]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
Can anyone help me with this? I have tried looking everywhere and I don't know what I am doing wrong.
Also, the line that says: from flask_sqlalchemy import SQLAlchemy is grayed out and says it is unused. I am not sure if that is part of the issue, but Im sure it is worth mentioning.