I have the following code which should return a list of integers; this list will have the size specified in the passed parameter
In case the parameter passed to it is not of type int, the function will throw a TypeError exception with the message
"A TypeError has occurred"
In the event that the parameter passed to it is of type int, but not positive, the function will throw the ValueError exception with the message "A ValueError has occurred"
If the parameter passed to it has the correct type and value, the function will ask the user to input as many numbers as the parameter value indicates and will form a list with them, adding the elements according to the order in which they are read. In case the user makes a mistake when entering the values, the function will handle the exception that occurs and continue asking the user for numbers until it has all the ones it needs
def tratamiento_excepciones(number):
while number == True:
if number == int and number < 0:
entrada_datos = int(input("Introduzca un número: "))
new_list = []
new_list.append(entrada_datos)
return new_list
elif type(number) != int:
raise TypeError("Se ha producido un TypeError")
elif number < 0:
raise ValueError("Se ha producido un ValueError")
if __name__ == "__main__":
print(tratamiento_excepciones(5))
The doubt is that it continuously returns None, I have tried with this fragment and with another that I have built that I can attach but it does not add the elements in the corresponding list
You have several errors:
The loop
while
doesn't make sense the way you use it. Inside the loop you should only ask the user for integers and add them to the list, not validate the argumentnumber
. Also, you must decrementnumber
on each iteration or else you will have an infinite loop. The list must be defined outside the loop or else it will only contain the last element entered.The check
number == int
is never going to be true, you compare an instance ofint
with the class/typeint
. They will always be different objects. You must useisinstance()
. This causes the function to returnNone
(default return of any function) or throw an exception.The
return
must occur at the end of everything, outside the loopwhile
, when the list is complete.The code could be something like this:
hello friend is that you are asking
And number is equal to the number you entered. It is not equal to "True" unless you type "True". I also suggest you review the code and if it is what you are looking for.
Greetings.