I am new so doing baby steps. Created a simple program of averaging heights.
No error message but return value is: <function Students.total_heights at 0x00000207DC119750>
I didn't need to create 'class.methods' with this script BUT am trying to do this to get the feel of how this works.
Two questions with this.
Material source to read more? Been looking through 'stackoverflow' about my question. I have seen similar questions but the responses are from the perspective of people who have been doing this for years. A lot of heavy terminology. I have been coding for 6 weeks. Working hard and reading a lot.
The script contains a 'main' method that is outside the 'class' structure. Main calls to a method within the class structure. The method within the class works corectly. Great! I now want to 'return' the output of that method so I can use it in the main method.
Thanks.
class Students:
def __init__(self, list_num):
self.heights = list_num
def convert_str_list(self):
for n in range(0, len(self.heights)):
self.heights[n] = float(self.heights[n])
return self.heights
print(f"Checking: changing str to float {self.heights}")
def main():
student_heights = input("Input a list of student heights, in cms, with commas inbetween.").split(",")
print(f"\n\t\tChecking: Student heights straight after removing commas "
f"and converting to a str list: {student_heights}")
str_list = Students(student_heights)
str_list.convert_str_list()
print(Students.total_heights)
main()
I assume that you are trying to convert the inputted string into a list and would like to have it as a function. The current code you are giving doesn't run since the iteration also includes invalid characters like "[", "]", and ",". Here is a solution I guess for your code:
class Students:
def __init__(self, heights:str):
self.heights = heights
def convert_str_list(self):
total_heights = []
for n in range(len(self.heights)):
try:
total_heights.append(float(self.heights[n]))
except ValueError:
continue
self.heights = total_heights
print(f"Checking: changing str to float {self.heights}")
return self.heights
def main():
student_heights = input("Input a list of student heights, in cms, with commas inbetween.").split(",")
print(f"\n\t\tChecking: Student heights straight after removing commas "
f"and converting to a str list: {student_heights}")
str_list = Students(student_heights)
str_list.convert_str_list()
print(str_list.heights)
main()
Make sure to not forget using the same variable you initiated class with to retrieve the variables inside it. You could also use a try catch blocks to process the individual characters from the string or to just use the builtin function eval() to get the list with floats:
student_heights = eval(input("Input a list of student heights, in cms, with commas inbetween."))