0

How do i creat the .len function in code

This seems right but it keeps giving me errors not sure what im doing wrong x=[6,8,9,10,8] num=0 y=(num+1) while num>=0 if x[y] not >=0 or not <=0 print(y) break else: num+=1

27th Nov 2022, 9:28 PM
Brayden Stevens
4 Antworten
+ 3
What output do you expect? And what is your if-statement supposed to test? A number is always >= 0 or <= 0.
27th Nov 2022, 9:49 PM
Lisa
Lisa - avatar
+ 1
# Hi, Brayden Stevens ! # Maybe you can try something like this: def my_len(lst): i = 0 while True: try: lst[i] except IndexError: return i else: i += 1 x = [6, 8, 9, 10, 8] print(my_len(x))
27th Nov 2022, 10:29 PM
Per Bratthammar
Per Bratthammar - avatar
0
# Hi, Brayden Stevens ! # It's more easy to write: ... if not x[y] >= 0 or not x[y] <= 0: print(y) ... # as the following: ... if x[y]: print(y) ...
27th Nov 2022, 11:07 PM
Per Bratthammar
Per Bratthammar - avatar
0
1. num starts as 0 and only gets incremented, so is always >= 0. What exactly did you intend with "while num >= 0"? 2. What is "y" for? 3. Double check the indentation of the "else" part. IMHO, the code is way overcomplicated for this task. A clean approach is to just iterate on the items and increment a counter. Another hint: use meaningful variable names. It helps a lot in debugging and improving your code.
28th Nov 2022, 11:31 AM
Emerson Prado
Emerson Prado - avatar