'Learning IDLE for Python and I am getting stuck on the message 'continue' not in loop [closed]
I am working on a course via Pluralsight called Building your first Python Analytics Solution. The current module is teaching about the IDE - IDLE. The demo I am following uses a prebuilt python file called price.py that is supposed to output a list of items along with the total price. Within the example the instructor is solving for a zero entry using except and continue, as show within the picture, which works when the instructor runs it. Course Example
But when I try to mirror the code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
price_data = pd.read_csv('~/Desktop/price.csv')
print(price_data.head())
price_data = price_data.fillna(0)
print(price_data.head())
def get_price_info():
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError :
continue
get_price_info()
plt.bar(price_data.Things, height=price_data.Total_Price)
plt.title('Barplot of Things vs Total_Price')
plt.show()
I get the error 'continue' not properly in the loop.
The course is using Python IDLE 3.8. The current version that I am running is IDLE 3.10.4.
I have repeatedly gone over the code in the screenshot and it seems to me that the code is exactly the same. I have also researched the error and still could not come up with a solution that will allow me to run the script. I am really new at this and would love to understand where the issue is.
Based on a point, that the code did not match the screen shot. I reloaded the original price.py file and mage the edits needed to make it match. If I am still missing something I would be grateful to know where the mistake is.
After doing some research on try catch blocks I was able to edit the code
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
and get the code to run. Thank you
Solution 1:[1]
Your try-except block is indented incorrectly: it runs after your for loop completes and therefore the continue statement is outside of the loop (invalid).
# loop begins
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
# loop ends
# try/catch begins
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
continue # outside of a loop - invalid
# try/catch ends
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pew |
