/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about all topics related to learning python.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

863,354 Subscribers

1

Reading data from jira and writing jibrish to excel

I am reading data from excel, and when I am writing it to excel one of the columns SE has gibrish data, when I print data in python it displays fine.

Value in excel [<JIRA User:displayName='Last, Name1', key='fname1',name='FName1'>,<JIRA User: displayName='Last, Name2',key='fname2',name='FName2'>]

I need displayName in different columns or comma separated there can be multiple of these. How can I get this done?

0 Comments
2024/11/08
16:29 UTC

2

Using Python to Programmatically Apply Video Effects to Images?

My Challenge:

I’m currently exploring ways to programmatically transform images into videos and apply various effects to make the final output more engaging and lively. My goal is to find a solution that efficiently handles this process with a wide variety of high-quality video effects.

While I’ve experimented with some existing tools, I haven’t found a solution that fully meets my needs in terms of speed, flexibility, and the diversity of available effects.

What I’ve Tested So Far: 1. MoviePy: I gave MoviePy a shot, but found it to be too slow, particularly when dealing with more complex video creation tasks and effects. The processing times made it impractical for my use case. 2. FFmpeg: This tool offers a range of capabilities, but I’ve found it difficult to grasp fully, especially when trying to implement more intricate effects. Additionally, FFmpeg’s built-in effects are relatively limited compared to what I’m aiming for.

What I’m Looking For:

I would like to incorporate the powerful video effects available in Adobe Premiere Pro directly into my Python program. Premiere Pro’s extensive range of high-quality effects is exactly what I need, but I’m unsure if there’s a feasible way to access and control these effects programmatically.

I’m interested in any potential solutions, such as APIs, plugins, or alternative tools that could bridge the gap between Python and professional video editing software like Premiere Pro. I’m also open to suggestions for other libraries or tools that provide a rich variety of effects while maintaining good performance.

Any insights, suggestions, or experiences you could share would be greatly appreciated!

1 Comment
2024/11/08
15:54 UTC

1

What is the mistake here?

I was trying to implement this method to calculate area of a shape by putting random dots and then calculating the ratio of dots that fall inside the shape. The program doesn't show any error but the blue dots I expected it to draw aren't being drawn and the area is wrong too, I guess... I wanted to consider 1 pixel as 1 unit.

import pygame
import random

# Initialize Pygame
pygame.init()
outside_points=[]
inside_points=[]
screen_width = 600
screen_height = 600
rect_height = 400
rect_width = 400
font = pygame.font.SysFont("Arial", 30)

# Set up the window
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Area calculation')

# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)

# Game loop
running = True
clock = pygame.time.Clock()

# Fuctions

def random_coordinate(screen_x, screen_y):
    x = random.randint(0,screen_x)
    y = random.randint(0,screen_y)

    return(x,y)

def check_coordinate(coordinate):
    if coordinate[0] > rect_width / 2 and coordinate[0] < 600 - rect_width / 2 and coordinate[1] > rect_height / 2 and coordinate[1] < 600 - rect_height / 2:
        return 1
    else:
        return 0
    
def draw_and_add_coordinates():
    coordinate = random_coordinate(screen_width,screen_height)
    pygame.draw.circle(screen, BLUE, coordinate, 1 )
    if check_coordinate(coordinate)==1:
        inside_points.append(coordinate)
    else:
        outside_points.append(coordinate)
   
def calculate_stuff():
    global text_surface, text_rect
    draw_and_add_coordinates()
    count_out = len(outside_points)
    count_in = len(inside_points)
    total_points = count_in + count_out
    ratio = count_in/total_points
    area_of_rectangle = int(600*600 * ratio)
    output_text = str(area_of_rectangle)

    text_surface = font.render(output_text, True, (0, 255, 0))  # White color
    text_rect = text_surface.get_rect(center=(400, 550))  # Center the text
    
  

while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    for i in range(10000):
        calculate_stuff()



   
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE,(screen_width/2-rect_width/2, screen_height/2-rect_height/2, 400, 400)),
    # Draw game objects here
    screen.blit(text_surface, text_rect)
    # Update the display
    pygame.display.flip()

    # Control frame rate
    clock.tick(60)

# Clean up
pygame.quit()


1 Comment
2024/11/08
15:15 UTC

1

Issues importing pyotp on pycharm

Hi everyone,

I'm currently trying to set up 2FA, but from the tutorials and guides I'm watching, I can't seem to figure out how to install it via pip using `pip install pyotp` and then import it in PyCharm—it just doesn't seem to work.

I'm on macOS and have checked through the terminal, but that's only confusing me more at this point. Any help would be greatly appreciated! (Please be kind; I’m super new to this.)

1 Comment
2024/11/08
14:35 UTC

5

Lists in python

hi i am new to python. we had a quiz question and the result that i waited to see was different. i think i read at somewhere that two lists become the same but i wasnt sure. the code is below. can you explain what is going on at the background. list1=[1,3] list2=list1 list1[0]=4 print(list2)

output is 4,3

6 Comments
2024/11/08
14:34 UTC

0

Feeling lost

Hi, so im currently doing python mooc 2024, up to part 5. IS it normal to feel like some days i have good days where i feel like im understanding and days that feel liek im not?

I just feel like its in and out my head sometimes

2 Comments
2024/11/08
14:00 UTC

1

How to become better

I’m programming in python for a while now and have made some decent things. I have one particular project that’s working really well for me. I’m no wondering how do I become better? I feel like I can make the software more efficient, use more advanced ways, etc. But how do you get better when you’re already reasonably well?

4 Comments
2024/11/08
13:53 UTC

1

Is there a way to change the string repesentation of a class before it has instantiated.

I have tried the following

and none of these work it still prints <class '__main__.r'>

class r:
    def __str__(self) -> str:
        return "yes"

    def __repr__(self) -> str:
        return "no"

    def __unicode__(self):
        return "maybe"


r.__repr__ = lambda: "shit"

print(r)

edit extra context:

this is for a streamlit app where I'm passing a list of uninitiated classes to a select widget where the user can select which class to use in a pipeline.

I can't initiative them because some need init arguments that the user chooses.

for now I have made an work around that uses a dictionary where user selects key and then the class gets taken out of the dict

14 Comments
2024/11/08
13:35 UTC

2

Extracting both tables and text from PDF using camelot

Hi,

I need to extract both tables and text from a PDF.

The PDF file I’m working with contains multiple tables along with accompanying text. The text often provides additional context for the tables, with some references pointing to content on subsequent pages. Because of this, I need to process the entire PDF as a cohesive document.

Here’s where the challenge arises: Camelot does a great job extracting tables, but it only provides limited metadata—specifically, the page number and bounding box (bbox) coordinates that specify the table’s location on each page. Unfortunately, this isn’t sufficient for text extraction, as Camelot doesn’t handle non-tabular content. Other libraries, like pdfplumber and PyMuPDF, do offer text extraction along with associated metadata, but they use different scaling and coordinate systems for bounding boxes. This results in mismatches, making it difficult to align text and tables accurately across libraries.

Do you have any suggestions or ideas on how I could extract text from the PDF, ideally while continuing to use Camelot as the primary tool? Any advice would be greatly appreciated.

Thank you!

1 Comment
2024/11/08
11:44 UTC

4

What exactly is a HTTP client?

According to what I had researched, in programming a client is an entity that requests a service from another entity. For example, when we use our PC to enter reddit we are a client that communicates with the Reddit server.

But in the guide to the web-scrapping sub-reddit there is something called httpx and requests, which apparently are clients of python. But I don't understand.

What is httpx? And how can it be a client if supposedly when entering a page the client is us?

14 Comments
2024/11/08
11:24 UTC

0

How to improve python for job coding tests

Hi i am currently learning python. I messed up my coding test recently for a data science internship. Any Suggestions preparing for them? Any websites i can practice? Really want one get an internship for summer.

3 Comments
2024/11/08
10:18 UTC

0

Can’t Plot A Surface For Prediction Model

I have a multiple linear regression model predicting Y for X1 and X2. I’ve got a script that runs without error, but no surface is drawn; where am I going wrong?

fig = plt.figure(figsize=(12, 9)) ax = fig.add_subplot(projection='3d') ax.scatter(df.eval(X1), df.eval(X2), df.eval(Y), color='blue') X_Plot = np.asanyarray(train[[X1]]) Y_Plot = np.asanyarray(train[[X2]]) Z_Plot = train_y_ ax.plot_surface(X_Plot, Y_Plot, Z_Plot, cmap=cm.coolwarm) #Doesn't work ax.set_xlabel(f'{X1_Mask}') ax.set_ylabel(f'{X2_Mask}') ax.set_zlabel(f'{Y_Mask}') plt.show()

0 Comments
2024/11/08
10:14 UTC

0

I asked ChatGPT how to learn Python in 6 months, and this was the answer. Should I follow it?

To get proficient in Python for data science and machine learning within six months, a structured plan with clear weekly goals and portfolio projects is essential. Here’s a detailed breakdown with step-by-step study areas, resources, and project ideas:

Months 1-2: Python Fundamentals and Data Manipulation

  • Week 1-2: Basic Syntax and Data Types
    • Learn basic syntax, variables, data types (strings, lists, dictionaries, sets, tuples).
    • Practice: Solve simple exercises on Python basics (e.g., from sites like Exercism or HackerRank).
  • Week 3-4: Functions, Loops, and Conditional Statements
    • Learn functions, control flow (if, else, while, for loops), and list comprehensions.
    • Practice: Write small scripts or mini-programs to reinforce these concepts (e.g., a calculator or a unit converter).
    • Project Idea: Simple Text Analyzer — Create a script that counts word frequencies, identifies unique words, and provides basic stats on a text input.
  • Week 5-6: File Handling, Error Handling, and Modules
    • Understand file operations (open, read, write files), error handling (try-except), and using modules.
    • Learn about libraries (time, random, os).
    • Project Idea: Contact Book — Develop a program to add, view, update, and delete contacts saved in a text file.
  • Week 7-8: Data Manipulation with Pandas and NumPy
    • Learn about NumPy arrays, array operations, and basic linear algebra operations.
    • Explore Pandas for data manipulation, including DataFrames, reading and writing files (CSV, Excel), data cleaning, filtering, and aggregation.
    • Project Idea: Sales Data Analysis — Analyze and visualize a dataset (e.g., a CSV file of sales data), performing tasks like finding the highest sales, monthly trends, and aggregating by region.

Months 3-4: Data Visualization and Basic Statistics

  • Week 9-10: Data Visualization with Matplotlib and Seaborn
    • Learn to create line plots, bar charts, histograms, scatter plots, and box plots.
    • Explore Seaborn for more advanced visualizations (heatmaps, pair plots, distribution plots).
    • Project Idea: Customer Insights Dashboard — Create a dashboard that visualizes customer data (age distribution, spending patterns) with various types of charts.
  • Week 11-12: Basic Statistics
    • Learn descriptive statistics (mean, median, mode, variance, standard deviation).
    • Explore distributions (normal, binomial, Poisson) and basic probability concepts.
    • Project Idea: Exploratory Data Analysis (EDA) on a Public Dataset — Use a dataset from Kaggle (like Titanic or Iris) to analyze key statistics, identify trends, and visualize the data.
  • Week 13-14: Working with APIs
    • Learn to make HTTP requests with Python’s requests library.
    • Practice extracting and processing data from APIs in JSON format.
    • Project Idea: Weather App — Create a program that fetches real-time weather data for a city of your choice and displays information such as temperature, humidity, and forecast.

Months 5-6: Introduction to Machine Learning with Scikit-Learn

  • Week 15-17: Machine Learning Fundamentals
    • Understand the basics of supervised vs. unsupervised learning.
    • Learn to split data into training and test sets.
    • Work with Scikit-Learn for training models (linear regression, decision trees, k-nearest neighbors).
    • Project Idea: Simple House Price Predictor — Use a dataset with house prices to predict a home’s price based on features like location, size, and number of rooms.
  • Week 18-20: Model Evaluation and Hyperparameter Tuning
    • Learn model evaluation techniques (accuracy, precision, recall, F1-score).
    • Experiment with hyperparameter tuning methods.
    • Project Idea: Customer Churn Prediction — Train a model on a customer dataset to predict which customers are likely to leave (churn) based on features like usage frequency, plan type, and support interactions.
  • Week 21-24: Final Project and Portfolio Polishing
    • Final Project Idea: End-to-End Data Science Project — Choose a dataset relevant to your interests, perform data cleaning, exploratory data analysis, visualize findings, build and evaluate a machine learning model, and document the process.
    • Suggested datasets: Kaggle datasets like Titanic, Iris, Wine Quality, or Customer Segmentation.

Additional Tips for Portfolio-Building

  • Document Your Work: Write detailed readme files explaining your project’s objectives, dataset, approach, and findings. This will make your portfolio more professional.
  • Use GitHub: Host your projects on GitHub, as employers often look for candidates with version control experience.
  • Blog About Your Projects: If possible, write blog posts explaining your projects or machine learning concepts you’ve learned. This can help showcase your understanding.
8 Comments
2024/11/08
10:12 UTC

1

What is the difference between pip install and pacman -S?

Absolute beginner here, currently trying to understand virtual environments. I am using Arch linux and whenever I try to install a python library using pip install it says that the environment is externally managed and I should use pacman -S. So my question is if arch already has a environment ready and a way to install libraries in it then why should I use pip and why should I create another venv in the first place.

4 Comments
2024/11/08
09:56 UTC

1

Adding a meta field to pcap packets that doesn't impact other parameters

Hi all, i'm doing analysis on large pcap file. For dev purposes, I would like to add a field to each packet, allowing me to do other operation a lot easier (it would be less efficient to refer to a map with a packet ID and the field)

I see the scapy.packet does have a comment method, but I couldn't find much element on that. I want my pcap field to be "rewritten" with a specific meta field, is that something achievable ? Perhaps it's more of a network capture related question than python but as I use python to manipulate these, and that scapy seems pretty powerful, I wanted to know if I should search deeper or surrender and use that external map

thank you very much !

1 Comment
2024/11/08
09:35 UTC

1

CERTIFICATE_VERIFY_FAILED when running python-script with shazamio on Mac?

I try to run the following code on a Mac-Computer:

import asyncio
from shazamio import Shazam
import os, sys
import pprint

path = os.path.abspath(os.path.dirname(sys.argv[0])) 
fn = os.path.join(path, "Tinashe Ft. Tyga - Nasty XXX - (A.D. Twerk Edit Dirty-).mp3")

async def main():
  shazam = Shazam()
  out = await shazam.recognize(fn)  # rust version, use this!
  pprint.pprint(out)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

on one computer it works fine without any problems but on the other Mac-Computer i get this error:

Traceback (most recent call last):
  File "aiohttp/connector.py", line 1098, in _wrap_create_connection
  File "asyncio/base_events.py", line 1081, in create_connection
  File "asyncio/base_events.py", line 1111, in _create_connection_transport
  File "asyncio/sslproto.py", line 528, in data_received
  File "asyncio/sslproto.py", line 188, in feed_ssldata
  File "ssl.py", line 944, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "checkMusic.py", line 101, in <module>
  File "asyncio/base_events.py", line 642, in run_until_complete
  File "checkMusic.py", line 28, in main
  File "shazamio/api.py", line 584, in recognize
  File "shazamio/api.py", line 597, in send_recognize_request_v2
  File "shazamio/client.py", line 57, in request
  File "aiohttp_retry/client.py", line 158, in __aenter__
  File "aiohttp_retry/client.py", line 119, in _do_request
  File "aiohttp/client.py", line 663, in _request
  File "aiohttp/connector.py", line 563, in connect
  File "aiohttp/connector.py", line 1032, in _create_connection
  File "aiohttp/connector.py", line 1366, in _create_direct_connection
  File "aiohttp/connector.py", line 1335, in _create_direct_connection
  File "aiohttp/connector.py", line 1100, in _wrap_create_connection
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host amp.shazam.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)')]
[PYI-1342:ERROR] Failed to execute script 'checkMusic' due to unhandled exception!
logout

Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Deleting expired sessions...none found.

Is there any workaround regarding this CERT-Error so i can get the script running on any Mac-computer?

2 Comments
2024/11/08
08:57 UTC

5

Does Python have a usable type system? How can I get typescript style type-checking in VSCode?

If I am trying to fetch a Django model from my psql db using a property that doesn't exist, I want my IDE to warn me about it before I deploy it to my server.

13 Comments
2024/11/08
08:29 UTC

2

How to debug a pypi package not found issue?

I've been trying to pip install intuit-oath package that is clearly in PyPi but get not found errors for linux and windows. Intuit is notoriously not responsive to developers so I have to ask elsewhere. Is there any way to debug this like finding out why it can't find a version for my systems.

4 Comments
2024/11/08
07:05 UTC

0

Help with Alien_Invasion

Hi I don't want to go into to much detail unless someone knows the answer, but am running into an issue need to get this project done. When I am trying to run the game it says the ship image is "not in working directory", but it is in fact in the directory already. When I run the game the screen is black as well as the window crashes. Anyone every done this? It's a popular project in "Python Crash Course" when learning python. Been search the web for a solution.

16 Comments
2024/11/08
06:43 UTC

2

Failed to install PyQt5 on python 3.11

I am trying to install PyQt5 in the raspberry pi 5 terminal using pip install PyQt5. I got a couple of warnings: certificate verify failed and an ERROR: could not find a version that satisfies the requirement PyQt5(from versions: none) and ERROR: No matching distribution found for PyQt5.

Learned that the PyQt5 isn't supported on python versions after 3.9. Should I roll back to prev version of python?

2 Comments
2024/11/08
06:38 UTC

0

I don't enjoy coding but I am forcing myself to learn it.

So basically I tried multiple times this year to start my coding journey and always I started with python only but as soon as 1 week ends I stop enjoying it. Once again, I started doing it last week and today I am getting lazy to back to it. Can someone give me advice on this.

39 Comments
2024/11/08
05:47 UTC

3

This is the same, right?

I just learned python for 1 month, and I need help. My teacher give me a web, and one of its task says that make a program that can count the numbers of lowercase letters when insert.

This is my code:
a = input()
b = 0
for i in a:
if i.islower():
b += 1
print(b)
But it says that this is the wrong answer, it does work though

Correct answer:
a = int(input())
words = ["a", "b",... ] -->lowercase alphabet
for i in range(a):
n = 0
lst = list(input())
for j in lst:
if j in words:
n += 1
print(n)
Sorry the second one I just copy from a correct answer, I don't even know if it's correct or not. What I want to ask is my code correct? Anyone got another way to code this? Thanks

10 Comments
2024/11/08
04:57 UTC

0

dataclasss object naming problems

I am struggling to create a dataclass from inventory data stored in a SQL database. retrieving the data and instantiating the class doesn't appear to be a problem. As I can see each instance thru a print statement in a for loop while instantiating the objects. My problem is I can't retrieve the info outside of the for loop used to create the objects.

This is a relevant snippet of the code I am using:

from dataclasses import dataclass

import os

#class Product(id,picture,sku,cost,oldsku,direct,notes,location,description,catalog,box,ratio,kind,images,catagory,pattern,video,current):

u/dataclass

class Product:

name:str

id:int

picture:str

sku:str

cost:str

oldsku:str

dir:str

notes:str

location:str

description:str

catalog:str

box:int

ratio:int

kind:str

images:str

catagory:str

pattern:str

video:str

current:int

data1=DB_open()

# Iterate through the data and write it onto the image

for row in data1:

newItem=('A'+row[2]) # sku

newItem = Product(newItem,row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17])

print(eval(str(newItem)))

print(eval(str(A1001))) # one of the objects created above A1001

8 Comments
2024/11/08
04:38 UTC

16

Best One Book Suggesations for Learning Python.

I am New to Programming World.

7 Comments
2024/11/08
04:31 UTC

2

Best course to study these topics?

Hi , I'm a college student taking a Python course "Modern Applications Development".
I don't feel my professor's slides and labs are enough to understand his exams. I did pretty bad on the midterm and have a project+final coming up.

So in my 1 week of fall break I want to learn these following topics:

  • Conditionals, Loops, & Functions
  • Data Structures (Lists & Tuples)
  • Data Structures (Dictionaries & Sets)
  • Files & Exceptions
  • OOP & Text Processing
  • Python & Data
  • Advance Python
  • Testing & Deployment
  • Web Scraping & API

Are there any well known online courses containing these topics?
I would like it to be free but paid is not off the table if it's worth it.

Any help would be appreciated, Thanks.

2 Comments
2024/11/08
04:05 UTC

4

Hard to Understand

I'm learning Python from Replit, but I find it really hard to write code without seeing a solution first. Why is that? I'm not sure if it's just hard for me or for many people. I want to become an expert in Python as soon as possible because it’s in high demand for jobs, but coming from a commerce background, I find it especially difficult to understand programming concepts and I'm 29 years old.

I'm from a commerce background, which is why it's so difficult for me to understand Python or What.

14 Comments
2024/11/08
03:18 UTC

3

Dynamic DateTime Conversion

I'm building a small tool in QT that uses a format string based on the standard format specifiers used by the QDateTime::toString() function.

  • yyyy - 4-digit year
  • MM - 2-digit month
  • dd - 2-digit day
  • hh - 2-digit hour (24-hour format)
  • mm - 2-digit minute
  • ss - 2-digit second

The date format I'm using is: yyyy-MM-dd

I want to use Pillow within the tool and I can get the datetime like this:

datetime = datetime.strptime(date_time, "%Y:%m:%d %H:%M:%S")

I can then convert it to the same date format like this:

datetime = dt.strftime("%Y-%m-%d")

The issue is that I need to be able to convert between the dates dynamically, either by converting the QT date to DateTime or vice versa. The user is able to set their preferred date format so this bit of the code is unknown "%Y-%m-%d" For example, instead of yyyy-MM-dd the user might set the overall date format to yy-MM-dd which would mean that I would need to use date_obj.strftime("%y-%m-%d") but how would I actually know the format code to use seeing as the user can enter a range of different time formats?

Hope this makes sense.

3 Comments
2024/11/08
02:22 UTC

6

Best premium school

What is the best premium school for python. I have seen pros and cons for most of them but which one gives you the best bang for buck. And will make sure I don't have any gaps.

Some I am considering Real python Udemy Programiz W3schools Codeacademy

Or any others you would recommend

3 Comments
2024/11/08
01:54 UTC

1

Adding Simple User Authentication to a Javascript project?

Hi, I’m currently working on a web app for a group project that uses Firebase with JavaScript to retrieve and display recipes. My group tasked me with adding authentication in python to our almost complete codebase (utilizing python is a project req.). Currently the app has features like displaying, rating and querying recipes using firebase. I previously tried implementing authentication with Django and managed to get the authentication working smoothly, but I ran into issues getting firebase to connect and work properly. I spent a lot of time debugging to no avail.

Could anyone suggest a simple way to implement a login system using Python, which will work smoothly with our current Firebase/JavaScript setup? Thanks.

0 Comments
2024/11/08
01:44 UTC

0

Anomaly with scope?

I'm an experienced programmer trying to learn Python. Please help me understand scope. If I understand what I've read properly, a variable defined at the top has global scope. So here is the code that has me scratching my head:

1  x = 5
2  def outer():
3     print (x)
4     #x=x+1
5  print("Value of x in the beginning is " + str(x))
6  outer()
7  print("Value of x after the function call is " + str(x))

This prints the value of x properly all 3 times (from lines 3, 5 and 7). If I uncomment line 4, it fails with an error (UnboundLocalError). I have a coupl questions now.
a) Since x is declared before any function definitions, shouldn't it scope be global, and hence should be usable anywhere?
b) If x is not global, how come the print command in line 3 works fine with line 4 commented out?
c) If the value of x is known in line 3, why does line 4 throw an error when it is uncommented?

Thanks in advance.
6 Comments
2024/11/08
01:30 UTC

Back To Top