#๐Ÿ”’ Int inside of functions

10 messages ยท Page 1 of 1 (latest)

prime spindle
#
#!/bin/python3

import math
import os
import random
import re
import sys

Positive = 0
Negative = 0
Zero = 0
def plusMinus(arr):
    for number in arr:
        if number > 0:
            Positive  = Positive + 1
        elif number < 0:
            Negative = Negative + 1
        else:
            Zero = Zero + 1


if __name__ == '__main__':
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

print(Positive/n)
print(Negative/n)
print(Zero/n)
  File "/tmp/submission/20240713/00/11/hackerrank-881e6285da71ad60d3222d71a873259f/code/Solution.py", line 27, in <module>
    plusMinus(arr)
  File "/tmp/submission/20240713/00/11/hackerrank-881e6285da71ad60d3222d71a873259f/code/Solution.py", line 17, in plusMinus
    Negative = Negative + 1
               ^^^^^^^^
UnboundLocalError: cannot access local variable 'Negative' where it is not associated with a value
novel lightBOT
#

@prime spindle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

chilly orbit
#

add global Negative as the first line of your function

#
#!/bin/python3


Positive = 0
Negative = 0
Zero = 0


def plusMinus(arr):
    global Positive
    global Negative
    global Zero

    for number in arr:
        if number > 0:
            Positive = Positive + 1
        elif number < 0:
            Negative = Negative + 1
        else:
            Zero = Zero + 1


if __name__ == "__main__":
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

print(Positive / n)
print(Negative / n)
print(Zero / n)
prime spindle
#

thx

#

never knew about global

#

it works

#

!close

novel lightBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.