/r/learnpython
Subreddit for posting questions and asking for general advice about all topics related to learning python.
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.
Wiki and FAQ: /r/learnpython/w/index
/r/learnpython
Hello! I'm very much new to Python, I want to eventually create a sports simulation game. Step 1 would probably be setting up an SQLite database which I've done already! Step 2 would probably to try to make a table appear in a terminal and make sure everything equals to say, 140 for simplicity. Is it possible to make things equal to a specific amount without just writing the number? I don't just want to write "28, 28, 28, 28, 28" for every player, especially if I want to have more than 5 players!
Hello, the project I am trying get black to run on our precommit hook. The command works in terminal but doesn't work in the subprocess. I tried using python_path = sys.executable but the python_path is /usr/local/bin/python3 whereas my python environment home/dev/opensource/.direnv/python-3.9.20/bin/python. I also tried passing os.environ.copy() to no avail. Any ideas?
def run_black() -> None:
"""Runs black formatter."""
cmd = "git diff --cached --name-only --diff-filter=d | grep -E '\\.py$' | xargs black"
subprocess.run(cmd, shell=True, check=True, text=True)
I’m a data engineer, but have never coded. I’m also enrolled in a masters degree program on data science. I’d like to have a crash course in python during my Xmas school break. I have lots of available time and I mostly learn by doing. I’m also really old and became a data engineer through promotions and not by degree. Any other questions, just let me know. I’m in the US.
"I'm having trouble executing a command in Python. Can someone help me? I'm trying to automate web scraping, but when I run the .perform()
command, I get the errors shown in the image. I've imported all the necessary libraries. Can anyone help me?"
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import random
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def config_inicial(dados_element, driver):
element = driver.find_element('xpath', dados_element)
html_content = element.get_attribute('outerHTML')
soup = BeautifulSoup(html_content, 'html.parser')
return soup
def action(driver, xpath_vaga):
elemento = driver.find_element(By.XPATH, xpath_vaga)
action = ActionChains(driver)
action.click(elemento).perform()
driver.current_url
aleatory_time = round(random.uniform(4, 6), 2)
time.sleep(aleatory_time)
driver = webdriver.Chrome()
driver.get('https://app.vidatrilegal.com.br/resultados-desktop')
time.sleep(10)
wait = WebDriverWait(driver, 10)
elemento = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/app-root/ion-app/ion-router-outlet/page-resultados-desktop/ion-content/div/resultado-do-sorteio/div/buscar-resultados-por-data/ion-grid/ion-row/ion-col[2]/imprimir-sorteio/ion-grid/ion-row/ion-col/ion-row/ion-col[4]/ion-button')))
action = ActionChains(driver)
action.click(elemento)
action.perform()
OUTPUT
{
"name": "JavascriptException",
"message": "Message: javascript error: {\"status\":60,\"value\":\"[object HTMLElement] has no size and location\"}
(Session info: chrome=131.0.6778.86)
Stacktrace:
\tGetHandleVerifier [0x00007FF70CAB6CB5+28821]
\t(No symbol) [0x00007FF70CA23840]
\t(No symbol) [0x00007FF70C8C578A]
\t(No symbol) [0x00007FF70C8CC2ED]
\t(No symbol) [0x00007FF70C8CEFCC]
\t(No symbol) [0x00007FF70C8CF09F]
\t(No symbol) [0x00007FF70C920283]
\t(No symbol) [0x00007FF70C91F516]
\t(No symbol) [0x00007FF70C96A2B9]
\t(No symbol) [0x00007FF70C93F2FA]
\t(No symbol) [0x00007FF70C95F412]
\t(No symbol) [0x00007FF70C93F0A3]
\t(No symbol) [0x00007FF70C90A778]
\t(No symbol) [0x00007FF70C90B8E1]
\tGetHandleVerifier [0x00007FF70CDEFCAD+3408013]
\tGetHandleVerifier [0x00007FF70CE0741F+3504127]
\tGetHandleVerifier [0x00007FF70CDFB5FD+3455453]
\tGetHandleVerifier [0x00007FF70CB7BDBB+835995]
\t(No symbol) [0x00007FF70CA2EB5F]
\t(No symbol) [0x00007FF70CA2A814]
\t(No symbol) [0x00007FF70CA2A9AD]
\t(No symbol) [0x00007FF70CA1A199]
\tBaseThreadInitThunk [0x00007FFF7BE97374+20]
\tRtlUserThreadStart [0x00007FFF7C11CC91+33]
",
"stack": "---------------------------------------------------------------------------
JavascriptException Traceback (most recent call last)
Cell In[10], line 8
6 actions = ActionChains(driver)
7 actions.click(elemento)
----> 8 actions.perform()
File c:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\selenium\\webdriver\\common\\action_chains.py:94, in ActionChains.perform(self)
92 def perform(self) -> None:
93 \"\"\"Performs all stored actions.\"\"\"
---> 94 self.w3c_actions.perform()
File c:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\selenium\\webdriver\\common\\actions\\action_builder.py:96, in ActionBuilder.perform(self)
94 enc[\"actions\"].append(encoded)
95 device.actions = []
---> 96 self.driver.execute(Command.W3C_ACTIONS, enc)
File c:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\selenium\\webdriver\\remote\\webdriver.py:384, in WebDriver.execute(self, driver_command, params)
382 response = self.command_executor.execute(driver_command, params)
383 if response:
--> 384 self.error_handler.check_response(response)
385 response[\"value\"] = self._unwrap_value(response.get(\"value\", None))
386 return response
File c:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python313\\Lib\\site-packages\\selenium\\webdriver\\remote\\errorhandler.py:232, in ErrorHandler.check_response(self, response)
230 alert_text = value[\"alert\"].get(\"text\")
231 raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here
--> 232 raise exception_class(message, screen, stacktrace)
JavascriptException: Message: javascript error: {\"status\":60,\"value\":\"[object HTMLElement] has no size and location\"}
(Session info: chrome=131.0.6778.86)
Stacktrace:
\tGetHandleVerifier [0x00007FF70CAB6CB5+28821]
\t(No symbol) [0x00007FF70CA23840]
\t(No symbol) [0x00007FF70C8C578A]
\t(No symbol) [0x00007FF70C8CC2ED]
\t(No symbol) [0x00007FF70C8CEFCC]
\t(No symbol) [0x00007FF70C8CF09F]
\t(No symbol) [0x00007FF70C920283]
\t(No symbol) [0x00007FF70C91F516]
\t(No symbol) [0x00007FF70C96A2B9]
\t(No symbol) [0x00007FF70C93F2FA]
\t(No symbol) [0x00007FF70C95F412]
\t(No symbol) [0x00007FF70C93F0A3]
\t(No symbol) [0x00007FF70C90A778]
\t(No symbol) [0x00007FF70C90B8E1]
\tGetHandleVerifier [0x00007FF70CDEFCAD+3408013]
\tGetHandleVerifier [0x00007FF70CE0741F+3504127]
\tGetHandleVerifier [0x00007FF70CDFB5FD+3455453]
\tGetHandleVerifier [0x00007FF70CB7BDBB+835995]
\t(No symbol) [0x00007FF70CA2EB5F]
\t(No symbol) [0x00007FF70CA2A814]
\t(No symbol) [0x00007FF70CA2A9AD]
\t(No symbol) [0x00007FF70CA1A199]
\tBaseThreadInitThunk [0x00007FFF7BE97374+20]
\tRtlUserThreadStart [0x00007FFF7C11CC91+33]
"
}
Hey folks,
I recently faced a programming challenge while brushing up on classical python.
What is given: the grid with leaves (integers) and wind string (only U, D, L, R characters). Wind can move the leaves 1 cell in any direction one step at a time.
Task: how can one calculate total leaves remaining after wind is gone (i.e. we processed all character in wind string)?
How can I make this code more efficient (computationally and memory wise), especially for large grids and large wind strings?
def compute(leaves: List[List[int]], wind: str) -> int:
NUM_ROWS = len(leaves)
NUM_COLS = len(leaves[0])
top = 0
bottom = NUM_ROWS - 1
left = 0
right = NUM_COLS - 1
row_offset = 0
col_offset = 0
for dir in wind:
if dir == 'U':
top += 1
row_offset -= 1
elif dir == 'D':
bottom -= 1
row_offset += 1
if dir == 'L':
left += 1
col_offset -= 1
if dir == 'R':
right -= 1
col_offset += 1
top = max(top, 0)
bottom = min(bottom, NUM_ROWS - 1)
left = max(left, 0)
right = min(right, NUM_COLS - 1)
if top > bottom or left > right:
print("EARLY EXIT")
return 0
print("L, R, T, B: ", (left, right, top, bottom))
total_leaves = 0
for row in range(NUM_ROWS):
for col in range(NUM_COLS):
new_col = col + col_offset
new_row = row + row_offset
if 0 <= new_col < NUM_COLS and 0 <= new_row < NUM_ROWS:
total_leaves += leaves[row][col]
return total_leaves
I need help!
I already installed mysqlclient, but whenever I try to run python makemigrations I get this error:
(I had just updated my MariaDB and I don't know if I'm facing this problem because of it or not.)
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
Python 3.11 or higher please help thanks. No threading
# Welcome message
print ("Welcome to the YouTube Channel Name Generator:")
# Ask the user to put their nickname
nick_name = input ("What is your nickname?\n")
# Ask for their YT channel's topic
topic = input ("What is your channel about?\n")
# The result of YT channel name suggestion
print ("You could name your channel (" + topic + " with " + nick_name + ")")
Hello. I am encountering an issue. When I put the choices.py in a different folder with main-DESKTOP-V6PA6E6.py
(main game file), I encounter this issue:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Default.DESKTOP-V6PA6E6\AppData\Local\Programs\Python\Python313\Lib\tkinter\__init__.py", line 2068, in __call__
return self.func(*args)
~~~~~~~~~^^^^^^^
File "C:\Users\Default.DESKTOP-V6PA6E6\OneDrive - Salesian School and Xavier CET\Comp Sci\NEA project\tutorial3-code\choices\choices.py", line 91, in open_py_file
spec.loader.exec_module(module)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 1022, in exec_module
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "C:\Users\Default.DESKTOP-V6PA6E6\OneDrive - Salesian School and Xavier CET\Comp Sci\NEA project\tutorial3-code\main-DESKTOP-V6PA6E6.py", line 20, in <module>
GRASS = scale_image(pygame.image.load("imgs/grass.jpg"), 2.5)
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
FileNotFoundError: No file 'imgs/grass.jpg' found in working directory 'C:\Users\Default.DESKTOP-V6PA6E6\OneDrive - Salesian School and Xavier CET\Comp Sci\NEA project\tutorial3-code\choices'.
However, when I put both py in the same directory, the game launches successfully. What have I done wrong? Thanks
my code for launching the main-DESKTOP-V6PA6E6.py
:
def open_py_file():
root.destroy()
path1 = r"C:\Users\Default.DESKTOP-V6PA6E6\OneDrive - Salesian School and Xavier CET\Comp Sci\NEA project\tutorial3-code\main-DESKTOP-V6PA6E6.py"
# Read and execute the file
#using a modular approach
spec = importlib.util.spec_from_file_location("your_script", path1)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
I am trying to finish a project to make a small text based game but the elif break when you reach the exit room wont work and keeps looping as if it is another room, any thoughts to fix it?
#create welcome message
print('Welcome to the Fire Temple')
print('Explore rooms to find the exit.')
print('Take too long and the Guardian will crush you!')
#create rooms
rooms = {
'start room' : { 'east' : 'side room' , 'west' : 'storage room' , 'north' : 'temple hall' },
'side room' : { 'west' : 'start room' , 'north' : 'treasure room' },
'storage room' : { 'east' : 'start room' },
'temple hall' : { 'north' : 'prayer room' , 'south' : 'start room'},
'treasure room' : { 'south' : 'side room' },
'prayer room' : { 'south' : 'treasure room' , 'east' : 'exit' },
'exit' : {'west' : 'prayer room'}
}
# starting the game
current = 'start room'
print('Find the exit from the Temple. Good luck!')
print('Move Commands: go South, go North, go East, go West, exit')
# allow for input
# if ' go direction' => 'direction'
while True:
print('current room:' , current, rooms[current])
move = input(' move: ')
if move in rooms[current]:
current = rooms[current][move]
else:
print('invalid move')
continue
else if : move = rooms['exit']
break
#if 'exit' => break
print('You escaped!')
I’ve taken all the classes at my school that teach python, where do I go from there?
So I have been automating a few reports using python. To keep things simple I created a library for the team to shorten code. One of them is a library to run sql queries.
Basically using cx_oracxle I create a class to connect to our database, preset the connection info into an environmental variable as well as some methods that work best for our team.
Thus running a query is pretty simple. Pseudo code below:
from team_library import OracleDatabase
conn = OracleDatabase()
conn.run_query(Select * From Table)
conn.close
The issue now is that sometimes multiple connections maybe running simultaneously.
I may have a script which makes a database connection. But this script also calls a function from another script which makes another database connection. So in that moment I’d have two database connections active.
Is there a way to set up the OracleDatbase such that if a new instance is being created but one already exists, it just references that one?
Hello all,
Can anyone recommend solid self paced Python training? Appreciate the assistance.
Hello,
I would like to make a script that would ping X. and if X stop pinging for more than 30 minutes it would SSH on ip Y and do a re-initialize command.
Is python the best language to use for this type of commands. I was think about a while loop ?
.
import speech_recognition as sr
import random
r = sr.Recognizer()
randomList = ["one", "two", "three","four", "five"]
randomNumber = random.choice(randomList)
guessLoop = True
while guessLoop == True:
with sr.Microphone() as source:
print("Try to guess the random number between 1 and 5")
##print(randomNumber)
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
audioText = r.recognize_google(audio)
audioText = audioText.lower()
try:
print("You guessed: " + audioText)
if audioText == randomNumber:
print("Correct!")
guessLoop = False
else:
print("Try again!")
except:
exit()
I'm a complete newbie so it's probably something stupid simple. I'm just unsure what to really do now.
Errors:
Traceback (most recent call last):
File "d:\Test.py", line 17, in <module>
audioText = r.recognize_google(audio)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Bill\AppData\Local\Programs\Python\Python312\Lib\site-packages\speech_recognition\recognizers\google.py", line 263, in recognize_legacy
return output_parser.parse(response_text)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Bill\AppData\Local\Programs\Python\Python312\Lib\site-packages\speech_recognition\recognizers\google.py", line 134, in parse
actual_result = self.convert_to_result(response_text)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Bill\AppData\Local\Programs\Python\Python312\Lib\site-packages\speech_recognition\recognizers\google.py", line 183, in convert_to_result
raise UnknownValueError()
speech_recognition.exceptions.UnknownValueError
when I replace active = False
with break
, it just works and I am curious why.
Im thinking that with break
the program immediately exits the while loop. While active = False
finishes the loop somehow? but then that just doesn't make any sense. shouldn't both end the loop immediately because I'm turning it off or breaking out of it?
the error I get when it says active = False is:
File "G:\CODING THE INTERNET\projects\python_crash_course_for_dummie.py", line 961, in <module>
age = int(message)
^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'quit'
this is my code:
question = "how old are you? "
active = True
while active:
message = input(question)
if message == 'quit':
active = False
age = int(message)
if age <= 3: print ("its free to enter")
elif age <= 12: print ("its $10 dollars")
elif age >= 13: print ('its $15 dollars')
list1 = [1, 3] list2 = [2, 4]
result = sum(a * b for a, b in zip(list1, list2))
hi, i have installed python and pygame but i cant import it, it keep give to me this error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import pygame
ModuleNotFoundError: No module named 'pygame'
what i have to do?
Hey everyone o/
I got 2 lists of integers
a = [5, 2, 4]
b = [3, 2, 3]
how do i subtract each matching element of a list eg.:
5-3
2-2
4-3
genCharacter.getHealth()
genCharacter.setHealth()
NameError: name 'genCharacter' is not defined
Hi all.
I have looked through the documentation but I cannot find a working solution to my problem. In short, I really like the presentation of the plotly treemap, but I want to disable the option that someone can click down into the lowest levels (just doesn't look nice). Is there a work around to this?
Thanks
I'm at week 0, first video lol , a few minutes in & I'm already lost I understand a few concepts like variables, functions, arguments, strings (I think i do). But I'm stuck at what return values and side effects are. I utilized their notes ,but I'm as confused as before.. I used YouTube and google ("python in plain English" or " explain side effects like I'm 5" ) to understand the concepts, still lost.
I started playing a python game for kids but it contains none of the concepts being taught in the harvard course.
For example it may have been more pleasant to be able to typehint each of these left hand sides using the right hand side
list[str]
-> [str]
tuple[int, str]
-> (int, str)
dict[str, int]
-> { str: int }
list[tuple[bool, str]]
-> [(bool, str)]
set[str]
-> { str }
Why do Python typehints use the left hand style rather than the right hand style? Especially for tuples, I wonder why (bool, str)
isn't a valid type.
https://i.imgur.com/fs8dvrD.png
from bs4 import BeautifulSoup
import requests
url = "https://real-debrid.com/downloader"
debrid_link = "https://real-debrid.com/d/HM3XHJIOGAOEUC5C" # Wall-E (2008)
raw_html = requests.post(url, data=debrid_link)
soup = BeautifulSoup(raw_html.text, 'html.parser')
link_generated = soup.find('div', class_='link-generated')
if link_generated:
print("success: link generated")
print(link_generated.text)
else:
print("error")
I have been coding for quite a while (2-3yrs) and use to mostly just let it go but I need to know how these things work. Also what was the need for this that could not possibly be done without decorator.
p.s. I did try chatGPT I did not understand
Hi,
I'm using PyAutoGUI to automate typing on my AZERTY keyboard, but I’ve run into a strange issue. When I try to type an underscore (_
), the script writes a 8
instead. Similarly, for other special characters like (
or )
, incorrect outputs are written (e.g., 5
or °
).
Manually typing works perfectly fine on my keyboard, so I suspect the issue is related to PyAutoGUI assuming a QWERTY layout. Has anyone experienced this before or found a way to fix it?
Here’s a simple example of my code:
import pyautogui
pyautogui.write('_') # This types '8' instead of '_'
How can I get PyAutoGUI to respect my AZERTY keyboard layout?
I think I've searched across all of the web but can't seem to find this specific hook. I've tried using a .sh script with poetry and running pre-commit using it but its a bit ugly to store this sh script in project source
I need to learn python, but I don't have anyone to help and I am a deeply undisciplined person to learn alone, so I keep failing to log on to my computer and practice or keep learning on my own. Has anyone else been in this situation? If so l, how did you overcome it?
Im going to college for this little IT certificate and i've been doing it since August and about halfway I stopped understanding what was going on in the class. It's really demotivating because The videos are mainly code alongs and I haven't learned a thing. Im a complete newbie and I barely even understand what words do what. learning how to program has stopped being fun and started feeling more like a chore. I can't build a single thingy from scratch because all I was shown was what to type and not how to figure out what to type. Learning was a ton of fun when I first started but now im realizing that if they keep just handing me the answers im never gonna learn how to Actually code. The Professor gives us the base for the program but after that were supposed to figure out the rest and I don't know how to come up with the rest.