Home > Blockchain >  Python program not working - simple mathematic function
Python program not working - simple mathematic function

Time:12-03

cat Prog4CCM.py
numberArray = []
count = 0

#filename = input("Please enter the file name: ") 
filename = "t.txt" # for testing purposes
file = open(filename, "r")


for each_line in file:
    numberArray.append(each_line)



for i in numberArray:
    print(i)
    count = count   1

        
    
def findMaxValue(numberArray, count):
    maxval = numberArray[0]
    for i in range(0, count):
        if numberArray[i] > maxval:
            maxval = numberArray[i]
    return maxval


def findMinValue(numberArray, count):
    minval = numberArray[0]
    for i in range(0, count):
        if numberArray[i] < minval:
            minval = numberArray[i]
    return minval


def findFirstOccurence(numberArray, vtf, count):
    for i in range(0, count):
        if numberArray[i] == vtf:
            return i
            break
        i = i   1


# Function calls start


print("The maxiumum value in the file is "  str(findMaxValue(numberArray, count)))
print("The minimum value in the file is " str(findMinValue(numberArray, count)))

vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at " str(findFirstOccurence(numberArray, vtf, count)))

This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array.

It should return a proper value, but just returns "None". Why might this be?

The file reading, and max and min value all seem to work perfectly.

CodePudding user response:

At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt

CodePudding user response:

You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error with adding one to the iterator and use break, the for loop will do that for you.

The correct code would look like this:

...

def findFirstOccurence(numberArray, vtf, count):
    for i in range(0, count):
        if numberArray[i] == vtf:
            return i
        #     break # <==
        # i = i   1 # It's errors
    return "Can't find =("


# Function calls start


print("The maxiumum value in the file is "  str(findMaxValue(numberArray, count)))
print("The minimum value in the file is " str(findMinValue(numberArray, count)))

vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at " str(findFirstOccurence(numberArray, vtf, count)))
  • Related