Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error in my code
#1
Hello everyone,
I am working on my school homework that is quite easy for some professional, but I have troubles with few things that I tried to change but obviously I can't make them work.
p=[]
def number():
    c=1
    try:   
        x=int(input("Insert integer number:"))
        p.append(x)
        for z in p:
            nn=p.sort(p) #nn=new number
        print(p,"->",nn)
        
    except ZeroDivisionError: 
        print("You cant divide by Zero")
        c=0
    except ValueError:
        print("You didn't insert integer number")
        c=0
    return c

while c!=0:
    number()
The point of this exercise is to insert numbers until we insert 0, than every inserted number - every digit of this number sort in order from the biggest to smallest.

After making this, the program tells me
Output:
1# name "c" is not defined - when I define c as 1 (c=1), next problem income 2# File "/Users/adam/Desktop/python/kod2.py", line 12, in cisla nc=p.sort(z) TypeError: sort() takes no positional arguments
- after 2nd problem I tried to delete "p" from parentheses and than my program did this:
Output:
Insert integer number: --I inserted 23--- program did this: [23] --> None
Does anyone have any solution how to solve this? I tried almost everything...
Reply
#2
The final result is None because list.sort() sorts in place, meaning no value is returned. When a variable is set based on a function/method that returns nothing, it is set as None.

In general, this needs some refactoring before it will work. Consider these questions:
  • Why sort the code for every new addition?
  • Does list.sort() take any arguments? Which ones? (Research standard library documentation.)
  • If variable c is instantiated in number(), how would the while loop outside of number know about c? Is that proper coding or just a quirk of Python? And, if it's a quirk, how would the loop know about c changing to a different value? (Think about scope.)
  • Where is there any division in number()?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020