def odd ():
for i in odd:
if i % 2 == 1:
print (i)
Here I am trying to take an input of numbers from user and then print if that is an Odd number, but getting errors, can someone please help me to understand what I am doing wrong here, first thing I am getting name ‘odd’ is not defined.
When you do def odd()
it creates or defines a function with the name odd.
Now in that function,
When you do for i in odd:
it starts a loop for variable odd which you haven’t defined or initialized.
For your code odd is probably a list of numbers, so you can define it like:
def odd():
odd = [2,4,5,6,7,13,45,66,78,79,89,98] # Random list of numbers assigned to variable odd
for i in odd: # Command to loop through the list odd one by one starting from index [0]
if i%2==1: # Condition to check if the number in the list odd is odd
print(i)
To call or activate the function you would have to do odd()
.
This will print the numbers the odd numbers in the list odd
.
But to implement the func() on list from user you would have to define it as a parameter for the function.
def odd(odd): # odd {inside the()} is a parameter/argument required for the func.
for i in odd:
if i%2==1:
print(i)
now you can pass the user-generated list as an argument for the function odd.
user_list = [2,4,5,6,7,13,45,66,78,79,89,98]
odd(user_list)
This will also print out the odd statements.