77|PYTHON – Error Correction

BYU Student Author: @IWillyerd
Reviewers: @TylerBooth, @Spencer, @Nate
Estimated Time to Solve: 15 Minutes

We provide the solution to this challenge using:

  • Python

You can use Google Collab as the Integrated Development Environment (IDE) to complete the challenge. The challenge solution uses the Pandas library.

Need a program? Click here.

Overview
You have a friend who just started a Python class. They know that you are pretty good at Python, and since they’re struggling with one of their homework assignments they were wondering if you could debug their code before they turn it in. They sent you over three problems to see if you could debug them and let them know what they did wrong.

Instructions
You won’t need to read in any data for the challenges except for Problem 2. To easily read in the data ensure that the “Problem 2” datafile is in the same directory as the python file you are working in. To begin the challenge, copy over the following sets of code to your preferred IDE to debug the sets of code:

Problem 1
#Problem 1 
print("Welcome to the guessing game!") 
solution = 5 
guess = input("Guess a number between 1 and 10: ")) 
while guess = solution 
  if guess < solution 
  print("Your guess is too low.") 
  elif guess > solution 
  print("Your guess is too high.") 
  else 
  print("Congratulations, you guessed the number!") 
print("Thanks for playing!") 
Problem 2
#Problem 2 
import pandas as pd 

# Create a DataFrame 
df = pd.read_exls('ChallengeX_Problem_2.xlsx') #This will need to be updated for the challenge number after download 

# Print the DataFrame 
print(df) 

# Calculate the average salary 
average = df['salary'].mean 
print("The average salary is:" average) 

# Add a new column for bonus 
df['bonus'] = df['salary'] x 0.1 

# Print the updated DataFrame 
print(df.head()) 
Problem 3
#Problem 3 
revenue = 5000 
expenses = [1000, 1100, 200, 2500] 
net_income = revenue - expenses 
profit_margin = net_income / revenue * 100 

print("Revenue: $" revenue) 
print("Expenses: $" sum(expenses)) 
print("Net Income: $" net_income) 
print("Profit Margin: %" profit_margin) 

Data Files

Solution

Problem 1 Answers

Problem 1 had the following errors:

  • A missing colon at the end of the “while” statement
  • Missing colons at the end of the “if”, “elif”,and “else”
  • The “while” loop condition should use “!=” instead of “=”
  • The “input()” function returns a string, but it should be stored as an integer using “int()” before
    storing it as “guess” so that you can use it as a comparison
  • The logic of the problem is faulty. Initialize the “guess” before the “while loop” move the “input()” into
    the “while loop”, and have the “else” statement be a “break” when the correct number is guessed
Problem 2 Answers

Problem 2 had the following errors:

  • A missing plus sign to concatenate and “str()” function for the “average” variable in the print statement
  • Missing the parenthesis after “.mean()” for the “average” variable calculation
  • Misspelled statement should read to read in Pandas data frame it should be “pd.read_excel()”
  • Though just visual, there is a space missing after colon in “The Average salary is:”
Problem 3 Answers

Problem 3 had the following errors:

  • A missing a plus sign to concatenate and “str()” function for the “revenue” variable in its print statement
  • A missing a coma between the string and “expense” variable for the “expense” print statement.
  • The “net_income” variable is created from subtracting a list “expenses” from an integer “revenue” you need to sum the expenses to get a total expense number
  • Missing either a coma, or a plus sign to concatenate the “Net Income” and “Profit Margin %” statement
  • The “profit_margin” variable is being multiplied by 100 with an “x” and not a “*” the multiplication operator for Python

The output of Problem 3 should look similar to:
Challenge77_Image

Solution Code
#Problem 1 
print("Welcome to the guessing game!") 
solution = 5 
guess = 0 
while guess != solution:   
    guess = int(input("Guess a number between 1 and 10: ")) 
    if guess < solution: 
        print("Your guess is too low.") 
    elif guess > solution: 
        print("Your guess is too high.") 
    else: 
        break 

print("Congratulations, you guessed the number!") 
print("Thanks for playing!") 



#Problem 2 
import pandas as pd 

# Create a DataFrame 
df = pd.read_excel('ChallengeX_Problem_2_Data.xlsx') 

# Print the DataFrame 
print(df) 

# Calculate the average salary 
average = df['salary'].mean() 
print("The average salary is: " + str(average)) 

# Add a new column for bonus 
df['bonus'] = df['salary'] * 0.1 

# Print the updated DataFrame 
print(df.head()) 



#Problem 3 
revenue = 5000 
expenses = [1000, 1100, 200, 2500] 
net_income = revenue - sum(expenses) 
profit_margin = (net_income / revenue) * 100 

print("Revenue: $" + str(revenue)) 
print("Expenses: $" ,sum(expenses)) 
print("Net Income: $", net_income) 
print("Profit Margin: %", profit_margin) 

Challenge77_Solution.txt
Solution Video: Challenge 77|PYTHON – Error Correction

Thanks for the fun debugging challenge! I went about few of the problems a little differently, but enjoyed working through this. Here’s my code:

Problem 1:
print(“Welcome to the guessing game!”)
solution = 5
while True:
guess = input("Guess a number between 1 and 10: ")
if int(guess) < solution:
print(“Your guess is too low.”)
elif int(guess) > solution:
print(“Your guess is too high.”)
else:
print(“Congratulations, you guessed the number!”)
break
print(“Thanks for playing!”)

Problem 2:
import pandas as pd

df = pd.read_excel(‘Challenge77_Problem_2_Data.xlsx’)

df

average = df[‘salary’].mean()
print(f"The average salary is: ${average}")

df[‘bonus’] = df[‘salary’]*.01

df.head()

Problem 3:
revenue = 5000
expenses = [1000, 1100, 200, 2500]
net_income = revenue - sum(expenses)
profit_margin = net_income / revenue * 100

print(f"Revenue: $ {revenue}“)
print(f"Expenses: $ {sum(expenses)}”)
print(f"Net Income: $ {net_income}“)
print(f"Profit Margin: {profit_margin}%”)

Problem 1:
print(“Welcome to the guessing game!”)
solution = 5
guess = input("Guess a number between 1 and 10: ")
while guess == solution:
if guess < solution:
print(“Your guess is too low.”)
elif guess > solution:
print(“Your guess is too high.”)
else :
print(“Congratulations, you guessed the number!”)
print(“Thanks for playing!”)

Problem 2:
import pandas as pd

Create a DataFrame

df = pd.read_excel(‘Challenge77_Problem_2_Data.xlsx’) #This will need to be updated for the challenge number after download

Print the DataFrame

print(df)

Calculate the average salary

average = df[‘salary’].mean
print(“The average salary is:” + str(average))

Add a new column for bonus

df[‘bonus’] = df[‘salary’] * 0.1

Print the updated DataFrame

print(df.head())

Problem 3:
revenue = 5000
expenses = [1000, 1100, 200, 2500]

expensetotal = 0
for expense in expenses:
expensetotal = expense + expensetotal

net_income = revenue - expensetotal
profit_margin = net_income / revenue * 100

print(“Revenue: $” + str(revenue))
print(“Expenses: $” + str(sum(expenses)))
print(“Net Income: $” + str(net_income))
print(“Profit Margin: %” + str (profit_margin))

#Problem 1
print(“Welcome to the guessing game!”)
solution = 5
guess = input("Guess a number between 1 and 10: ")
while guess == solution:
if guess < solution:
print(“Your guess is too low.”)
elif guess > solution:
print(“Your guess is too high.”)
else:
print(“Congratulations, you guessed the number!”)
print(“Thanks for playing!”)

#Problem 2
import pandas as pd

Create a DataFrame

df = pd.read_excel(‘Challenge77_Problem_2_Data.xlsx’) #This will need to be updated for the challenge number after download

Print the DataFrame

display(df)

Calculate the average salary

average = df[‘salary’].mean
print(f’The average salary is:" {average}')

Add a new column for bonus

df[‘bonus’] = df[‘salary’] * 0.1

Print the updated DataFrame

display(df.head())

#Problem 3
revenue = 5000
expenses = [1000, 1100, 200, 2500]
total_exp = 0
for expense in expenses:
total_exp = total_exp + expense
net_income = revenue - total_exp
profit_margin = net_income / revenue * 100

print(f"Revenue: $ {revenue}“)
print(f"Expenses: $ {sum(expenses)}”)
print(f"Net Income: $ {net_income}“)
print(f"Profit Margin: % {profit_margin}”)

This is a good one! Here’s how I did it:

#Problem 1
print(“Welcome to the guessing game!”)
solution = 5
guess = input("Guess a number between 1 and 10: ")
while True:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
if guess < solution:
print(“Your guess is too low.”)
elif guess > solution:
print(“Your guess is too high.”)
else:
print(“Congratulations, you guessed the number!”)
break
print(“Thanks for playing!”)

#Problem 2

import pandas as pd

Create a DataFrame

df = pd.read_excel(‘Challenge77_Problem_2_Data.xlsx’)

Print the DataFrame

print(df)

Calculate the average salary

average = df[‘salary’].mean()

print(f"The average salary is: {average}")

Add a new column for bonus

df[‘bonus’] = df[‘salary’] * 0.1

Print the updated DataFrame

print(df)

#Problem 3

revenue = 5000

expenses = [1000, 1100, 200, 2500]

net_income = revenue - sum(expenses)

profit_margin = (net_income / revenue) * 100

print(f"Revenue: $ {revenue}")

print(f"Expenses: $ {sum(expenses)}")

print(f"Net Income: $ {net_income}")

print(f"Profit Margin: % {profit_margin}")