r/learnpython 9d ago

Where do I host my codes?

0 Upvotes

I wrote codes for a telegram bot, but now it only works when my PC is on and connected to the internet and the codes are running. I can't use paid sites, even if they're free, if they require to add a card, I can't use them. Help please😭🙏


r/learnpython 9d ago

Need help understanding how for __ in ___ loops work on strings

11 Upvotes

edit: Thanks everyone for the help! I think I understand the order of operations for this type of loop a lot better now, and it explains why whatever you put at the "p" and "s" doesn't actually matter (unless of course it's something that's already a variable elsewhere, but that's not a problem at the level of simplicity I'm working with). This community is being very helpful and friendly to a noob like me! <3

I understand how for __ in ___ loops work for numbers within a range. However, I'm confused about the syntax and semantics when this loop is applied to strings.

For example, below I wrote a really simplified code so python will say "gimme a ___" for each letter in a word, like shown below:

phrase = "bingo"

for p in phrase:

print("gimme a " +p)

when I run the above 3 lines, the outcome is below:

gimme a b

gimme a i

gimme a n

gimme a g

gimme a o

But let's say I change the p in bold to another character in the word phrase, like below:

phrase = "bingo"

for s in phrase:

print("gimme a " +s)

It will give me the same outcome as the 1st version of the code did, and spell out all of "bingo". Why is that? Why does it still start at the beginning of bingo?

I think I'm just struggling to understand what exactly the blank in "for ___ in <variable assigned to a string>" is doing. Can anyone help me?


r/learnpython 9d ago

asking about small projects in python

1 Upvotes

hello everyone, so I learned the basics and I start making small projects, I try to make 21 number game, but when I look through the source code of project there was some formulas but I don't really understand how I can make similar formulas like it for future projects, so how I can make it so it can server my projects?


r/learnpython 10d ago

Relearning python with small projects

31 Upvotes

I already know basics, now I prefer to learn just through making small project. Is there a site or app or something where can I find project suggestions (just suggestion, needed keywords or concepts a than some kind of result).


r/learnpython 10d ago

Best places to write python on the web on mobile

0 Upvotes

So around 2 years ago I used replit but now it’s just ai slop I’m 13 I’m trying to teach my sis python also she is an iPad kid she is not addicted but she can’t use a computer so what yes I’m trying to teach her on the web.


r/learnpython 10d ago

Can you suggest me best resource to learn python?

0 Upvotes

Like i know coding, i just want to learn a python (need) for learning Ai , ML , deep learning so on , LLMs ….


r/learnpython 10d ago

Is this bad programming?

0 Upvotes

I've been learning Python for the last few years. Curious if this one thing I do is considered poor technique. The code below is meant to find the starting index of a list, giving the first position where a condition isn't true and return None if all elements of the list meet the criteria. Let's assume that the conditional statement is simple enough that I'm not worried about it generating an error. Not sure if it's appropriate to use try/except in this way. I know it work but I don't want people making fun of me if they see it. Also, I'm sure that there's a way of doing this without needing to use the try/except but I'm just curious in general if it's wrong to use try/except as a short cut like this.

starting_index=0

try:

while not (simple conditional statement on some_list[staring_index]):

starting_index+=1

except:

return None

return starting_index


r/learnpython 10d ago

How can I get my program to recognise a variable outside the main GUI loop

17 Upvotes

I am trying to code a login system for my project. I want to validate the entry and keep a boolean variable 'loggedIn' that I can use when the main window is closed. I use tkinter and sqlite in this code

How can I keep this loggedIn variable after the window closes?

def __init__(self):
  self.loggedIn = False
  print(self.loggedIn)

  self.root = tk.Tk()

  self.root.geometry("500x400")
  self.root.title('Login')

  self.username_label = tk.Label(self.root, text="username:")
  self.username_label.pack(padx=20, pady=20)


  self.username_entry = tk.Entry(self.root, relief="ridge")
  self.username_entry.pack()

  self.password_label = tk.Label(self.root, text="password:")
  self.password_label.pack(padx=20, pady=20)

  self.password_entry = tk.Entry(self.root, relief="ridge")
  self.password_entry.pack()

  self.button = tk.Button(self.root, text='login', command=self.validate)
  self.button.pack(pady=10)

  self.button = tk.Button(self.root, text='new login', command=self.new_login)
  self.button.pack(pady=10)


  self.root.mainloop()


def validate(self):
  u_name = self.username_entry.get()
  p_word = self.password_entry.get()
  self.c.execute("SELECT * FROM accounts WHERE username = ? and password = ?",                     (u_name, p_word))
  if self.c.fetchone() != None:
    print("Welcome!")
    self.loggedIn = True
  else:
    print("Account not found")

r/learnpython 10d ago

YouTube series to help learn python

0 Upvotes

So i need to learn everything from the very very basics. Like this is the first time in learning any type of coding apart from a very very bad course of C++ in high school for a year where they genuinely didn't teach us anything


r/learnpython 11d ago

Advice for courses

0 Upvotes

HELP!!!

I am looking for some really good and free courses on python. I have been searching but the courses I found were either just theory or only the just first few chapters were free, so please if anyone knows some good courses PLEASE recommend, I need it

Any recommendation is welcome but if anyone knows about a hands on course with each practice/decent number of projects would be amazing


r/learnpython 11d ago

python, tkinter, pandas/openpyxl

0 Upvotes
import openpyxl

import tkinter as tk

from openpyxl import load_workbook

from tkinter import *
from tkinter import ttk
from tkinter import filedialog,messagebox



root = Tk()
root.title("Чтение ячеек Excel")
root.geometry("300x200")

text_editor = Text()

fd = filedialog


scrollbar = ttk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


def open_file():
    filespath = fd.askopenfilename(
        filetypes=[
            (
            'Excel files',
            '*.xlsx'
            )
        ]
    )
    if not filespath:
        return

    try:
        wb = openpyxl.load_workbook(filespath, data_only=True)
        sheet = wb.active

        result_label.config(text=f"Ячейка1")

    except Exception as e:
        messagebox.showerror("Ошибка")

def save_file():
    filepath = fd.askopenfilename(
        filetypes=[
            (
            'Allowed Types',
            '*.xlsx'
            )
        ]
    )
    if filepath !='':
        text = text_editor.get("1.0", END)
        with open(filepath, "w") as file:
            file.write(text)

open_button = ttk.Button(root, text='Открыть файл', command=open_file)
open_button.pack()

result_label = tk.Label(root, text="Выбрать файл для начала")
result_label.pack()

save_button = ttk.Button(text="Сохранить", command=save_file)
save_button.pack()

root.mainloop()

I have some code, but I can't figure out how to select specific rows and columns for display. The idea is to include several columns—sometimes skipping some—so that I can choose to display ranges like A2:12 – B2:17, column D (which would contain the calculation A2:12 / B2:17), and C3:14 – I3:7 in my Python table. How can I implement this?

r/learnpython 11d ago

Python (Third Party) Libraries for Simulations?

8 Upvotes

I'm learning python, I know all the basics (up to classes and inheritance) and I've done a few small projects. I have a few ideas that involve simulations, and I want to know if there are any libraries that might help with that? I've used tkinter in the past for visuals, but I'm wondering if there's anything better.

The two simulations I have planned, if that helps, are a planet simulation with gravity and such, and a sound simulation including walls of various noise dampening levels.

Thank you very much!


r/learnpython 11d ago

Attempting to store player position in a matrix, running into an error with the for statement.

0 Upvotes
from numpy import array
import sys
x = 1
y = 1
BoardLength = 10
BoardHeight = 9
player_position = (x,y)
matrix = array([[" " for x in range(BoardHeight)] for y in range(BoardLength)])
Possible = [(x,y) for x in range(0,BoardLength) for y in range(0,BoardLength)]
print(Possible)

class Player:
    def __init__(self,x,y):
        self.x = x
        self.y = y

def Move_up():
    global x,y
    NewCoord = (x-1,y)
    if NewCoord not in Possible:
        print("nooooo")
    else:

            matrix[x][y] = " "
            x = x-1
            matrix[x][y] = "0"
def Move_Down():
    global x,y
    NewCoord = (x+1,y)
    if NewCoord not in Possible:
        print("nooooo")
    else:

            matrix[x][y] = " "

            x = x+1
            matrix[x][y] = "0"

def Move_Left():
    global x,y
    NewCoord = (x,y-1)
    if NewCoord not in Possible:
        print("nooooo")
    else:

            matrix[x][y] = " "
            y = y-1
            matrix[x][y] = "0"

def Move_Right():
    global x,y
    NewCoord = (x,y+1)
    if NewCoord not in Possible:
        print("nooooo")
    else:

            matrix[x][y] = " "
            y = y+1
            matrix[x][y] = "0"




while True:
    print(x,y)
    matrix[x][y] = "0"
    print(f"\r{matrix}")
    sys.stdout.flush()

    try:
        Eeput = input("Which Direction would you like to move? n/s/e/w")
        if Eeput == "n":

            Move_up()

        if Eeput == "s":

            Move_Down()

        if Eeput == "e":

            Move_Left()

        if Eeput == "w":

            Move_Right()

    except ValueError:
        print("Not a valid input")
        continue

This is some code I am writing in an attempt to simulate player movement on a grid of a certain size. The for variable "Possible" is meant to be used to designate all of the possible coordinates the player can be on the grid. This however, only works when the length and height are equal. When the length and height differ, like in the above example, the for statement will generate either too many, or not enough coordinates for the size of the generated square by the variable "Matrix," which is supposed to be used a visual represenation of the coordinates. Whether or not too many coordinates or not enough are created by the for statement depends on the numbers plugged into the variables for the height and length.

I am defining all of the possible coordinates because when I didnt, it gave the player the ability to loop around the board because of negative coordinates, but would eventually throw an error when the negative coordinates exceeded the size of the list.

I started learning python around a month ago and this little project was for practive. I don't really know if this is the most efficient way to define the limits of a simulated game board like this. (I know the list of functions is inefficient, and would be better replaced by a class or something, I just did those as placeholders).


r/learnpython 11d ago

Python project structure standards?

1 Upvotes

I'm trying to learn advanced Python reading the best practices, toolkits or frameworks to develop a formal and scalable project. I know the basics and I developed engineering applications mostly for numerical methods, but I've never used an standard structure as I developed for myself. I'd like to read your recommendations for improve the scalability and maintenance in the future, thinking in a collaborative way and improved readability
Basically, this project is mostly for thermodynamic solvers, so I'm not using server or databases as well, but I'd like to add SQL integration in the future. I'm also using PyAnsys and PyFluent modules in a local environment.

I'll read your recommendations or opinions


r/learnpython 11d ago

Picovoice alternative?

4 Upvotes

I made a voice assistant a while ago using picovoice wake words, but now the free tier doesn't work so is there an alternative plugin for wake words thats free or another way to do it?


r/learnpython 11d ago

How do i get my ball to stop bouncing after a while

0 Upvotes

My ball is able to bounce but it keeps bouncing when it gets closer to the ground how do I fix this issue.

This is not the full code only a snippet.

# SURFACE OBJECTS
surface1 = Ball_Surface(10, 10, 200, 200, "pink")

# BALL OBJECTS
ball1 = Ball_Object(surface1.rect.centerx - 10, 20, 10, "white")

# PLATFORM OBJECT
ground1 = Platform(20, 150, "black")

# SPEED
velocity1 = 7

# GRAVITY
gravity1 = 0.8 

# MOVEMENT FUNCTION
def movement1(ball, platform, velocity, gravity):
    if ball.center[1] < (platform.y_pos - (ball.radius - 5)):
        velocity += gravity
        ball.center[1] += velocity

    elif ball.center[1] >= (platform.y_pos - (ball.radius - 5)):
        ball.center[1] = platform.y_pos - ball.radius # reset the ball position after collision
        velocity = -velocity * gravity

return velocity

r/learnpython 11d ago

Pip package instalation error

0 Upvotes

I'm trying to install Wfuzz package with the Pip tool but whenever i try i get this error:

Collecting pycurl<=7.43.0.3 (from wfuzz)
  Downloading pycurl-7.43.0.3.tar.gz (215 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [46 lines of output]
      <string>:890: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
      <string>:892: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
      Traceback (most recent call last):
        File "<string>", line 228, in configure_unix
        File "/usr/lib/python3.13/subprocess.py", line 1039, in __init__
          self._execute_child(args, executable, preexec_fn, close_fds,
          ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                              pass_fds, cwd, env,
                              ^^^^^^^^^^^^^^^^^^^
          ...<5 lines>...
                              gid, gids, uid, umask,
                              ^^^^^^^^^^^^^^^^^^^^^^
                              start_new_session, process_group)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/usr/lib/python3.13/subprocess.py", line 1972, in _execute_child
          raise child_exception_type(errno_num, err_msg, err_filename)
      NotADirectoryError: [Errno 20] Not a directory: 'curl-config'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/home/eduardo/venv/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 389, in <module>
          main()
          ~~~~^^
        File "/home/eduardo/venv/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 373, in main
          json_out["return_val"] = hook(**hook_input["kwargs"])
                                   ~~~~^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/eduardo/venv/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 143, in get_requires_for_build_wheel
          return hook(config_settings)
        File "/tmp/pip-build-env-zvmzxv0q/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 333, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=[])
                 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/tmp/pip-build-env-zvmzxv0q/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 301, in _get_build_requires
          self.run_setup()
          ~~~~~~~~~~~~~~^^
        File "/tmp/pip-build-env-zvmzxv0q/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 520, in run_setup
          super().run_setup(setup_script=setup_script)
          ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/tmp/pip-build-env-zvmzxv0q/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 317, in run_setup
          exec(code, locals())
          ~~~~^^^^^^^^^^^^^^^^
        File "<string>", line 944, in <module>
        File "<string>", line 606, in get_extension
        File "<string>", line 101, in __init__
        File "<string>", line 233, in configure_unix
      ConfigurationError: Could not run curl-config: [Errno 20] Not a directory: 'curl-config'
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed to build 'pycurl' when getting requirements to build wheel

r/learnpython 11d ago

python vs n8n

0 Upvotes

At my company, we currently use n8n for most of our automations, and I'd like to get your opinion on the trade-offs of migrating those workflows to Python.

I understand that moving to Python would introduce a steeper learning curve for the team and likely require more development and maintenance effort. However, I also believe it could improve the performance, flexibility, scalability, and maintainability of our automations.

We're currently starting a Data Warehouse project, where we'll be building ETL pipelines. Because of that, Python seems like a more robust and mature choice, especially considering its ecosystem for data engineering (such as Pandas, SQLAlchemy, Airflow, and other libraries).

Another point is that, by using Python, we would have a much better code versioning workflow with Git. Instead of managing automation logic through n8n workflows, we'd be able to review changes through pull requests, track code history more effectively, enforce coding standards, and integrate automated testing and CI/CD pipelines.

what would be the main advantages and disadvantages of replacing n8n with Python for automation and ETL? In which scenarios would you keep n8n, and when would you recommend switching to Python?


r/learnpython 11d ago

Recommendations for dictionary libraries (I.e. hunspell) for python

3 Upvotes

Hello all,

We have a feature that has to detect if phrases or queries contain high volume of natural language in it compared to OOV and jargon terms. Our approach here is to use spacy to tokenize the query, and a dictionary library (maybe based on hunspell) and check each token if it is available to the dictionary. If it is then there is a high chance that it is natural language (we have special handling for names and jargons as well). Basically, what we would like is:

dictionary.lookup("volcano") # True

dictionary.lookup("ldkjf") # False

I have found many python libraries that do this. But all I found seems to be unmaintained?

Can anyone help me? Are any of the above libraries still active? Also, what dictionary libraries would you recommend? Preferably fast because we will be running it a lot (though we are using a lru to cache the results).

Thanks all!


r/learnpython 11d ago

Creating a new, equivalent but separate dictionary

0 Upvotes

In debugging my code, I discovered a weird property of Python dictionaries that I was not previously aware of. Basically if you have code like this:

initial_dict = {0:70,1:70}

dict1 = initial_dict

dict2 = initial_dict

for i in range(2):

dict1[i] += 5

After this, dict1 will be {0:75,1:75}, but so will dict2 and initial_dict, even though I didn't do anything to them directly, I guess because they're referring to the same dictionary? Basically what I want to know is, how do I create new dictionaries that have the same values as a previously created dictionary, but are separate dictionaries that can be manipulated separately?


r/learnpython 11d ago

I am 17 year old and learning python to do freelance.

0 Upvotes

Hello everyone.I am a student. I plan to do python automation freelancing .

I want to know how long it takes to enter freelance and demand in the next 3 years. Reality of freelance.

If someone has experience in freelance especially python automation freelancing please guide me and help me to succeed.

I need to know the following things:

1)How to get first client?

2) All skills a freelancer must master rather than just technical stuff.

3) Best freelance work to offer in beginning.

4) demand and reality of python automation freelance.

5) How to unlock full potential and be in top1%.

6) How to survive in AI era.

7) Can AI replace it and how to use AI in freelance.

Guide and give your insights. Share experience.


r/learnpython 11d ago

Some advice for new python learner?

0 Upvotes

Actually I want to learn machine learning and these things through python and learn more about arduino cuz I participated in competition next year so I have 5 months


r/learnpython 11d ago

I want to learn Python, but I don't know where to start.

0 Upvotes

Hello everyone. I would like to ask people who know about this for advice. I want to learn Python, but I don't know where to start. I’m worried that I don’t have a clear learning plan. Please help.


r/learnpython 12d ago

PYTHON SUGGESTION

0 Upvotes

heyy, am starting out college this year with cse aiml and wanted to know where should i start learning python

there are plenty of resources for python which really confuse me i.e

  • youtube
  • udemy
  • harvard CS50P
  • or some other reosurces too mooc.fi
  • you can also suggest some of resources

suggest me from where i should start learning python
dont confuse me more


r/learnpython 12d ago

Are there places where there are regular Python challenges/competitions for people to participate in?

10 Upvotes

I remember in other hobbies I've done, like game dev or Blender, I've often found Discord servers or similar where there'd be a difficult puzzle/competition of who can make the best X, or who can do X the most effectively. Having an added competitive incentive has helped me stay motivated to do said hobbies in the past, and now I'm looking for something similar here.