Utilizing a global variable for tracking iterations in a nested for loop in Python

I am facing an issue while using a global variable x as a counter in my for loops. I have two lists, col_values_X_right and col_values_Y_right, which store coordinates. I intend to create 15 different plots using these coordinates, as the '-' separators within them indicate new chapters of data obtained from another source. However, I am struggling to utilize my global counter variable within the loops. I attempted to use global x, but encountered the error message

SyntaxError: name 'x' is assigned to before global declaration
. Could someone guide me on how to resolve this and effectively utilize the x variable across all cycles?

x = 0

for j in range(number_of_separatores//2):
    image_plot1 = plt.imshow(image1)
    global x
    for i in range(len(col_values_X_right)-x):
        if stimulus_name[x+1] == '5_01.jpg' and col_values_X_right[x+1] != '-':
                plt.scatter([col_values_X_right[x+1]], [col_values_Y_right[x+1]])
                x += 1
        else:
            break
plt.show()

Additional details:

x = 0 # initializing the counter variable for cycles 
a = 15
image = mpl.image.imread('file_name.png')
X = list() # specify float numbers here
Y = list() # include coordinate values here

for j in range(a): # loop for creating multiple plots 
    image_plot = plt.imshow(image) # display image for plotting
    for i in range(len(X)): # iterating through coordinate columns separated by '-'
        if X[x+1] != '-':
            plt.scatter([X[x+1], Y[x+1]) # plot a point based on coordinates
            x+=1 # move to the next column cell for the next iteration
        else:
            break # stop plotting current plot and move to the next one upon encountering '-'
  
plt.show() 

Answer №1

I'm not entirely sure what you're aiming for, but this approach could potentially provide a solution. Take a look at this answer

y = 0 #Global

def bar():
    global y
    for k in range(10):
        for m in range(10 - y):
            #Implement your own logic here
            if k % 2 == 0:
                y += 1
            else:
                break
    print("Inside: ", y)

def main_function():
    print("Initially", y)
    bar()
    print("Afterward", y)    

main_function()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to locate the Twitter direct message input box with Xpath in Selenium

I have been struggling to locate the textbox element using the find_element_by_xpath() method. Unfortunately, every time I try it, I receive an error stating that the element cannot be found. Here is the specific line of code in question: Despite attempti ...

What are the steps to accessing and interpreting the information in /dev/log

Is there a way to read syslog messages directly from Python by accessing /dev/log? It seems like the correct approach is to use a datagram socket. import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sock.bind('/dev/log') sock ...

Python die rolling

My current project involves digitalizing the throw of various dice. The code I have written so far prompts for input on the number and type of dice to be thrown, and then displays the result. Here is an overview: import dice die = input("Roll the dic ...

Discovering a specific element within a nested element using Selenium WebDriver

I have encountered an issue while trying to search for an element within a sub-element using Selenium (Version 2.28.0). It seems that Selenium does not restrict its search to the specified sub-element. I am unsure if my approach is incorrect or if there is ...

Encountering a type error when attempting to open a SQL file that has been

I'm currently working on a Python application using Django where users can upload SQL files. I am using fileField to receive the uploaded file, however, it is not being stored anywhere. When attempting to process the file by opening it, I encounter an ...

The synchronization between Chrome and Selenium is experiencing difficulty

Attempting to launch a selenium browser with sync option enabled has been proving difficult. Whether I use the --used-data-dir parameter (loading all cookies and extensions from my google account onto selenium) or not, synchronization still does not work. ...

Error related to environment / authentication - BigQuery Admin: {invalid_grant, Invalid JWT Signature}

Recently, I embarked on my first journey to utilize the BigQuery API by following a Python tutorial guide available here. My primary objective is to create datasets, however, I'm encountering challenges with basic public data access. To address this, ...

Grouping pandas dataframes and appending values to distinct columns

Currently, I am working with a pandas dataframe which is displayed as follows: https://i.stack.imgur.com/K3XoT.png I am looking to get the output in the format shown here: https://i.stack.imgur.com/WyH19.png Your assistance on this matter would be high ...

Finding the smallest value within a collection of JSON objects in an array

Looking at the following list, I am in search of the lowest CPU value: [{'Device': 'A', 'CPU': 10.7, 'RAM': 32.5}, {'Device': 'B', 'CPU': 4.2, 'RAM': 32.4}, {'Device' ...

A guide to accessing a specific element within a JSON object using Python

I am currently working with a JSON file that contains the following two lines: "colors": ["dark denim"] "stocks": {"dark denim": {"128": 4, "134": 6, "140": 17, "146": 18, &quo ...

Looking to extract and interpret the content of an Outlook email using Python and convert it into a pandas DataFrame. How can I achieve this task

Looking to extract the body of emails from Outlook and import them into a pandas data frame. How can I separate the msg.Body into individual lines that can be saved to a csv file and then imported into pandas? Currently, this is what I have been able to a ...

Python code that evaluates two lists and retains only the elements that match or do not match

Searching for matches in two lists of tuples and generating separate lists seems tricky. I attempted a nested loop to compare the tuples, but ended up with incorrect results. The "no match" list contained some tuples that were actually matching. There must ...

Dealing with Non-ASCII Characters When Importing Libraries in Python Arcpy

While working on debugging a simple GIS python script, I encountered an unexpected error: Traceback (most recent call last): File "<module1>", line 13, in <module> import arcpy File "C:\Program Files (x86)\ArcGIS\Desktop ...

What could be causing the JSON.parse() function to fail in my program?

Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

Can value_counts() be applied to two columns simultaneously?

I am working with a pandas dataframe that contains texts, each of which can be categorized into multiple categories and belong to one genre. The categories are represented in the dataframe using one-hot encoding. For example: df = pd.DataFrame({'text ...

Is there a way to quickly obtain a sorted list without any duplicates in just one line

Since the return value of sort() is None, the code snippet below will not achieve the desired result: def get_sorted_unique_items(arr): return list(set(arr)).sort() Do you have any suggestions for a more effective solution? ...

Currently caught up creating an Instagram bot

Here is the code snippet I have been working on: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys # initiating browser session browser = webdriver.Chrome() browser.get("https://instagram.com") time.sleep ...

When incorporating quotation marks within quotation marks

Whenever I try to use the print command in Python with quotation marks, I struggle to prevent the string from closing prematurely. For example: print " "a phrase that requires quotation marks" " Attempting the above approach results in the string being ...

How can I use Selenium to open a webpage without pausing the script?

I am facing an issue where all the code execution after driver.get(url) is halted until the page finishes loading. I want to avoid this behavior, so I am looking for alternative methods or perhaps a way to make the get method non-blocking. Is there any s ...

Is It Possible to Split a String Using Only External Brackets?

Here is the string I have: {"type":"summary","symbol":"SPY","open":"267.09","high":"267.22", "low":"265.6", "prevClose":"266.75","close":"265.66"} {"type":"quote","symbol":"SPY","bid":265.38,"bidsz":3, "bidexch":"Q","biddate":"1513293904000","ask":265.42, ...