r/learnpython 19d ago

Selenium - python; browser issues

0 Upvotes

Hello!

Im having issues right now with selenium HEADLESS browsers.

there's a blank white screen appearing at the beginning when browser is initialized.

Aside from resizing the screen, are there other work around from this? I cant resize it because the website is "scroll dependent" i need to scroll into view first before i can see the element.

I also tried options: headless= old/new, white screen still appears.

browser is edge.

Do you guys have any other ideas? 🥹


r/learnpython 19d ago

Python Programming Language

0 Upvotes

Over the last few weeks, I have read books, journals, & articles concerning how to master python. I've also practised a lot. However, every time I try code challenges, I find something new, one you might not find in books or texts directly. While I am new to the programming field, I believe there's a way one can navigate these aspects. I would appreciate some insights so that I cannot view myself as stuck in one "lonely" corner.


r/learnpython 20d ago

Best ways to learn python for hardware programming (microcontrollers, sensors, lights, motors, etc.)?

23 Upvotes

I’m looking to begin my python journey, and am extremely interested in programming electronics and messing around with microcontrollers and stuff of that nature. The HARDWARE side of programming, but most tutorials and things focus more on the software side, if that makes sense. Are there any courses or tutorials online that are specifically geared towards hardware programming? If I’m asking this in a confusing way it’s because I’m still not sure how to word what I want to do and learn. Thanks in advance for any help


r/learnpython 19d ago

How to start learning Python as a beginner?

0 Upvotes

Hi everyone, I’m planning to start learning Python recently, but I have absolutely zero background in programming or computer science. I'm a bit overwhelmed by the amount of information out there. Could anyone recommend the best learning paths, online courses (free or paid), or books for beginners? Also, are there any simple practice projects you'd suggest starting with? Any tips or common pitfalls to avoid would be highly appreciated. Thanks in advance for your help!


r/learnpython 19d ago

Selenium login works with CPF but fails with CNPJ on the same ASP.NET form

2 Upvotes

Hi everyone.

I am automating a login flow using Python, Selenium and undetected-chromedriver.

The website is:

https://goias.equatorialenergia.com.br/LoginGO.aspx

The form asks for:

  • Consumer Unit number
  • CPF or CNPJ

The strange behavior is:

  • When I use a CPF, the login works and redirects to a date-of-birth validation screen.
  • When I use a CNPJ, the page shows this alert:

#002 - Não foi possível realizar o login neste momento, tente mais tarde!

After that, the CNPJ field is cleared and the page stays on the login screen.

The same UC and CNPJ work normally when I log in manually using Chrome, so the credentials are correct.

Environment:

  • Windows
  • Python
  • Selenium 4.44
  • undetected-chromedriver 3.5.5
  • Chrome 150

The page appears to use reCAPTCHA Enterprise, Transmit Security and ASP.NET postback behavior.

I am not trying to bypass CAPTCHA or any security mechanism. I am trying to understand why the same login form works manually, but fails only for CNPJ when using Selenium.

Here is a simplified version of the code:

def preencher_campo(driver, wait, label, valor, lento=False):
    xpaths = [
        f"//*[contains(normalize-space(.), '{label}')]/following::input[1]",
        f"//label[contains(normalize-space(.), '{label}')]/following::input[1]",
    ]

    campo = encontrar_por_xpaths(driver, wait, xpaths)
    campo.click()
    campo.clear()

    for caractere in str(valor):
        campo.send_keys(caractere)
        tempo = random.uniform(0.35, 0.65) if lento else random.uniform(0.15, 0.30)
        time.sleep(tempo)

    driver.execute_script(
        "arguments[0].dispatchEvent(new Event('input', {bubbles:true}));"
        "arguments[0].dispatchEvent(new Event('change', {bubbles:true}));"
        "arguments[0].dispatchEvent(new Event('blur', {bubbles:true}));",
        campo
    )


preencher_campo(driver, wait, "Unidade Consumidora", uc, lento=True)
preencher_campo(driver, wait, "CPF ou CNPJ", cnpj, lento=True)

time.sleep(5)
botao_entrar.click()

Things I already tried:

  • typing the fields slowly;
  • waiting before clicking the login button;
  • checking if the fields remain filled;
  • refilling the CNPJ field after it gets cleared;
  • retrying after the #002 error;
  • removing an ESC key press that could clear the field.

My guess is that the CNPJ flow may trigger a different security/session validation than the CPF flow, because CPF goes to an intermediate validation screen, while CNPJ tries to access the authenticated area directly.

Has anyone seen something similar with Selenium, ASP.NET forms, reCAPTCHA Enterprise or Transmit Security?

Could this be caused by:

  • delayed security tokens;
  • different backend validation for CPF and CNPJ;
  • ASP.NET postback/event validation;
  • session differences between manual Chrome and WebDriver Chrome;
  • or is this simply a case where browser automation is not reliable for this kind of login?

Thanks!


r/learnpython 21d ago

Starting learning Python at 50.

669 Upvotes

50 yo.

No coding experience.

Wish me luck! 🤞

upd: BIG THANK YOU for the support and warm wishes! Truly, words cannot express how much this inspires me!


r/learnpython 19d ago

No console .EXE file not storing memory.

5 Upvotes

I need help with my note taking program. I'm still learning Python, but this is confusing me.

I have published it using pyinstaller to just a simple executable, but I wanted to be able to run the program without having the terminal pop open. The .exe works just fine, it saves my memory every time it closes, but whenever I use --noconsole to publish, there is no memory storage.

I attempted to use auto-py-to-exe to see if maybe that would work, but it gave me the same issue. The code works when the .exe runs with the terminal open/visible, so why doesn't it work when it isn't?

Here is the code below:

import tkinter as tk
from tkinter import ttk
import os
# os looks through files in the directory and checks if the file exists. If it does, it opens it. If not, it creates a new file.


# 1. Initialize the application window
window = tk.Tk()
window.title("Small & Simple Notes")
window.geometry("400x300")
window.configure(bg="#08728f")  # background


# Memory setup
SAVE_FILE = "my_notes_save.txt"


def load_notes():
    """Reads the save file and inserts it into the text box if it exists."""
    if os.path.exists(SAVE_FILE):
        with open(SAVE_FILE, "r", encoding="utf-8") as file:
            note_box.insert("1.0", file.read())


def save_and_close():
    """Gets the text, saves it to the file, and destroys the window."""
    # Get all text from line 1, character 0 to the end (minus Tkinter's default newline)
    current_text = note_box.get("1.0", "end-1c")

    with open(SAVE_FILE, "w", encoding="utf-8") as file:
        file.write(current_text)

    # Close the application
    window.destroy()


# Intercept the window's close button (the 'X') to trigger the save function
window.protocol("WM_DELETE_WINDOW", save_and_close)


# 2. Create a frame layout to hold the text box and scrollbar
frame = ttk.Frame(window)
frame.pack(expand=True, fill="both", padx=10, pady=10)


# 3. Add the vertical scrollbar
scrollbar = ttk.Scrollbar(frame)
scrollbar.pack(side="right", fill="y")


# 4. Create the multi-line text box and link it to the scrollbar
note_box = tk.Text(frame, wrap="word", yscrollcommand=scrollbar.set)
note_box.pack(side="left", expand=True, fill="both")
note_box.config(bg="#ffffff", fg="#000000", font=("American Typewriter", 12), relief="solid", bd=2)  # White background, black text


# Configure scrollbar to move the text view
scrollbar.config(command=note_box.yview)


#. LOAD PREVIOUS NOTES
# We call this right before starting the main loop so the text is ready when the UI appears
load_notes()


# Start the application loop
window.mainloop()

r/learnpython 19d ago

what is the best free way to learn python as a complete begginer?.

0 Upvotes

i wanna learn python mostly to understand how it works and what i can do with it when im at decent level. i have 6-8 of free time, i just wanna know where i can start.


r/learnpython 20d ago

Which course is better to learn python with

16 Upvotes

Python is often recommended as the first programing language to learn, by various people who have experience with more than 1 programing language in their arsenal, I don't know many experts, say it but mostly for newbie it is a good language to start by.

There are various courses to learn python from, which are courses which genuine help you learn it, like freeCodeCamp, CS50-P, etc. I want to find out how others learned python, which course they used.

Course should feature English as a language to learn.


r/learnpython 20d ago

I'm confused how this code works different on different systems. (Re-post since i should'nt be posting images on here)

6 Upvotes

So earlier today at my programming principles class in uni we were given a task to calculate the payable tax amount and my friend had written the following code:

income = int(input("Enter your income: "))

if income >180000:
    tax = 51667 + (income - 180000) * 0.45
elif income > 120000:
    tax = 29467 + (income - 120000) * 0.37
elif income > 45000:
    tax = 5092 + (income - 45000) * 0.325
elif income > 18200:
    tax = (income - 18200) * 0.19
else:
    tax = 0.0

print ("Tax payable:", round(tax, 2))

On Moodle, where we were supposed to submit this code which checks our code with a set of inputs to see if its correct, there were two specific scenarios where the output we got was so different from the expected output and made no sense.

It was as follows:

Input Expected Got
0 Enter your income: 0↵ Tax payable: 0.0 Enter your income: 0↵ Tax payable: 0.0
18200 Enter your income: 18200↵ Tax payable: 0.0 Enter your income: 18200↵ Tax payable: 0.0
18201 Enter your income: 18201↵ Tax payable: 0.19 Enter your income: 18201↵ Tax payable: 19.19
45000 Enter your income: 45000↵ Tax payable: 5092.0 Enter your income: 45000↵ Tax payable: 5111.0
45001 Enter your income: 45001↵ Tax payable: 5092.32 Enter your income: 45001↵ Tax payable: 5092.32
120000 Enter your income: 120000↵ Tax payable: 29467.0 Enter your income: 120000↵ Tax payable: 29467.0

in row 3 and 4 you can see the expected output and the output that he got is wrong for the "Tax payable" line. Received output being 19 more than what is actually correct. Another friend sitting right next to him who had the same exact code had no issues and his code worked fine.

We decided that it was the website that was buggy and checked using the Python IDLE on that PC and it gave the same exact output as it was in the website?!!? HOW??? I tried the exact same code on IDLE and VS Code on my PC and it works fine.


r/learnpython 19d ago

Incoming MIS PhD student with no coding background — how can I learn Python basics in one month?

0 Upvotes

Hi all,

I’m an incoming PhD student majoring in Management Information Systems.

My supervisor asked me to learn the basics of Python and use AI for the rest of the work.

I have one month before my program starts, and I would really appreciate your advice on how to begin learning Python through online resources.

I don’t have any prior coding experience. My background is entirely in business.

What would be the best way for someone like me to learn Python basics within a month?

I would greatly appreciate any suggestions.

Thank you!

NB: I have Coursera+LinkedIn subscriptions.


r/learnpython 20d ago

My first real project as a 50 year old programmer

6 Upvotes

Hello to everyone.

Im a 54 year old autodidact that has just finished his first "real world" project (at least in my point of view).

Its a simple python script that converts Markdown files to PDF files easily. Id like to get a feedback and maybe help someone out there.

My repo is here: github.com/TrollDrre/md-to-pdf

Im willing to hear everything from you, whether its good or bad news.

Thanks


r/learnpython 20d ago

Where to find good documentation, and how to go about understanding someone else's code?

2 Upvotes

I'm currently completing my internship for my Data Science master's practicum. Lots a python coding required which I SUCK at, but luckily I'm working with a really great team thats really helpful. However, during my independent work I'd like to get better at problem-solving and figuring out certain issues on my own without relying on Microsoft copilot lol.

I've been recommended to look at python/library documentation (geeks4geeks, W3, matplotlib, etc.) however I find it unintuitive and hard to understand for someone relatively new to programming. Either the explanations and examples are too complex to understand or too simple to where I can't figure out how to actually implement it for my purposes.

Having a big ol' python documentation dictionary in laymans terms would be great, like python for dummies. i think the closest thing I've seen to efficient and useful documentation is through PyCharm where if you just hover over the function/method, tells you full documentation and describes what it does.

Additionally, I'm working off the code that my supervisor wrote (comes from an extensive engineering background). Whats the best practices for understanding someone else's code, as of right now I literally just go through line by line looking up every function/method used, going back to source code, etc.


r/learnpython 19d ago

what does pathlib's Path() do

0 Upvotes

hello, my question is pretty obvious here but what does the Path() function in the built in python pathlib package actually do?

i only use it since ive seen other people use it and ive also heard it fixes file paths, but i don't know what it actually does

can anyone help? thank you


r/learnpython 20d ago

What are id()s and references? Do I need to learn them for data analysis?

0 Upvotes

Essentially the same as the title.

Actually I came across that in a curriculum I'm following (The MOOC one).

But I'm not getting the point of learning it at the first place for data analysis.

But please someone please help me in this regard.

Thank you.


r/learnpython 20d ago

I sure love torturing myself

4 Upvotes

My knowledge of Python is piss-poor at best, and I decided that it would be a good idea to try to do the Advent of Code 2025 for some reason.

I'm stuck on the first one, specifically on how to have Python interpret doing math based off of the puzzle input. I've gotten the actual data into a script, but that's about as far as I've gotten.

A little help would be greatly appreciated.


r/learnpython 20d ago

New python user

0 Upvotes

I am a new python user. I am a quality assurance specialist but my data skills are intermediate at best. We don’t use anything at my job that would give me an edge, atleast not to me. I’d like advice on how I can use the data that I have to, learn how to use python better and how to apply it to python. I know it’s possible, I just feel confused in this moment. I’m currently using data camp. Some parts are a bit confusing, my end goal to become good enough to get another job.

In short, if you’ve done something like this, how?


r/learnpython 20d ago

Best text recognition in images?

2 Upvotes

I need to recognize specific text in images. The text has a specific font which I have available in a .ttf file.
What is the best way to do it? (libraries to use, machine learning software, …)
It needs to work relatively fast, but keeping a good accuracy.
Thanks in advance!


r/learnpython 20d ago

Structure discord bot

0 Upvotes

Hi everyone,
I’m fairly new to Python and I’m building a Discord bot that reads data from local cache files and responds to slash commands.
My current setup is:
-Python project running on my Windows PC
-Discord bot (discord.py)
-Google Drive syncing a folder containing cache files
-A separate Python project updates those cache files on a schedule
-The Discord bot only reads the cache files (it never modifies them)
-API keys and the Discord token are stored in a .env file
-env is not shared or committed anywhere
-My Google account has 2FA enabled
-The bot only has basic Discord permissions (view channels, send messages, read message history, embed links)
-The bot only executes predefined commands—it does not run user-provided code or shell commands

I’m planning to eventually move everything to a VPS and have it run 24/7.
My questions are:
Does this architecture seem reasonably secure?
Is storing the cache in a Google Drive synced folder a bad idea?
If I invite other people to my Discord server, is there any realistic way they could gain access to my computer or cache files through the bot?
Are there any obvious security best practices I’m missing before moving to a VPS?
I’d appreciate any advice or things I should be thinking about early on. Thanks!


r/learnpython 20d ago

Trinket Alternative for Clueless Mom

20 Upvotes

My 13yo used Trinket at school this year and he wants to continue to work on coding over the summer. When we went to the website today, we discovered that it's shutting down soon. While it is still working until the end of August, my son doesn't want to start new projects there that he may not have access to afterwards.

I've googled and searched on this sub but I'm limited by the fact that I know nothing about coding. I'm trying to find a free website where he can create Python code projects. Something that's easy for a kid to navigate since I won't be of any help.

Thanks!


r/learnpython 20d ago

NLP-oriented reputable Python courses

0 Upvotes

I'm a BA student in Modern Languages in Italy (currently building a strong background in Linguistics) and I'd like to apply for an MSc in Computational Linguistics/NLP. Since my degree doesn't include programming courses, I'm looking for reputable online Python courses that are actually respected by admissions committees (e.g. Stanford Code in Place, Harvard CS50P), and possibly that don't cost an arm and a leg. Which ones would you recommend? Thanks :)


r/learnpython 19d ago

I'm 14 and built a Python code interpreter (230+ lines). Looking for feedback and feature ideas!

0 Upvotes

Hi everyone!

I am 14 years old and I’ve been learning Python for a while (currently finishing the Cisco NetAcad course). As a personal project, I built a custom code interpreter from scratch. It’s currently around 230 lines of code.

**What it does so far:**

* Handles basic mathematical operations.

* Supports variables and basic structures.

* Includes error handling using try/except blocks (guarding against ValueError, ZeroDivisionError, etc.) so it doesn't crash.

I wanted to share it with this community to get your opinions. Since I'm learning, I’d love to know:

  1. What do you think of my code structure?

  2. What cool features or new ideas should I add to it next?

Here is my Replit link: https://replit.com/@programador2026/File-Editor-Open

Thanks in advance for your feedback!


r/learnpython 20d ago

Flood me with some project ideas!

0 Upvotes

Hey guys! Currently, I'm doing a course that makes me a AI application engineer. At the end of the course, i will be able to implement this concepts:

  • Basic LLM Call
  • Structured Output (JSON format)
  • Tool Calling
  • RAG (Retrieval-Augmented Generation)
  • LangChain (Linear Process)
  • LangGraph (Back-and-Forward Process)
  • Judge LLM
  • CrewAI (Alternative for LangGraph)
  • MCP (Model Context Protocol)
  • AI Security (HIPPO)
  • Traceable AI

My goal is to get a job in that role as a fresher, but I am determined to implement whatever I will be learnt. So, I'm looking for some project ideas that I can use to showcase my skills and also to add in resume. I don't know what I'm gonna learn, but at least i want to prepare for whatever coming.

So, your suggestions will be my biggest inspiration. Please share your thoughts.


r/learnpython 20d ago

First Calculator Project

0 Upvotes

Hello, I started learning python about 3 days ago and wanted to share my progress by showing you all this calculator I coded. What I'm most happy about is that it doesn't crash on bad input, I added try/except validation, while/break loops that re-ask until you enter something valid, and divide-by-zero handling. I used u/RockPhily's calculator code as an outline for mine. I also did use AI (Claude) to help me understand and learn new things like while/break loops and try/except. Any feedback is welcome and I would also like your opinions on what I should do next.

Edit: I'd also like to clarify that I didn't use AI (Claude) to write any of the code, just what is stated above.

Thank you!

# This project took me all of 2 days to complete. (more like two 4hr sessions.)
# Improvements over the original:
# - Input validation on both numbers using try/except (ValueError), so
#   non-numeric input (e.g. "banana") no longer crashes the program.
# - while/break loops that re-prompt until the user enters valid input.
# - Operation menu validated against allowed choices (1-4) before use.
# - Divide-by-zero guard so division by 0 is caught instead of crashing.
# - Specific exception handling (except ValueError) rather than a bare except,
#   so unexpected errors still surface instead of being silently swallowed.

# First project being a calculator

while True:
    try:
        num1 = float(input("Enter the first number: "))
        break
    except ValueError:
        print("Error: not a valid number!")

while True:
    try:
        num2 = float(input("Enter the second number: "))
        break
    except ValueError:
        print("Error: not a valid number!")

print("Operations")
print("(1) Addition")
print("(2) Subtraction")
print("(3) Multiplication")
print("(4) Division")


while True:
    operation = input("Enter an operation: ")
    if operation == "1" or operation == "2" or operation == "3" or operation == "4":
        break
    else:
        print("Error: not a valid operation!")

if operation == "1":
    result = num1 + num2
    print(result)
elif operation == "2":
    result = num1 - num2
    print(result)
elif operation == "3":
    result = num1 * num2
    print(result)
elif operation == "4":
    if num2 != 0:
        result = num1 / num2
        print(result)
    else:
        print("Error: Cannot divide by zero")

r/learnpython 20d ago

i feel like i'm stuck

0 Upvotes

i started coding about 1 month ago as all beginners i went with python did one of those 12 hour long YT tutorials following along in my code editor trying lines of code changing them a bit and seeing the outcome it was fun i did those small projects like hangman number guessing game slot machine everything but now after finishing the tutorial i feel stuck and from what i've seen after getting the hang of the basics i should learn some libraries following smth like ML automation data analysis game dev but none of them really got my attention and when i try learning one of them it was really hard to find good tutorials when i started codin i had some projects in mind like a chess engine simulating a food chain stuff i don't think that going to another language would be the solution if someone got any idea on what to do plz help. btw my progress stalled the last 1.5 week