Number of Odds and Evens in a List Function - Python - python

I am trying to create a function called "odd_even" which takes my already created list (named "nums") and determines the number of odd and even numbers, and then returns the variables to me. However when I run this code I get:
NameError: name 'odd' is not defined
How do I fix this? If you can give me any useful pointers on the "return" function that would also be greatly appreciated.
import random
def main():
nums = []
for x in range(10):
nums.append(random.randrange(1,26))
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd
return even
odd_even(nums)
print("List had ", odd, "odds and ", even, "evens.")
main()

You are doing 2 things wrong.
First, you are trying to return two values but on different lines. You cant do this, to do this, do so as a tuple:
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd, even
Second, you call the function but dont store the value(s) of return. So you need change:
odd_even(nums) to odd, even = odd_even(nums)
By trying to execute:
print("List had ", odd, "odds and ", even, "evens.")
The main() is looking for variables odd and even, but they dont exist in main(), they exist locally in odd_even() (hence why you are calling return as to return them to the calling function. The reason you only see an error with respect to odd is because it is the first variable in that print() that the interpreter encounters an error on.
The only way around this without correct use of return is to declare them as global. But that is a bad idea so don't do that, keep things local on the stack!

You have some syntactic errors. Python...unlike many programming languages is whitespace conscious. This means you need to be careful with your indentation and spacing. More traditional languages like Java and C use brackets {} to define a scope, and semicolons ; to figure out line termination.
Perhaps you copied it poorly, but from what I see, it appears as though you are defining the function odd_even() within the function main(). That is, the definition of odd_even() is tabbed to the right, which means that its definition is within the function main. I assume that you want main to call the function odd_even(). Thus, you must tab it back over to the left so that it is at the same indentation level as main().
For this reason I use horizontal lines (see below) to clearly outline the scope of functions. This is good for me when I write in Python because otherwise it can be very unclear where one function ends, and where another begins.
Also, it appears as though you have 2 return statements. If you want to return 2 values, you should encompass it within an object. To get around this, there are two simple solutions that come to mind. You can make the odd_even() function access global variables (not recommended)...or you can return an array (any number of values back) or a tuple (exactly 2, but this is python specific).
Below is an implementation of both:
import random
# Declare global variables outside the scope of any function
odd = 0
even = 0
#-------------------------------------------------------------------------------
def main():
nums = [1,2,3,4,5,6,7,8,9,10]
return_value = odd_even(nums)
# Get the individual values back
o = return_value[0]
e = return_value[1]
# You can use the global variables
print("List had ", odd, "odds and ", even, "evens.")
# Or you can get the array back
print("List had ", o, "odds and ", e, "evens.")
#-------------------------------------------------------------------------------
def odd_even(given_list):
# This means we are referencing the variables odd and even that are global
global odd
global even
# Loop through the array
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return [odd, even]
#-------------------------------------------------------------------------------
main()

Related

Changing a variable outside of a if statement using curses

This could be super simple but I can’t think of a solution. I want to be able to change a variable outside of a if statement. I have this in a try loop.
For example:
Try:
X = 0
If char == ord (‘w’):
X += 1
The only problem is that once it runs again the value of x will return to 0. How do I reassign the value of x to be the new number?
assign as an argument of the function what you want to change from one side and inside of the function make sure to use "return" the value that you want to be changed.
Once done push the same returned as an argument, with a loop most likely.
def function_name(x):
x +=1
print('New X Value',x)
return x
for i in range(5):
function_name(i)

Turning Python code into a function

I am new to Python functions and am just practicing on my end. I wrote some basic code that asks user for a number input, 9 times, and then outputs either True or False based on > 100 or < 100.
This code works fine:
list_1 = []
count = 0
while count < 10:
text = int(input('list a number:'))
if text < 100:
list_1.append(True)
else:
list_1.append(False)
count = count + 1
print(list_1)
Now I want to convert that into a function (using For loop instead, for something different). I tried a few versions and can't get it, nothing happens when i run this:
def foo():
list_1 = []
text = int(input('list a number:'))
for x in range(10):
if text > 100:
list_1.append(True)
else:
list_1.append(False)
return()
2 questions:
How do I write that function so it is actually useful and returns True or False?
Can someone show me a basic example of how using a function in this instance could be worthwhile? Like how could I separate it from the first piece of code so it's actually useful in a different way?
I'd like to branch out from just writing pieces of code, to organizing it in a more efficient way
Thanks
It looks like you have an error in your return value for foo().
Make sure you return the list out of your function. for example:
def foo():
list_1 = []
for x in range(10):
text = int(input('list a number:'))#this should be inside the loop
if text > 100:
list_1.append(True)
else:
list_1.append(False)
return(list_1) #you are passing list_1 after your for loop
bool_list = foo() #will pass return value in function
#print(list_1) this will throw an error!
print(bool_list) #bool_list was list_1 in foo()
Reading up on namespaces, it is critical for understanding funcitons. When you launch foo(), it will run its own code, but if you don't pass objects with a return value, you can't use it in other places.
Functions are absolutely essential for well maintained code. Anytime an operation is needed repeatedly, functions cut down on unnecessary lines of code. They also offer versatility when the same operation needs to be run many times but in slightly different ways. You could pass an argument through foo() specifying how many times you want to run through your for loop, for example.
There's an almost unlimited number of ways that you can use functions. The main driver in your decision is whether or not you can reuse functionality or if it simplifies your code. So in essence, can I build this into a building block is the question you should ask yourself.
So in your example, say you have to take input in several different scenarios or you have to maybe evaluate a number of lists and provide print output.
You could separate things based on that:
def take_input(list):
count = 0
while count < 5:
inputlist.append(int(input('list a number:')))
count += 1
def print_output(list):
outputlist = []
for input in list:
if input < 100:
outputlist.append(True)
else:
outputlist.append(False)
print(outputlist)
inputlist = []
take_input(inputlist)
print_output(inputlist)

Name 'absolute value' not defined in Python

So I am really knew to coding, this is problem occurred about 5 minutes after I started. So I am currently doing this Coursera course made by an associate professor at Wesleyan (https://www.coursera.org/learn/python-programming-introduction). One of the exercises was:
Write a function absolutevalue(num) that computes the absolute value of
a number. You will need to use an 'if' statement. Remember if a number is less than zero then you must multiply by -1 to make it greater than zero.
So I figured my answer should be something like this:
absolutevalue(num):
""" Computes the absolute value of a number."""
if num >> 0:
absolutevalue =num
print(absolute value)
elif num<< 0:
absolutevalue == -1*num
print(absolutevalue)
else:
print("Absolute value is 0")
But when I run the code the console keeps saying:
Traceback (most recent call last):
File "", line 1, in
absolutevalue(5)
NameError: name 'absolutevalue' is not defined
For the past hour, I have been trying to fix the problem, yet I don't know how.
Could someone please help me, and keep in mind this is one of my first times trying to code something.
Thanks
A few errors:
Your def statement is missing. Normally a function definition should start with a line like def absolutevalue(num) rather than just absolutevalue(num).
You're using double comparators >> where you should be using single ones >. The former is a bit-shifting operator.
Within the function, you're using a variable with the same name as the function itself: absolutevalue. It's not necessarily wrong, but definitely not particularly handy.
Your function doesn't actually return the absolute value; it just prints it.
Edit: now that your question has been edited to use code blocks: your indentation is missing. :)
Hope that helps!
Function definitions in python need to start with def. Function blocks also need to be indented correctly, for example:
def absolutevalue(num):
""" Computes the absolute value of a number."""
if num > 0:
return num
elif num < 0:
return -1 * num
return 0
print(absolutenumber(-1))
print(absolutenumber(1))
print(absolutenumber(0))
>>> 1
>>> 1
>>> 0
You need to define the function absolutevalue and pass num into it. If you need to return the value instead, use return rather than print()
def absolutevalue(num):
if num > 0:
print(num)
elif num < 0:
abs_value = num * -1
print(abs_value)
else:
print("Absolute value is 0")

Issue with calling a function inside a while loop

I don't know if this is a simple question or not, but I couldn't find anything on it so I figured I would ask it.
I try to call a function in a while loop but it keeps on returning the same result until the condition is completed. The function main() is imported from another file and return a list with two elements [a,b].
Those two elements are generated randomly, therefor they should change after every step. The function works perfectly fine if I call it on its own.
Here is my code so far, I hope someone can help me:
I thought there was something wrong with my list x so I tried to delete it after every step, but it doesn't change anything.
from some_module import main
def loop(variable):
i = 0
while i <= 5 :
x = main(variable)
a ,b = x[0], x[1]
print a, b
del x[:]
i += 1
The code for main() is :
def main(file):
iniciate(file)
obtain_neighbours(initial_solution())
get_all_costs(get_all_solutions())
return get_best_solution()
And the random choice appears in the function initial_solution() :
#those list are being updated at every step
So = []
I_assign = []
I_available = ['1','2','3','4',...,'n']
def initial_solution():
while len(I_available) != 0:
update_I_assign()
random_task = random.choice(I_assign)
So.append(random_task)
I_available.remove(random_task)
return So
def get_best_solution():
if min(i for i in all_cost) < calculate_cost(fill_station(So)):
best_solution = solutions[all_cost.index(min(i for i in all_cost))]
return [min(i for i in all_cost),best_solution]
else:
best_solution = fill_station(So)
return [calculate_cost(fill_station(So)),best_solution]
It's pretty hard for me to show the rest of the code here because it's quite long. Hope the update helps you understand.

Why doesn't my function to swap variables swap variables?

First, I have this function:
def change_pos(a, b):
temp = a
a = b
b = temp
print 'Done'
And I call it in another function but it just print 'Done' and do nothing.
I write the code directly:
a = 1
b = 2
temp = a
a = b
b = temp
It works fine. Any suggestion here?
Second, this is my code
def check_exception(list):
for element in list:
# Take list of numbers
# \s*: Skip space or not (\t\n\r\f\v), \d: Number [0-9]
# ?: Non-capturing version of regular parentheses
first = re.compile("\s*(?:\[)(\d+)\s*(?:,)").findall(element)
last = re.compile("\s*(?:,)(\d+)\s*(?:\])").findall(element)
# Convert string to integer
first_int = map(int, first)
last_int = map(int, last)
# Check and code above works
i = 0
print first_int[i]
change_pos(first_int[i],first_int[i+1])
print first_int[i+1]
print len(first_int)
#print type(first_int[0])
# Sort
# Error: list index out of range at line 47 and more
i = 0
while i < len(first_int):
if first_int[i] > first_int[i+1]:
change_pos(first_int[i], first_int[i+1])
change_pos(last_int[i], last_int[i+1])
i += 1
# Check exception
j = 0
while j < len(last_int):
if last_int[j] < first_int[j+1]:
return false
break
else:
j += 1
continue
return true
And I see: IndexError: list index out of range at conditions after # Error
Thanks for any help. :)
Your change_pos function does nothing useful as it only swaps the variables inside the function, not the variables that was used to call the function. One method of accomplishing what you want is this:
def change_pos(a, b):
print 'DONE'
return b, a
and then using it becomes:
a, b = change_pos(a,b)
Or even without a function:
a, b = b, a
Secondly, I'm sure you can figure out why you're getting an index error on your own. But here's why anyways. Arrays are zero indexed and you are using the length of last_int in your while loop. Now imagine last_int has a length of 5. That means it has index values ranging from 0-4. In the last iteration of the loop you are attempting to access last_int[5] in your if statement (last_int[j+1]) which of course will give you an index error.
You may have been told that variables are locations in memory with data in it. This is not true for Python. Variables are just names that point to objects.
Hence, you can not in Python write a function such as the change_pos function you attempt to write, because the names you change will be the names used in the function, not the names used when calling.
Instead of this:
a = 1
b = 2
change_pos(a, b)
You will have to do this:
a = 1
b = 2
a, b = change_pos(a, b)
The function needs to look like this:
def change_pos(a, b):
return b, a
This give you a hint that there is an easier way, and indeed there is. You can do this:
a = 1
b = 2
a, b = b, a
So no need for a function at all.
Since you actually want to swap integers in a list, you can make a function like this:
def change_pos(lst, p):
lst[p], lst[p+1] = lst[p+1], lst[p]
But I don't think that adds significantly the the readability of the code.
Also your usage of this is prefixed with the comment #sort. But your code does not sort. It's a bit like a half-assed bubble sort, but I don't know why you would want to do that.
Numbers are immutable in python. His when you pass them to a function, the function works with copies of the variables. This can be tricky if you try this with mutable types like Lists. But python has this function covered with some neat syntax tricks.
a, b = b, a
This swaps two variables with no need for any additional functions.

Categories