r/learnpython • u/United_Pizza_6340 • 19h ago
how do i learn python(programming)?
.
r/learnpython • u/Joltik2007 • 1d ago
I'm combing two lists together into a dictionary, but when i print it also prints out the type of value(e.g float).
[-1.61803399 -0.61803399 1.61803399 0.61803399]
[[ 0.37174803 -0.60150096 0.60150096 -0.37174803]
[ 0.60150096 -0.37174803 -0.37174803 0.60150096]
[-0.37174803 -0.60150096 -0.60150096 -0.37174803]
[-0.60150096 -0.37174803 0.37174803 0.60150096]]
{np.float64(-1.6180339887498922): array([ 0.37174803, -0.60150096, 0.60150096, -0.37174803]), np.float64(-0.6180339887498947): array([ 0.60150096, -0.37174803, -0.37174803, 0.60150096]), np.float64(1.6180339887498942): array([-0.37174803, -0.60150096, -0.60150096, -0.37174803]), np.float64(0.6180339887498946): array([-0.60150096, -0.37174803, 0.37174803, 0.60150096])}
This is what I get as an output. Aside from the types being printed it's fine. The code I'm using to join the two together is
energy_levels = dict(zip(eigenvalues, eigenvectors))
where eigenvalues and eigenvectors are the two lists printed above and energy_levels is defined earlier on as empty dictionary.
r/learnpython • u/timepassr • 23h ago
so a little of context i have computer science as a subject in grade 12 , and in it i have to study python , sql , stack and python connectivity with sql . i have managed to study sql but im struggling with python all i know is print("hello world") , i dont know if this is the right place to post this but help will be really appreciated . also i cant give it much time sadly coz i have subjects like physics chem and maths hanging in my neck . max i can give is 45 mins a day and i have to do it in under a month .
these are all the topics i need to learn
if, elif, else) and loops (for, while, break, continue).math, random, and statistics.def).return statement) vs. void functions.global keyword.ZeroDivisionError, TypeError, ValueError, IndexError, KeyError, FileNotFoundError, IOError, etc.try, except, else, and finally clauses, along with raise and assert statements..txt), binary files (.dat), and CSV files (.csv).open(), close(), with statement, and file access modes (r, r+, w, w+, a, a+, rb, wb, ab, etc.).read(), readline(), readlines()), writing (write(), writelines()), and file pointer manipulation (seek(), tell()).pickle module (pickle.dump() and pickle.load()).csv module (csv.reader(), csv.writer(), writerow(), writerows()).push via append(), pop via pop(), peek/display, and underflow/overflow checks).mysql.connector.connect(), cursor(), execute(), parameterized queries (%s or .format()), commit(), fetchone(), fetchmany(), fetchall(), and rowcount.THANKS A LOT FOR READING
r/learnpython • u/WheetabixLicker6767 • 1d ago
hello, I am kinda new to python and I am not sure if someone already answered this in another post but how do you fully shut down the windows running python? Like not just clearing them but getting rid of the whole window
Right so to clarify- Yes I know that the "x" exists im not blind I meant how to close the window without any pop-ups (In the actual code itself)
r/learnpython • u/cheriieriot • 2d ago
same stuff on every venue site. name, date, price, ticket link. but each one hides it somewhere else, a table on one, cards on another, and a couple only fill in after the js runs so those go through playwright
so now theres a parser per site, and when a venue redesigns i find out because my list goes quiet
do people just live with one parser per layout or is there a way to describe the fields once
r/learnpython • u/Dragoran21 • 2d ago
I wish to alter a table/dataframe like this one:
| Type | Alpha | Type | Beta | Type | Gamma |
|---|---|---|---|---|---|
| A | 100 | A | 80 | A | 90 |
| B | 20 | B | 40 | B | 30 |
| C | 1 | C | 1 | C | 0 |
| X | 1 | Y | 2 | Z | 1 |
Into something looking like this one:
| Type | Alpha | Beta | Gamma |
|---|---|---|---|
| A | 100 | 80 | 90 |
| B | 20 | 20 | 30 |
| C | 1 | 1 | 0 |
| X | 1 | nan | nan |
| Y | nan | 2 | nan |
| Z | nan | nan | 1 |
To combine data based on shared values so it is easier to compare different types.
How could I do this with Python?
EDIT: I followed Likh-98's advice but I ran into an issue.
import pandas as pd
df0=pd.read_csv('Table of Test.txt', sep='\t')
df1=df0.iloc[:,0:2]
df2=df0.iloc[:,2:4]
df3=df0.iloc[:,4:] #works
df1.rename(columns={'Alpha':'Value'}, inplace=True)
df2.rename(columns={'Type.1':'Type','Beta':'Value'}, inplace=True)
df3.rename(columns={'Type.2':'Type','Gamma':'Value'}, inplace=True)
df1=df1.assign(Source=['Alpha','Alpha','Alpha','Alpha']) #They were unclear how to fill the new column
df2=df2.assign(Source=['Beta','Beta','Beta','Beta'])
df3=df3.assign(Source=['Gamma','Gamma','Gamma','Gamma'])
frames=[df1, df2, df3]
result=pd.concat(frames)
result.pivot(index='Type', columns='Sourge', values='Value')
#Here I got "ValueError: Index contains duplicate entries, cannot reshape", when result was:
Type Value Sourge
0 A 100 Alpha
1 B 20
2 C 1
3 X 1
0 A 80 Beta
1 B 40
2 C 1
3 Y 2
0 A 90 Gamma
1 B 30
2 C 0
3 Z 1
EDIT2: Here are a few ways to do it.
One:
import pandas as pd
df0=pd.read_csv('Table of Test.txt', sep='\t')
df1=df0.iloc[:,0:2]
df2=df0.iloc[:,2:4]
df3=df0.iloc[:,4:]
df2.rename(columns={'Type.1': 'Type'}, inplace=True)
df3.rename(columns={'Type.2': 'Type'}, inplace=True)
x=pd.concat([d.set_index('Type') for d in [df1, df2, df3]], axis=1)
print(x)
Two:
df = pd.read_csv('Table of Test.txt', sep='\t')
type_cols = df.columns.str.startswith('Type')
# Check type column names correctly positioned
assert all(value is not bool(i % 2) for i, value in enumerate(type_cols))
frames = [
df.iloc[:, [i, i+1]].set_index(df.columns[i])
for i in np.flatnonzero(type_cols)
]
df_new = pd.concat(frames, axis=1)
print(df_new)
There, solved!
PS: Is it just me, or are you also getting double text when you post to a code block?
r/learnpython • u/lailoken503 • 2d ago
Been at this for a while and can't seem to make sense of why a multi-conditioned while loop only triggers when one condition is met, but not the other, which generally happens sooner before the 2nd condition is met.
The results I get running the sample:import random
numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
randNum = int(random.randint(1, 10))
numMatch = False
maxNum = 9
incCount = 0
while numMatch == False or incCount <= maxNum:
if numList[incCount] == randNum:
numMatch = True
print(numList[incCount])
incCount += 1
print('Random number: ' + str(randNum) + '\n')
print('numMatch: ' + str(numMatch))
Y:\Users\lailoken\Documents\Python>python sample.py
1
2
3
4
5
6
7
8
9
10
Random number: 3
numMatch: True
The second condition triggers but not the Boolean, and I'm stumped as to why.
r/learnpython • u/One_Yellow_7849 • 1d ago
I’ve been learning how to code in python for a couple of months, and I know things like loops, conditionals, variables, functions, arrays and basic concepts of POO. I learned all those concepts reading books, watching YouTube videos and using Claude, but I’ve been trying to build automation scripts with no ia I feel like I still don’t know what I’m doing and when I ask Claude to make the script for me I don’t understand it completely. My question is: should I avoid using ia until I can build scripts or software by myself?
r/learnpython • u/MezzoScettico • 2d ago
An old habit from C days is to add print statements for debug and assign them different verbosity levels. I've been doing that in Python as well.
if verbosity > 2:
print("This level generates a lot of output, so use it sparingly")
I've been told that the logging facility is the Python way to do this, so I'm finally investigating it. What I'm seeing is that the levels are DEBUG, INFO, WARNING, ERROR which doesn't really fit what I want to happen. Everything I want to put under verbosity control is technically DEBUG or INFO.
So my question is: are there sublevels on the DEBUG or INFO logging? Or is there another approach for this sort of thing?
EDIT: Still reading. I think the answer might be a hierarchy of loggers and filters? Trying to figure out how that works now.
r/learnpython • u/PhilosopherNext1448 • 2d ago
In our software department we have a few dozen python libraries that different teams maintain, some open source, some closed source. I'm trying to centralize commonalities between them so that all pipelines run the same stages, that all pre-commit hooks are the same, and so on. I got most of it working, except that I don't have a good way to centralize configurations. For example I want all repos to use a common set of ruff linter rules, all documentation builds to use the same template and plugins, pin the most of the [dev] dependencies to the same versions..
Was wondering if anyone has experience with this :) I've been back and forth with Claude for quite a while, but I wasn't a fan of its ideas (using templates, copier, custom scripts, monorepo)
r/learnpython • u/Candid-Page1895 • 3d ago
Good morning,
I use conda environments with pandas for updating product information and data analysis.
I use Windows 11 and Fedora, but am more often using Windows.
I want to start creating and storing my own modules and packages for ease of use on my own machine for private use.
Is there a dedicated storage location for user created modules as there is for say Powershell 7?
I've asked chatgpt and searched google but a lot of the information is conflicting.
Are there dedicated locations and methods of retrieval depending on OS used?
r/learnpython • u/Mundane_Emu_3 • 3d ago
I've gone through multiple Python courses and understand the basic concepts like if-else, loops, lists, dictionaries, functions, etc.
However, when it comes to solving problems on my own, I struggle a lot. I can manage very basic questions like addition, subtraction, reversing a string, or checking for palindromes, but beyond that, I just can't seem to figure out the logic.
I understand the concepts and can follow someone else's solution, but when faced with a new problem, I have no idea where to start or how to break it down.
For those who have been through this, how did you develop your problem-solving skills? What kind of practice or approach helped you learn to think logically and solve problems independently?
I'd really appreciate any advice!
r/learnpython • u/MokpotheMighty • 2d ago
I used to dabble around with Python from time to time...
However every time I come back to it I seem to hit this brick wall before I even get to write a line of code.
Long story short, I want to do the tutorial you find here:
https://www.youtube.com/watch?v=8OMghdHP-zs
I just wanna get to work instead of spending hours and hours grappling with things not installing properly, as it is yet again doing to me right now. So either help me fix the errors I am getting or show me the easy alternative.
I'd rather not use VSCode because it's Microsoft and it seems almost impossible to disable the AI "copilot" thing, from what I read online, so I'd rather not if that's the case.
I used to use Anaconda to set up environments using older versions of python and pygame, however, setting up an environment with python 3.14 it throws this at me when I activate it:
C:\Users\Mokpo>if exist "C:\Windows\System32\msmpi.dll" (
echo "You seem to have a system wide installation of MSMPI. "
echo "Due to the way DLL loading works on windows, system wide installation "
echo "will probably overshadow the conda installation. Uninstalling "
echo "the system wide installation and forced deleting C:\Windows\System32\msmpi*.dll"
echo "will help, but may break other software using the system wide installation.")
C:\Users\Mokpo>if defined MSMPI_BIN (set "MSMPI_BIN_CONDA_BACKUP=" )
C:\Users\Mokpo>if defined MSMPI_INC (set "MSMPI_INC_CONDA_BACKUP=" )
C:\Users\Mokpo>if defined MSMPI_LIB64 (set "MSMPI_LIB64_CONDA_BACKUP=" )
C:\Users\Mokpo>if defined MSMPI_LIB32 (set "MSMPI_LIB32_CONDA_BACKUP=" )
C:\Users\Mokpo>set MSMPI_BIN=\Library\bin
C:\Users\Mokpo>set MSMPI_INC=\Library\include
C:\Users\Mokpo>set MSMPI_LIB64=\Library\lib
C:\Users\Mokpo>set MSMPI_LIB32=""
Okay so it's recommending me to delete a file on which other things may depend system-wide, because Anaconda cannot get the environment to isolate itself from it and use the "proper" version instead? Will that not risk me breaking my OS in some horrible way?
Anyway. After typing "spyder" I get an error popup window titled: "analysecrash.exe - Application Error" saying "The application was unable to start correctly (0xc0000142). Click OK to close the application." This happens again once after I click okay.
However, Spyder does in fact launch, except it doesn't do anything. As in, I can make a folder into a project, theres a "temp.py" file open in the editor, I write print('hello world'); and click "run" but it doesnt do anything.
When I was trying this before, it did say something somewhere about the console not working because "the kernel" isnt loaded or whatever?
Anyway, this is extremely, extremely frustrating, especially as so many "beginners tutorials" seem hell-bent on skipping over any of this preliminary setup stuff like it's hot lava, while 99% of the actual beginners presumably die before they get to even try out much code, you know, like it's hot lava they cant skip over yet. I've written some programs in python before so I'm not even a beginner it's just this stuff is so obscure and it always manages to "snipe" me somehow whenever I try something new. So more generally, if there's a way to learn to deal with these kinds of problems, finding out more about how it works, etc... How do I become the person that answers these questions rather than asks them?
r/learnpython • u/SuperExperience6689 • 3d ago
Hi everyone, I'm on Python 3.12 (Windows) and building a small CLI script to fetch search results from a REST API.
Earlier I tried using resp.raise_for_status() + urllib3.Retry, but ran into two things that tripped me up:
200 OK even when rate-limited (status: 1029) or on upstream failures, putting the actual error code inside the JSON body and retry hints in response headers (Retry-After, X-SerpBase-Retryable).format="markdown"), the response comes back as text/markdown with no JSON wrapper, so blindly calling resp.json() crashed with JSONDecodeError.Here is the wrapper I wrote to handle both cases (using requests.Session and reading the key from an environment variable):
import os
import time
import requests
API_KEY = os.environ["SERPBASE_API_KEY"]
BASE_URL = "https://api.serpbase.dev"
session = requests.Session()
session.headers.update({
"X-API-Key": API_KEY,
"Content-Type": "application/json",
})
def search_google(query: str, as_markdown: bool = False, retries: int = 2):
payload = {"q": query, "gl": "us", "hl": "en"}
if as_markdown:
payload["format"] = "markdown"
for attempt in range(retries + 1):
resp = session.post(f"{BASE_URL}/google/search", json=payload, timeout=60)
resp.raise_for_status()
content_type = resp.headers.get("Content-Type", "")
if "text/markdown" in content_type:
return resp.text
data = resp.json()
status = data.get("status")
if status == 0:
return data.get("organic", [])
if status == 1029 and attempt < retries:
wait = int(resp.headers.get("Retry-After", "2"))
time.sleep(wait)
continue
retryable = resp.headers.get("X-SerpBase-Retryable") == "true"
if retryable and attempt < retries:
time.sleep(2 ** attempt)
continue
raise RuntimeError(f"API error status={status}, retryable={retryable}")
It works now, but I have three specific questions to make this more Pythonic:
urllib3.Retry (via HTTPAdapter) only retries on HTTP-level status codes like 429/503, is a manual for attempt loop the normal way to handle HTTP-200 JSON error envelopes, or is a library like tenacity cleaner?int(resp.headers.get("Retry-After", "2")) risky if a server ever sends an HTTP-date string instead of integer seconds?session into search_google() as a parameter instead of keeping it at module level, especially if I want to write unit tests later?Thanks in advance for any pointers!
r/learnpython • u/Deep-Ostrich9298 • 2d ago
I put together a few Python scripts that pull two CSV exports and merge them with pandas.
One of the exports renamed a column and the merge started throwing a KeyError. I still don't really get half of what the script does. Nobody here knows Python.
I want to know these scripts well enough to fix them myself. What helped you go from pasting code to understanding what your own code does?
r/learnpython • u/silverknife42 • 3d ago
How do you update Python on macOS? I looked it up and from what I can tell, there is no simple command you can enter into the terminal to update it, and you have to instead go to the website https://www.python.org/downloads/ and download and install it manually to update which is inconvenient. There's also the question of removing the old versions you have no intention of using anymore.
I am aware of Homebrew and I do have it for other things I've installed, but I want to try to only use it to download things to my MacBook that I otherwise couldn't. Python can easily be downloaded for mac separately and I want to keep it that way if possible. Is there no update command for the mac terminal to simply update Python?
r/learnpython • u/TreacleFlaky2283 • 3d ago
leetcode 2926
```py
class Solution:
def maxBalancedSubsequenceSum(self, nums: List[int]) -> int:
t = [nums[i] for i in range(len(nums))]
max_val = 0
for i in range(len(nums)):
for k in range(i):
if nums[k] - k <= nums[i] - i:
t[i] = max(t[i], t[k] + nums[i])
max_val = max(max_val, t[i])
return max_val if max(nums) > 0 else max(nums)
```
time limit exceeded how to fix? same error for top down as well
r/learnpython • u/playsthebongcloud • 4d ago
Sorry this isn't super specific to python, but I can't find anything online. I want to specify to sympy that I want the output of its simplification to be in the form of a rational function. (A rational function is one where it equals one polynomial divided by another.)
After the function gets complex enough, it does start to format it as a rational function (but not exactly, it does factoring where it can). I want the output to be in the format of
(x0 * (a^n0*b^m0) + x1 * (a^n1*b^m1) + ...) / (X0 * (a^N0*b^M0) + X1 * (a^N1*b^M0) + ...)
where the powers and coefficients are integers.
It's not super relevant, but here is my code:
def f(a, b):
return 1 - a/b
a = s.Symbol('a', real=True)
eq_1 = s.simplify(f(a, s.Symbol('b', real=True)))
eq_2 = s.simplify(f(eq_1, a))
i = 3
while True:
old_eq = eq_2
eq_2 = s.simplify(f(eq_2, eq_1))
eq_1 = old_eq
print(f'f({i}) = {s.latex(eq_2)}\n')
i += 1
r/learnpython • u/King_Trance • 3d ago
All those memes with deleting System32 but what if I want to be nice to Linux users? On a fresh install of most Linux distributions, the C:/Windows/System32 file path wouldn't exist, but a lot of Linux users have wine, so it might. Can I write a script where if the user is on windows it deletes System32 but if they're on Linux it just like opens Mario Kart or something? Is there a method in the os module or any other one to get the user's operating system type?
r/learnpython • u/Better-Prior5988 • 4d ago
Hello, I’m starting to learn how to use python. I do scientific research in my job and right now what I’m most interested in learning is how to use python to analyze data, perform statistical tests, data plotting and visualization, and later on maybe creating simple tools that might be helpful to automate some steps in data analysis. As I’m just starting I need some advice on good ways and resources to use for beginners to eventually be able to do these things. Perhaps some free courses or good youtube channels. Thank you 😊
r/learnpython • u/DeWittySmookie • 4d ago
I'm doing a Monte Carlo analysis on playing poker using different strategies and need a way to return the number of games won by each bot over some number of simulated games. I looked on the GitHub and didn't have much luck.
r/learnpython • u/Vast_Battle5414 • 5d ago
Learning Python syntax is one thing, but solving a problem from scratch feels completely different.
What small projects or daily exercises would you recommend to develop real programming skills without constantly following tutorials?
r/learnpython • u/GoldEquivalent3597 • 4d ago
Ciao a tutti, sto imparando a usare python, solitamente eseguo il codice dentro spider ma vorrei proprio creare delle app eseguibili dal desktop (ho windows)
r/learnpython • u/First-Ad6991 • 4d ago
def main(ips, users, passwords, ThreadNumber):
queue = queue.Queue(maxsize=20000)
for t in range(ThreadNumber):
try:
t = Apophis(queue)
t.daemon = True
t.start()
except Exception as e:
break
r/learnpython • u/PerformanceNo4750 • 5d ago
Hi guys. I'm a university student, my profession is Data Science. I want to improve my Python. I'm a beginner. How do you recommend learning it? I have made a few failed tries before and I still couldn't find the right way. Youtube tutorials do not help me :(Hi guys. I'm a university student, my profession is Data Science. I want to improve my Python. I'm a beginner. How do you recommend learning it? I have made a few failed tries before and I still couldn't find the right way. Youtube tutorials do not help me :(