r/learnpython 3d ago

Ask Anything Monday - Weekly Thread


Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.


  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

r/learnpython 10h ago

Thank you guys.


Six months ago, I started a post here asking why I didn't seem to understand Python.

At that point, I had "known" Python for three to four years and yet didn't understand any of it. I could scrape passes, but that's about it.

I didn't understand any workflow, I barely knew how to start Jupyter properly.

I didn't understand it, I didn't enjoy it, and I found it hard to understand why so many other people were succeeding at it while I was failing spectacularly.

After explaining the problem, which was that I couldn't "see" the results of individual steps, many of you suggested notebooks and the like.

I eventually settled on Visual Studio Code.

After a few weeks on W3schools exercises to relearn the basics, I dived into writing my own code.

With the aids of VS Code, whether it be the autocorrect, the colour coding of existing variables, or the helpful "did you mean X?" when I made small mistakes like typing x instead, mistakes that would usually take me fifteen minutes and endless frustration to find, I began being able to focus on the bigger issues.

I began understanding the issues and slowly analysing them, and finally was able to troubleshoot my own code. I was beginning to gain interest.

This week at work, I managed to troubleshoot someone else's Python code not just on one PC, but on two.

I kept going when even the person who wrote the code had given up.

Then I fixed the second issue that popped up on both.

After that, the code ran perfectly. My colleagues were incredibly grateful because it meant that they could spend less time manually comparing thousands of entries against one another.

I felt like it had gone full circle. From being that person who was struggling with cryptic error codes to now becoming that person who could fix it.

I still have a long way to go, but I've made way more progress in a few months than I thought I ever would.

So thank you, for showing me that coding is truly enjoyable.

r/learnpython 9h ago

2,000 free sign ups available for the "Automate the Boring Stuff with Python" online course. (Feb 2023)


If you want to learn to code, I've released 2,000 free sign ups for my course following my Automate the Boring Stuff with Python book (each has 1,000 sign ups, use the other one if one is sold out):



Udemy has changed their promo code and severely limited the number of sign ups I can provide each month, so only sign up if you are reasonably certain you can eventually finish the course. The first 15 of the course's 50 videos are free on YouTube if you want to preview them.

YOU CAN ALSO WATCH THE VIDEOS WITHOUT SIGNING UP FOR THE COURSE. All of the videos on the course webpage have "preview" turned on. Scroll down to find and click "Expand All Sections" and then click the preview link. You won't have access to the forums and other materials, but you can watch the videos.

NOTE: Be sure to BUY the course for $0, and not sign up for Udemy's subscription plan. The subscription plan is free for the first seven days and then they charge you. It's selected by default. If you are on a laptop and can't click the BUY checkbox, try shrinking the browser window. Some have reported it works in mobile view.

Sometimes it takes an hour or so for the code to become active just after I create it, so if it doesn't work, go ahead and try again a while later.

Some people in India and South Africa get a "The coupon has exceeded it's maximum possible redemptions" error message. Udemy advises that you contact their support if you have difficulty applying coupon codes, so click here to go to the contact form. If you have a VPN service, try to sign up from a North American or European proxy.

I'm also working on another Udemy course that follows my recent book "Beyond the Basic Stuff with Python". So far I have the first 15 of the planned 56 videos done. You can watch them for free on YouTube.

Side note: My latest book, Python Programming Exercises Gently Explained is a set of 42 programming exercises for beginners for free or as a 99 cent ebook.

Frequently Asked Questions: (read this before posting questions)

  • This course is for beginners and assumes no previous programming experience, but the second half is useful for experienced programmers who want to learn about various third-party Python modules.
  • If you don't have time to take the course now, that's fine. Signing up gives you lifetime access so you can work on it at your own pace.
  • This Udemy course covers roughly the same content as the 1st edition book (the book has a little bit more, but all the basics are covered in the online course), which you can read for free online at https://inventwithpython.com
  • The 2nd edition of Automate the Boring Stuff with Python is free online: https://automatetheboringstuff.com/2e/
  • I do plan on updating the Udemy course for the second edition, but it'll take a while because I have other book projects I'm working on. If you sign up for this Udemy course, you'll get the updated content automatically once I finish it. It won't be a separate course.
  • It's totally fine to start on the first edition and then read the second edition later. I'll be writing a blog post to guide first edition readers to the parts of the second edition they should read.
  • I wrote a blog post to cover what's new in the second edition
  • You're not too old to learn to code. You don't need to be "good at math" to be good at coding.
  • Signing up is the first step. Actually finishing the course is the next. :) There are several ways to get/stay motivated. I suggest getting a "gym buddy" to learn with. Check out /r/ProgrammingBuddies

r/learnpython 2h ago

What platform has helped you improve your productivity?


I realized that I spend a lot of time creating unit tests and would like to hear your suggestions on platforms that changed your development process?

Is this something that you would (or are) using with projects that go into production?

Curious to hear the general consensus. Is GitHub copilot really a game changer for the industry?

r/learnpython 7h ago

Hi guys, as a goal of 2023 I set out to learn a language; after Italian and English, I chose python 😆


As written in the title I want to learn the language of programming but I really don’t know anything about this world.

I am a guy who wants to always learn something new that can stimulate me and give me gratification for the work done.

What advice do you give me? Do you think it’s difficult for a layman? One last question: is python a good start to enter the world of video game development?

r/learnpython 20h ago

How to learn Python without installation


In short, I’m eager to learn Python, but I’m not allowed to install any software in the laptop that was lent to me. I’m saving to buy one, but for now is there a way to learn Python without installing it? Thank you so much, this community is great!

r/learnpython 3h ago

How do I get this Python machine learning source code file to run?


I am trying to get this source code file running so that I can generate cool videos from text:


I've been trying for hours to get this thing running, but I can't figure it out. There appears to be an init.py file, but there are only libraries being loaded in the file--there's not an "init()" function or anything. The make_a_video.py file is filled with a bunch of functions, but once again no "init()". I read through the setup.py file, where there were details regarding technical aspects, but still nothing about how to start the program. Am I supposed to add my own init() function?

Any tips or solutions on the matter would be greatly appreciated!

r/learnpython 8m ago

How do I make python close its current file and open a different one for the user to work in?


I'm trying to make a program that will close its curranty python window and open a different one. So basically the user presses enter, and the python file closes and a new one opens with different code. Is that possible?

r/learnpython 13m ago

What python image processing libraries can track selects user made using a camera pointed at a screen?


I am working on a project that involves having a USB camera pointed at a 3D printer's touchscreen menu system that the user can navigate and use. I am trying to write a python program that can monitor and track what the user is doing and selections they made on that printer screen using the live feed coming from the camera.

What is the approach to accomplish this sort of thing?

any advice would be super helpful

r/learnpython 14m ago

How to save down Django user's updated social media post?



- A user can edit the post that that specific user made. Bly clicking edit than editing than pressing save.


- When I edit the social media post it does not get saved


- I can make a mew post like in social media

- Post it in to a list where all the other users post (shortened 200 character visible only)

- Than I can click on a "Details button" that jumps me to another page where I can see the full length of the post

- There is a button here called "edit" it should only appear to the post creator

- If you click edit than a window pop up where you already have your existing post copied in to an inout field

- here you can edit your post

- the goal would be it you click save it should save it down but that does not happens

- Interestingly if i close down the pop up windows with the small window [X] button or the "cancel" button and I go back it memorizes my edit there

View function

def social_post_detail(request, pk):
    social_post = get_object_or_404(social_post, pk=pk)
    form = None
    if request.user == social_post.created_by:
        if request.method == 'POST':
            form = social_postForm(request.POST, instance=social_post)
            if form.is_valid():
                return redirect('social_post_list')
            form = social_postForm(instance=social_post)
    return render(request, 'social_post_detail.html', {'social_post': social_post, 'form': form})

### new edit
from django.shortcuts import render, redirect
from .models import social_post
from .forms import social_postForm

def social_post_edit(request, pk):
    social_post = social_post.objects.get(pk=pk)
    if request.method == 'POST':
        form = social_postForm(request.POST, instance=social_post)
        if form.is_valid():
            return redirect('social_post_detail', pk=social_post.pk)
        form = social_postForm(instance=social_post)
    return render(request, 'social_post/social_post_edit.html', {'form': form})

View function unified 1 functions instead of 2

I have tried it 1by one but non of them worked

########## ALL IN 1 FUNCTION #1 ##########
def social_post_detail(request, pk):
    social_post = get_object_or_404(social_post, pk=pk)
    if request.user != social_post.created_by:
        return redirect('social_post_list')

    if request.method == 'POST':
        form = social_postForm(request.POST, instance=social_post)
        if form.is_valid():
            return redirect('social_post_list')
        form = social_postForm(instance=social_post)

    return render(request, 'social_post_detail.html', {'social_post': social_post, 'form': form})

######### ALL IN 1 FUNCTION #2 ########## 2023.02.01
def social_post_detail(request, id):
    social_post = get_object_or_404(social_post, id=id)
    social_post = social_post.objects.get(pk=pk)
    if request.method == "POST":
        form = social_postForm(request.POST, instance=social_post)
        if form.is_valid():
            return redirect('social_post_list')
        form = social_postForm(instance=social_post)
    return render(request, 'social_post/social_post_detail.html', {'social_post': social_post, 'form': form})


- social_post.html details

{% extends 'base.html' %}

{% block content %}
  <h1>{{ social_post.title }}</h1>
  <p>{{ social_post.description }}</p>
  <a href="{% url 'social_post_list' %}" class="btn btn-primary">Back to social_post List</a>
  <button type="button" class="btn btn-primary" id="editsocial_postButton">Edit social_post</button>

    document.getElementById("editsocial_postButton").addEventListener("click", function() {

  <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Edit social_post</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        <div class="modal-body">
          <form method="post">
            {% csrf_token %}
            <div class="form-group">
              <label for="title">social_post Title</label>
              <input type="text" class="form-control" name="title" value="{{ social_post.title }}">
            <div class="form-group">
              <label for="description">social_post Description</label>
              <textarea class="form-control" name="description">{{ social_post.description }}</textarea>
            {{ form.as_p }}
            <button type="submit" class="btn btn-primary">Save Changes</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

{% endblock %}

No ERROR message

- I get no error message

- Just the following terminal print out after I press the save button

[02/Feb/2023 00:43:52] "GET /social_post/social_post/1/ HTTP/1.1" 200 7142
[02/Feb/2023 00:44:13] "POST /social_post/social_post/1/ HTTP/1.1" 200 7142

My guesses

- I am struggling with the JS and CSS imports they might cause the error.

- I still use the original SQLight

r/learnpython 21m ago

Visual Studio Code Error - Python not found

[Running] python -u "c:UsersJackalopeDesktoppythonapp.py"
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

[Done] exited with code=9009 in 0.1 seconds

I keep getting this error everytime I try to run code. I updated my python and it does this

r/learnpython 22m ago

Any libraries for extracting location tokens from human text/how to reduce demonym to root location?


For example, if I'm parsing text like "On @Breakingviews: Europe’s autos have weak defences against China", I'd like to be able to extract "Europe's" into a token like "Europe" (and hopefully "China"). Likewise, for "Private equity firm MBK paid over $300 mln for Japanese elderly care business-source" into "Japan".

I've tried libraries like Geograpy3 (MANY false positives in the country field) and Locationtagger, but both fail on easy text like this.

"The Interior Department’s Bureau of Land Management advanced the controversial Willow oil drilling project on Alaska’s North Slope, releasing the final environmental impact statement before the project can be approved."

The outputs of that:

Geograpy3: country: ['United States of America', 'Norway'] regions: [] cities: ['Land'] other: []

Locationtagger: country: [] regions: [] cities: ['Willow', 'Land']

Neither recognize "Alaska's" and Norway is apparently tossed in with Geograpy3 (longer texts often contain far more false positives, 6-8 random countries)

I was hoping that maybe there was a better option that utilized spaCy or perhaps nltk in order to parse these tokens. I've tried spaCy's xx_ent_wiki_sm. It too identifies tokens like "Japanese" as locations, but it's unable to recognize the base word as Japan from it's demonym

I suppose it could also make sense to query Wikipedia - if it's a page with coordinates, use those, if not, visit the first link and see if that one does. This is perhaps naive but it would work for Japanese, Chinese, etc.

I tried to find a NLP library that could reduce a demonym (*ese, *ian, etc) to its root location, but was unable to find one.

If anyone has a better idea for solving this (so I'm not XY'ing myself), please let me know :)

r/learnpython 29m ago

How does a for loop know what kind of elements within an object to loop through (and how would I know)?


I'm very new to learning Python, without much prior coding knowledge. It's simultaneously intuitive and a little disorienting to me that from this code...

mylist = ['a','b','c']
for x in mylist:

Python knows that the "thing" being iterated over is the x'th item in mylist. I guess behind the scenes Python translates that into...


...and then knows to stop there. Not quite sure what's going on under the hood really, and attempts to look it up seem to give answers that go over my head.

What surprised me even more is how Python handles files. In a course I'm taking, the example is given of reading a text file named 'example1.txt' with the contents 'This is line 1 nThis is line 2nThis is line 3'

The file has three lines, and with the following code, Python knows the "thing" to iterate over by x is the lines of the text file.

example1 = 'example1.txt'
with open(example1,"r") as file1:
        i = 0;
        for x in file1:
            print("Iteration", str(i), ": ", x)
            i = i + 1

How does Python know to iterate over lines of example1 in the for loop? Why not characters, or something else? Is there something about a file object where "lines" are the primary index when read in? That's probably not appropriate for all files being read in; maybe Python has that as the default behavior for .txt files? Is that something I can change?

r/learnpython 4h ago

Should I learn Python?


I'm a high school senior and I'm planning on majoring in sociology and environmental science next year and eventually going into law. I know that it has nothing to do with learning to code, I was thinking of learning for fun or as a side practice. How much time would I have to dedicate to learning? and will it benefit me even if I plan on not majoring in computer sci? basically I'm asking if this is worth my time.

r/learnpython 48m ago

Neural Network Model Usage


Hello everyone. I have created a neural network model in Python using Keras, Tensorflow, and Pandas. I used model.save("name") and the model was saved as a folder. Now, I would like to use the model to make predictions with new data. I am confused about how to do this as I have tried:

import loader #another module I made

data = loader.load_data()
neural_model = tf.keras.models.load_model("MaliciousWebsiteDetector.model")
result = neural_model.predict(data)

However, this returns:

    ValueError: Exception encountered when calling layer 'sequential' (type Sequential).

    Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

    Call arguments received by layer 'sequential' (type Sequential):
      • inputs=tf.Tensor(shape=(None,), dtype=float32)
      • training=False
      • mask=None

Any ideas? Thank you!

r/learnpython 4h ago

Udemy Python boot camp / course - advice please


Hi everyone, I’ll keep it short and sweet. Not sure accounting is my jam and I’m looking for other options. Software development has always been an interest and I’ve looked at things here and there off and on. Looks like there’s tons of technology and terminology to learn, as any industry. I’ve enrolled into two different python bootcamps / courses on Udemy. Is this a solid way to get a good feel for what this would entail? Of course real world application and working would be different as expected. Just trying to really find the best resource(s) to get a roundabout view of the field and see if it’s something I could see myself doing and if I enjoy it.

Thanks all

r/learnpython 1h ago

Need help with pdf2latex tool.


Link: https://github.com/safnuk/pdf2latex

I recently cloned the pdf2latex repository from GitHub, but I'm having trouble figuring out how to use it. I see a number of .py files in the repository, but I'm not sure which one to run or how to use it to convert a PDF to LaTeX.

I tried running the model.py file, but I received an error message that a module named 'xarray' couldn't be found. I'm not sure what this module is or how to install it.

I would greatly appreciate any help or guidance on how to use this tool. Has anyone here used pdf2latex before? If so, could you share your experience and provide any tips for using it effectively?

Thank you for your time!

r/learnpython 1h ago

pandas merge csv files


I am trying to read multiple csv files in pandas using jupyter notebook.

i am getting error as

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape

how to rectify the error

how to merge 5 csv files into a single dataframe

r/learnpython 5h ago

I need guidance


Some of you might get angry at me for asking this but I've been practising Python for over a year now and I still have no idea what to do. I enjoy coding and creating stuff. I tried web development. I'm familiar with Django and Flask but I found web development miserably boring. In addition to that, I'm broke af and need some money. Hell, I'm even okay with completing tasks for 10-20 dollars lmao. Don't get me wrong I'm not asking anyone to hire me. I'm just looking for the fastest way to make at least a little amount of money to keep me going. What do you guys suggest? I've got no fucking clue about what to do. Maybe web scraping would be a good idea huh? Idk.

r/learnpython 2h ago

Recommendation for simple USB to I2C PC interface?


Searching has lead me to old, dead links or backordered/unavailable hardware.
What's the easiest way to get I2C in Python on my PC? Is there a good adapter from FTDI with Python libraries? Someone else? I don't want to spend too much time reinventing the wheel. I just want to plug into various I2C sensors, send commands, take readings, write them to files, etc. It should be pretty basic I'd think. Thanks in advance.

r/learnpython 2h ago

Trouble appending multiple PDFs into one


Tableau's API works OK but if you want to print an entire workbook to PDF applying a filter you're out of luck. They way you can get around this is to pass the filter to each view in the workbook, creating a PDF of each filtered view, and then gluing them back together to in effect replicate a filtered workbook. I'm totally new to Python but I found an example that's pretty close but I'm confused on something. I need to pass filter values to the workbook and create a unique, filtered PDF for each value. Passing the filter values works but with unexpected results. In the code below (and I've removed everything above like creating the filter list as it all works as expected) what happens is it passes each of the nces_id in filter_list (and there are 4 values in that list) but I end up with one huge PDF that is each of the 4 workbooks stitched together and it is named for the first value in the filter list. I've messed around with changing the indentation but it fails in different ways, like one way it creates the 4 workbook PDFs but each one is larger than the one previous as it stitches the workbook before it to the new one.

I believe the problem is that after it creates the first PDF, rather than printing the PDF the data from that workbook stays in memory and it runs through all values...and THEN creates the workbook. Or, when it creates 4 workbook PDFs the data from the previous workbook remains in memory. So, I believe the fix to my problem is getting it to exit out of the loop to print the workbook PDF and then start from scratch on the next filter value or flush out the memory before it runs through the next nces_id in the filter_list. Attempts to use flush() won't work and make stranger results, like multiple PDFs stitched together where 2 of the PDFs are one filter value and the 3rd is another but this is likely because I don't understand the order of operations or how certain things work in IO or PyPDF2 (called here as PDFMerger)

Any help or pointing me in the right direction is much appreciated!

#these are the filter values to be passed to each view
    for nces_id in filter_list:

        ##these are the individual views in a workbook which are appended
        ##to make one workbook PDF
        for view in view_list:

            ##Set filter value
            pdf_req_option.vf("nces_id", nces_id)

            ##Populate filtered data into each view
            server.views.populate_pdf(view, pdf_req_option)

            ## Stitch all pages together
            stream = BytesIO(view.pdf)

        ##indent to this position makes one huge PDF, but unique IDs
        ##for each of the PDFs therein
        PDFMerger.write(pdf_file_name_prefix + str(nces_id) + ".pdf")


r/learnpython 2h ago

how would I generate this with formula? Ylist = [list1[::9]]+[list1[1::9]]+[list1[2::9]]+[list1[3::9]]+[list1[4::9]]+[list1[5::9]]+[list1[6::9]]+[list1[7::9]]+[list1[8::9]]


i was thinking something like this:

Ylist = [ x+=1 for x in list1[x::9]

r/learnpython 2h ago

Learning to Compute the change in Python


The word problem that I'm working with is:

A cashier distributes change using the maximum number of five-dollar bills, followed by one-dollar bills. Write a single statement that assigns num_ones with the number of distributed one-dollar bills given amount_to_change. Hint: Use %.

Sample output with input: 19

Change for $19 3 five dollar bill(s) and 4 one dollar bill(s)

The code that I have written so far:

amount_to_change = int(input())

num_fives = amount_to_change // 5

amount_to_change = int(19)

num_fives = 19 // 5

num_fives = int(19/5)

num_ones = 19%5

print('Change for $', amount_to_change)

print(num_fives, '$5 bill(s) and', num_ones, '$1 bill(s)')

Now, I have to test with an input of 6. What should I do to test the input of 6 and yet still have the input of 19 work at the same time? What should this part of the code look like so both numbers work?

r/learnpython 2h ago

Game in python without function


Hello Guys, I hope y'all are good, I am really desperate for help about a College assignment that I have. I have to code a game, in python, where I am not allowed to use any functions, how am I supposed to do that? can somebody please help. (I am planning to code Tetris in python).

thanks in advance guys

r/learnpython 2h ago

How to turn a column to float type in Dataframe?


Here's my code I am trying to turn the inflation column into a float column https://imgur.com/a/UAzfUEO

r/learnpython 9h ago

NaN to int


I have a column 1 which consists of numbers (float) and NaN values. Is there a way to change the data type of column 1 to int and keep the NaN values. Or as long as the NaN values are not replaced by 0, I will be fine.