0

enter image description hereI fail to spot what is wrong on this code yet pytest runs succesfully but I get error messages when CS50 test my code.

I expect my code to raise ValuError, TypeError.Exceptions and be testable meet all requirements such as outputing the right percentage.

Here is My code of fuel.py

def main():
    while True:
        try:
            fuel = input("Fraction:").split('/')
            fraction = convert(fuel)
            if fraction is not None:
                print(fraction)

            percentage = gauge(fuel)
            if percentage is not None:
                print(percentage)
                break
        except ValueError:
            raise ValueError("ValueError")
        except ZeroDivisionError:
            raise ZeroDivisionError("Error")
        except TypeError:
            raise TypeError("ValueError")

def convert(fraction):

              fraction = fraction
              x = int(fraction[0])
              y = int(fraction[1])

              if y == 0:
                raise ZeroDivisionError("ZeroDivisionError")

              fraction = round((x/y)*100)
              if  fraction > 100:
                  raise ValueError("ValueError")

              else:
                  if fraction < 99 and fraction > 1:
                    return fraction
def gauge(percentage):
            fraction = percentage
            x = int(fraction[0])
            y = int(fraction[1])

            percentage = round((x/y)*100)
            if fraction[0] == fraction[1] or percentage >= 99 :
                return "F"
            if percentage <= 1:
                return "E"
            else:
             return str(percentage) + "%"


if __name__=="__main__":
   main()

My Test file is this one. below

import pytest
from fuel import convert, gauge

def test_convert():
   assert convert("3", "4") == "75%"

def test_convert():
    with pytest.raises(ZeroDivisionError):
        convert(["3", "0"])

def test_convert():
    with pytest.raises(ValueError):
        convert(["4", "3"])

def test_gauge():
    assert gauge("7", "7") == "F"

def test_gauge():
    assert gauge("1", "100") == "E"

However the instructions were In a file called fuel.py, reimplement Fuel Gauge from Problem Set 3, restructuring your code per the below, wherein:

convert expects a str in X/Y format as input, wherein each of X and Y is an integer, and returns that fraction as a percentage rounded to the nearest int between 0 and 100, inclusive. If X and/or Y is not an integer, or if X is greater than Y, then convert should raise a ValueError. If Y is 0, then convert should raise a ZeroDivisionError. gauge expects an int and returns a str that is: "E" if that int is less than or equal to 1, "F" if that int is greater than or equal to 99, and "Z%" otherwise, wherein Z is that same int.

  • Please post code as text not image. What's more can you please provide the exact error you're getting? – orhtej2 May 29 '23 at 10:54
  • @orhtej2 The error I'm getting is that my code returns None everytime my code runs. I fail to get rid of it because I want my functions to be both printed when the input meet thier requirments. however my code prints both the functions at the same time. – Tumelo Monaheng May 29 '23 at 11:18
  • Is this exact formatting of your code that you posted? Given [Python has significant whitespace](https://stackoverflow.com/questions/13884499/what-is-python-whitespace-and-how-does-it-work) a lot of this, i.e. positioning of `raise ZeroDivisionError("ZeroDivisionError")` looks off. – orhtej2 May 29 '23 at 11:24
  • @orhtej2 No, my code is fine and well fomatted on VS code (texteditor), just that I'm still a beginner so I was trying to fomat acording to stack overflow as it raised a exception that my code should be indented 4line. – Tumelo Monaheng May 29 '23 at 11:37
  • You can paste your code verbatim and surround it with triple backticks ``` before and after code as explained [here](https://stackoverflow.com/editing-help#code) – orhtej2 May 29 '23 at 11:39
  • thanks I will. besides indentation how can I get rid of double printing the functions at the same time. The gauge function should only print E when fuel percentage is 1%, below and F when the percentage is 99% ,above. Then the convert function should take care of all the percentages. – Tumelo Monaheng May 29 '23 at 11:44
  • Until you post the code exactly as you run it I find it hard to reason about why it is not working. – orhtej2 May 29 '23 at 11:45
  • Done. That's how I ran the code. – Tumelo Monaheng May 29 '23 at 12:00
  • 1
    If you want help, you **HAVE** to fix code formatting in your post. I tried, and still could not get this code to run as-is. I found 2 syntax errors: 1) `if name=="main":`, and 2) `"{:.0". format(fraction)`. You also have a logic error: you don't pass the result from `convert()` to `gauge()`. You get 2 printed results because you print the returns from both functions. – kcw78 May 29 '23 at 13:46
  • @kcw78 can you please check it for the last time . I used these to paste it ``` – Tumelo Monaheng May 29 '23 at 15:03

1 Answers1

1

OK, I looked at the updated code. So many problems...Did you re-run test_fuel.py with pytest? I ask because there are a LOT of errors that testing will uncover. The expectation when posting a question on StackOverflow is that you have done your own testing and are stuck. When I test, I get the following error:

============================================= short test summary info ==============================================
FAILED test_fuel.py::test_gauge - TypeError: gauge() takes 1 positional argument but 2 were given
=========================================== 1 failed, 1 passed in 0.08s ============================================

Note that it says 1 failed, 1 passed, not 1 failed, 4 passed. When I looked closer, I realized you have 3 versions of test_convert() and 2 versions of test_gauge(). That's a problem because only the last version of each function is kept. I added a number to each function name and reran. When I do, I get several errors:

============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - TypeError: convert() takes 1 positional argument but 2 were given
FAILED test_fuel.py::test_gauge1 - TypeError: gauge() takes 1 positional argument but 2 were given
FAILED test_fuel.py::test_gauge2 - TypeError: gauge() takes 1 positional argument but 2 were given
=========================================== 3 failed, 2 passed in 0.10s ============================================

So, next I fixed the function inputs so all of them are 1 list with 2 items. Then another error is discovered:

============================================= short test summary info ==============================================
FAILED test_fuel.py::test_convert1 - AssertionError: assert 75 == '75%'
=========================================== 1 failed, 4 passed in 0.08s ============================================

This occurs because your convert() function returns an integer, and your test function checks for a string. So, I fixed that error and added another test function to check for a return of '75%' from `gauge(["3", "4"]). When I do, all 6 pytests FINALLY pass. That's the good news.

The bad news? It still doesn't pass check50. Why? Because both of your functions don't follow the specification. Re-read and you will find these requirements:

  • convert expects a str in X/Y format as input, wherein each of X and Y is an integer
  • gauge expects an int and returns a str

You send the input as a list of strings to convert(), not as a X/Y string fraction. You also send the input list of strings to gauge()...not the integer returned from convert(). You need to fix these functions in fuel.py, then modify test_fuel.py to match the new inputs. Once you fix that, you will be pretty close. check50 will find 1 more error in your test_fuel.py. I will let you find and fix that on your own.

kcw78
  • 7,131
  • 3
  • 12
  • 44
  • @kwc78 thanks I restructured it according to your feedback and it I manage my code managed to pass the check 50 – Tumelo Monaheng May 30 '23 at 14:18
  • Glad that worked. If it answered your question, please check Accepted Answer for others who read this Q&A in the future. – kcw78 May 30 '23 at 14:57