Python function code help

Python function code help
0

#1

I am getting an indentation error, why is that?

start of code

sum = 0

num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

def evenNums(num1,num2):
        if num1%2==0 or num2%2==0:
            sum+=1
            return sum
        elif num1%2==0 and num2%2==0:
            sum+=2
            return sum
        else:

print evenNums(num1,num2)

Thanks


#2

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


#3

Is this Python 3 or 2?

You are getting an indention error, because you have an else: without any code after it. Get rid of that line and your code will run if you are not using Python 3.

Also, s does not have a starting value, so when using +=, you will get an error.


#4

It is 3, I did try having code after the else but it still did not work


#5

With Python 3, you must use parentheses with the print like:

print(evenNums(num1, num2))

#6

I also tried this. The problem is with something else


#7

Although i don’t see any point in this code. I think the problem would be fixed if you declare the sum variable inside the def evenNums.


#8

Your code has several serious issues. Your “else” block is empty. Either delete that block or return something from that block. You cannot update “sum” in your function. You have to make the “sum” global. Like below

sum = 0

num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

def evenNums(num1,num2):
    global sum
    if num1%2==0 or num2%2==0:
        
        sum+=1
        return sum
    elif num1%2==0 and num2%2==0:
        sum+=2
        return sum
    else:
        return sum

print(evenNums(num1,num2))

Note: Using “global” in a code is not suggested or not a good practice. You may declare the sum inside the function like below

num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

def evenNums(num1,num2):
    sum = 0
    if num1%2==0 or num2%2==0:
        
        sum+=1
        return sum
    elif num1%2==0 and num2%2==0:
        sum+=2
        return sum
    else:
        return sum

print(evenNums(num1,num2))

#9

Thank you so much, I understand but my reasoning was that I was only using this along and for practice, plus it is the only variable I am using.


#10

You are welcome. Of course, for practice, you can do what ever you want.
Happy codding!