I'm new to Python and programming in general.
Let's imagine I have a simple task:
Given 3 numbers from user input, I need to count negative ones and print the result.
Considering what I know about Python at this moment, I can solve it like this:
class ListTooShort(Exception):
pass
def input_check():
temp_list = []
while True:
try:
temp_list = [float(x) for x in input('Input 3 numbers, separated by space: ').split()]
if (len(temp_list) < 3):
raise ListTooShort
if (len(temp_list) > 3):
temp_list = temp_list[:3]
except ValueError:
print('One of given values is not a number, try again.')
except ListTooShort:
print('Not enough values, try again.')
else: return temp_list
def count_negative_numbers(value_list):
counter = 0
for i in value_list:
if (i < 0):
counter += 1
return counter
print('If theres more than 3 numbers,\nlist will be trimmed to 3 first values.')
numbers = input_check()
result = count_negative_numbers(numbers)
print(f'Theres {result} negative numbers in this 3 value list')
or like this:
counter = 0
numbers = [float(x) for x in input('Input 3 numbers, seperated by space: ').split()]
if (len(numbers) >= 3):
numbers = numbers[:3]
for i in numbers:
if (i < 0):
counter += 1
print(f'Theres {counter} negative numbers in this value(s) list')
Both do the trick, but the main questions I have is:
- Would it be better to not complicate the code too much when there's a simple task at hand?
- Is it even worth to make functions for simple things like that or should I just go straight to solving an issue?
- Should I even pay attention to things like that or its better to just "freeroam" without caring that much?