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

Question:

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.

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 numbersnthere are ', nn, ' negative numbersnthere 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.

Asked By: Bing Chilling

||

Answers:

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.

Answered By: Michael Cao

Use a for-in-range loop to execute code n times.

Use int() to convert user input to an integer, not eval().

n = int(input("Input a number between 3 and 6: ")
if 3 <= n <= 6:
    nums = []
    for _ in range(n):
        x = int(input("Input a number: "))
        nums.append(x)
    print(three(list))
else:
    print("That's out of the range")
Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.