r/learnpython • • 20d ago

I have an assignment and I am so confused

i talked to 4 tutors and for some reason i can not get this to work after 2 hours with a tutor. please tell me what i am doing wrong!

b. A function named DisplayCardSales that displays scores for all items in the text file provided. Each score should have a line number to the left starting at 1. For example: 1: 1.24 2: 0.97. (see output example below). This function accepts zero arguments and does not return any values. This function does read from a text file, so it needs error handling for FileNotFoundError.

c. A function named CalcTotal that reads the text file provided, accumulates a total and divides the total by the number of items in the file provided. This function accepts zero arguments and returns two values. The values returned are the grand total and the sales amount as a result. This function does read from a text file, so it needs error handling for FileNotFoundErrors and ValueErrors.

def CalcTotal():
    try:
        infile = open("cards.txt",'r')
    except:
        print("Error")
    else:
        count = 0
        totalsales = 0
        
        for line in infile:
          sales = float(line)
          totalsales = totalsales + sales
          count = count + 1


        avgsale = totalsales/sales
        print("Total Sales: $", totalsales)
        print("Average Sale: $", avgsale)


        infile.close()

def DisplayCardSales():
    try:
        infile = open("cards.txt",'r')
        i = 0
        for line in infile:
            print((i+1), ": $", line)
            i = (i + 1)
        infile.close()
    except:
        print("Error")
3 Upvotes

32 comments sorted by

14

u/atarivcs 20d ago

What exactly do you mean when you say "can not get this to work"?

Do you mean the code does not run because it has errors?

Do you mean the code runs, but produces no output?

Do you mean the code runs, but produces incorrect output?

2

u/x_slysuccubus_x 20d ago

it runs but has errors, neither one of the for loops seem to work. if i choose C or D calc or display I get the print "error" message

1

u/atarivcs 20d ago edited 20d ago

One obvious reason for the "Error" output is that it could not find the cards.txt input file.

The code expects the input file to be in the current directory. But, depending on exactly how you run it, the current directory may not be the same as the directory where the python script is located.

You can add this snippet of code to the top of each function so you can see the actual current directory:

import os
print(os.getcwd())

And the way you're handling exceptions, it hides the actual reason for the error, which is a terrible way to do it.

It would be better if you just let the exception happen, without a try/except block, so you can see the actual reason for the error.

1

u/x_slysuccubus_x 19d ago

so should i just comment them out because they have to be there for the assignment?

1

u/atarivcs 19d ago

I would take them out temporarily, so you can see the full error happen once. You can put them back after that.

3

u/RngdZed 20d ago

you could use an f-string to make printing more intuitive and make debugging easier.. use more print, check everything you can

print(f"{variable} some other words")

1

u/eykei 19d ago

For line in infile.readlines():

1

u/[deleted] 19d ago

[removed] — view removed comment

1

u/x_slysuccubus_x 18d ago

no kidding

3

u/Agawell 20d ago

Adding some extra print statements will help massively in debugging - ie print out each line that’s being read from each of the files - so you know the file is being read correctly

You can comment them out or delete them once you’ve verified what’s happening!

What is actually being output when you call these functions?

And what are your expected results?

1

u/x_slysuccubus_x 20d ago

this is the full assignment

OVERVIEW Most programs store and read information each time they are ran. So far, we have created programs that only operate at runtime. This means that the user must enter values every time the program is ran. Instead, data can be saved to file and used each time an application is opened. Examples of programs that store information would be Word, Canvas, and Excel. These applications rely completely on data that is stored.

TASK Dylan has a small side hustle selling Pokémon cards. His process stores sales information for each card in a file and he needs a program to calculate the total sales as well as the average card price. Average sale amount is determined by dividing the grand total by the number of sales. Your task is to create a program that displays the card sale prices to screen and calculate the average sale amount.

REQUIREMENTS

  1. Pseudocode containing:

a. A main function that displays a menu of choices. Menu choices are: D: Display Sales C: Calculate Total and Average X: Exit application The menu will display until the user enters X to exit the application.

b. A function named DisplayCardSales that displays sales data for all items in the text file provided named cards.txt. Each score should have a line number to the left starting at 1. For example: 1: 1.24 and 2: 0.97. (see output example below). This function accepts zero arguments and does not return any values.

c. A function named CalcTotal that reads the text file provided, accumulates a total and divides the total by the number of items in the file provided. This function accepts zero arguments and returns two values. The values returned are the grand total and average sale amount.

2. Program written in Python containing:

a. A main function that displays a menu of choices. Menu choices are: D: Display Sales C: Calculate Total and Average X: Exit application The menu will display until the user enters X to exit the application.

b. A function named DisplayCardSales that displays scores for all items in the text file provided. Each score should have a line number to the left starting at 1. For example: 1: 1.24 2: 0.97. (see output example below). This function accepts zero arguments and does not return any values. This function does read from a text file, so it needs error handling for FileNotFoundError.

c. A function named CalcTotal that reads the text file provided, accumulates a total and divides the total by the number of items in the file provided. This function accepts zero arguments and returns two values. The values returned are the grand total and the sales amount as a result. This function does read from a text file, so it needs error handling for FileNotFoundErrors and ValueErrors.

d. Program is saved as Program6.py

NOTE: Function names must be correct as outlined above.

TEST CASES The formatted sales total will return $151.31 and the formatted average sale will return $2.80 based on the text file provided to you. You must develop your program to count the lines in the event the text file was to change.

ASSESSMENT Item Point Value

Pseudocode is created in a Word document and displays all processes (with IPO Charts). 5

Program runs in Python without error (required to earn any points) Yes/No

Program includes documentation. 2

Program includes main function that loops to redisplay menu. 2

Program includes function named DisplayCardSales that accepts zero arguments and returns zero values. The function opens the text file provided, loops through the lines, and displays each sale to screen including a 1-based line number with no extra blank lines (see expected output above) 4

Program includes function named CalcTotal that accepts zero arguments, opens the text file provided, loops through the lines, accumulates a total, and increments a counter. The function will then calculate the average which is the accumulated total divided by the counter. The total and average will be the return values from this function as floats. The final sales total and sale average is printed to screen and formatted in the main function (see expected output above) 4

Program includes error handling for DisplayCardSales and CalcTotal functions. 3

TOTAL POINTS 20 * Make Sure both pseudocode document and Python program are submitted for this assignment.

3

u/Western_Progress_456 20d ago

avgsales=totalsalles/count

1

u/x_slysuccubus_x 20d ago

good call forgot i changed that

1

u/Atmosck 20d ago

I second the question about what you mean by it not working. If it's producing an error, it would helpful to see the error message and traceback. If it's being rejected by your teacher or some online grading system, is there any feedback?

Your DisplayCardSales look likes it should work. Did they say what it should do if there is an error? Normally if you're catching an error it's because you want the program to do something other than crash when you get an error.

Your CalcTotal function doesn't return anything, like the question asks. What does the file look like? Your code treats it like it's just a single number on each line, each representing one s ale. In which case, your avgsale line should divide by count, not sales. But I would expect the file to look more like a csv with multiple things per row, like:

item,quantity,price
apple,3,4.50
banana,1,10.00

In which case you would want to split each row, like line.split(",")

In both questions, the wording makes it seem like they want you to catch those specific error types. In problem C they probably want different results depending on which error type.

In general, bare except is considered bad practice because it catches everything. Normally you want to catch only the errors you expect, and let other error go uncaught. Like if you're reading a file and it's not there, you can print a message saying what's wrong. But if you're reading a file and get some other error like you ran out of memory, that's considered "unrecoverable" and the program should actually crash in that case.

1

u/x_slysuccubus_x 20d ago

so the error it is producing is the printed error from the except block. which tells me the try block is not working but I had a tutor (did not have enough time/$) he said if both docs are in the same file their should be no issue.

yes the program can not crash! no matter what the input in main is nor if it cant find the file it can not crash.

i did add a return now but idk if it is correct. I feel like my indents are wrong now

def CalcTotal():
    try:
        infile = open("cards.txt",'r')
    except:
        print("Error - CT")
    else:
        count = 0
        totalsales = 0
        


        for line in infile:
          sales = float(line)
          totalsales += sales
          count += 1
          avgsale = totalsales/sales


        return totalsales, avgsale
        
    print("Total Sales: $", totalsales)
    print("Average Sale: $", avgsale)
        infile.close()

2

u/FrangoST 19d ago

I see quite a few errors with this.

Remove the try:except: parts and only add them when everything is working correctly. Until then, add prints to parts where you think there might be a mistake (e.g. print the sales on every loop, the count, and other things you are calculating).

From this I can see an indentation error and an arithmetic error that comes both from wrong variables being used in the calculation and incorrect indentation (not related to the error I mentioned).

Good luck.

1

u/x_slysuccubus_x 20d ago

also in the file it is a price per line

ex:

1.75

2.65

1.86

2.04

ect but no line spaces

1

u/x_slysuccubus_x 20d ago

okay so i need to do --- except FileNotFoundError: -- ?

1

u/WorriedTumbleweed289 20d ago

I would return after print error and unnest the else clause. In the for loop, use print statments for the line and sales to debug line by line to see what is going on.

1

u/x_slysuccubus_x 20d ago

that is above my brain cells I know nothing. my teacher does not teach he has you transcribe what he does and does not explain why things do what they do

1

u/WorriedTumbleweed289 19d ago

Read and learn the python tutorial. you can change the version on the top.

https://docs.python.org/3/tutorial/index.html

1

u/Chorizo_n_eggs 20d ago

Not seeing any call to the functions. Not seeing any return in CalcTotal. You said it returns two values

Do you get an error?
Is this all the code?

1

u/x_slysuccubus_x 20d ago

I am a student so I have no idea wtf I am doing. so after count in calc sales i need to ad -- return totalsales, avgsales -- correct? also no thats not the whole code the call to the functions are in the main which seems to work

import math
import sys


def Main():
    choice = "go"
    while choice != "x":
        print("===========================================")
        print("*           Pokemon Card Sales            *")
        print("===========================================")
        print("")
        print("C: Calculate Card Total and Average Sales")
        print("D: Display Sales")
        print("X: Exit")
        print("")


        choice = input("Enter Menu Selection: ").upper()
        
        if choice == "C":
            CalcTotal()
        if choice == "D":
            DisplayCardSales()
        if choice == "X":
            sys.exit()




def DisplayCardSales():
    try:
        infile = open("cards.txt",'r')
        i = 0
        for line in infile:
            print((i+1), ": $", line)
            i = (i + 1)
        infile.close()
    except:
        print("Error")
    
        
def CalcTotal():
    try:
        infile = open("cards.txt",'r')
    except:
        print("Error")
    else:
        count = 0
        totalsales = 0
        
        for line in infile:
          sales = float(line)
          totalsales = totalsales + sales
          count = count + 1


          return totalsales, avgsales


        avgsale = totalsales/sales
        print("Total Sales: $", totalsales)
        print("Average Sale: $", avgsale)


        infile.close()


Main()

4

u/RngdZed 20d ago

anything AFTER the return will not run, make sure the return statement is last and outside the forloop

1

u/Chorizo_n_eggs 19d ago edited 19d ago

As noted by RngdZed. Once a return is made in a function, that function is done. Nothing after it will run. So move your return to the end. Also, you're returning 2 values but you are not assigning the function call to a variable so those values aren't going to do anything but be discarded. They will also be returned as a tuple (if you assign the function result to a variable) which is a whole other ball game for you.

1

u/x_slysuccubus_x 19d ago

i have do idea what tuple means and idk what you mean by assigning a function call to a variable? isnt that what I did in the main?

1

u/Chorizo_n_eggs 19d ago edited 19d ago

You just called the function. You called CalcTotal and when the function returns the values, what then? If you say result = CalcTotal() then result will contain the values returned by the function as a tuple. So for example if your values are 2 and 5, result will be (2,5)

2

u/Agawell 20d ago

Are you actually calling the functions?

1

u/Lion2471 20d ago

CalcTotal is supposed to return two values. Did you do that?

1

u/RngdZed 20d ago

on top of what everyone else said, id use with open as a standard of opening files. also theres a weird indent after for line in infile: .. it has only 2 spaces indent, it wont affect the code running, but it's not proper pep8, sorry to bother you with that one lol.. your IDE should yell at you for inconsistent indentation, unless its a copy paste error idk

1

u/Discordbothost 20d ago

one concrete bug in CalcTotal: avgsale = totalsales/sales divides by the last line's price, not by how many lines you read. use count instead:

avgsale = totalsales / count

also that bare except: print("Error") is why you only see "Error" — cards.txt is probably not in the cwd when you run it. temporarily drop the try/except or do except Exception as e: print(e) so you see FileNotFoundError vs ValueError.

1

u/throwaway6560192 20d ago

Remove the try: ... except: print("Error") stuff. It's only obscuring the true error. Then run it and read the error message.