Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Short code with loop, function and list isn't working.Much appreciated if you help. (New at Python)

Just started learning python, so I’m very thankful for anyone who can help.

Anyways the task is to define a function that takes a list of numbers and returns 3 values – how many positive numbers, negative numbers and zeroes there are in the list.

The main program I need to use a loop that gets the user to input however many numbers he wants (must be between 3 and 6, and this has to be checked). these numbers that the user inputs are to be added to a list. Then I have to call a function that uses the list as the argument and then print the results that the function returns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using a loop is obligatory.

def three(z):
    np = 0
    nn = 0
    zeroes = 0
    
    for y in z:
        if x<0:
            nn+=1
        if x>0:
            np+=1
        if x==0:
            zeroes+=1
    
    print('there are ', np, ' positive numbers\nthere are ', nn, ' negative numbers\nthere are ', zeroes, ' zeros')
    
    return (np, nn, zeroes)

num_list = []

a = 0
n = eval(input('input a number (bigger than 3, smaller than 6): '))

while n>3 and n<6:
    if a < n:
        x = eval(input('input a number: '))
        num_list.append(x)
        a+= 1
    else:
        break
        
three(num_list)

I made a loop and a function, but I’m pretty sure I messed up at the loop or somewhere else because it looks like I’m using a lot of variables and it looks more complicated then it should probably be.

>Solution :

First, you should avoid using eval to get the numerical value of the user input. Ignatius Reilly left a good link to explain why in a comment. Instead, just cast the string input to int using int(input(...)) instead.

Second, the issue is that you are comparing x to zero. x is not defined in your function, so it looks outside the function scope and then pulls what you defined as x there, which is the last user input from x = eval(input(...)). So a user that inputs -1, 2, 0, 4 will return (4, 0, 0) because it just compares 4 to 0 four times rather than each individual input. You made a simple mistake here and should’ve used y in your if statements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading