How to increment list index in a function - python-3.3

im trying to print the next item in the list by using this function I defined below :
List = [1,2,3,4,5]
def next():
i=0
if (i<4):
i= i + 1
print (List[i])
The output of this remains as the second index and doesn't increments no matter how many times i call it
Thanks.

i in the next function is a local variable. It is always initialized to 0 when the function is called.
To make the variable i remember the last value, make it as a global variable.
i = 0 # <--- global variable
def next():
global i # <--- declare `i` as a global variable
if (i<4):
i= i + 1
print (List[i])

Related

Using a returned array in another function

I have a function that returns an array and a second function that is supposed to use this returned array, but the program returns saying array is not defined. How can I fix this problem?
def popt_reader(filename):
with codecs.open(popt, 'r', encoding='utf-8') as data_file:
rows, cols = [int(c) for c in data_file.readline().split() if c.isnumeric()]
array = np.fromstring(data_file.read(), sep=' ').reshape(rows, cols)
return array
def cleaner():
out = []
en_point = 0
for i in range(1,len(array)):
if np.all((array[i,1::] == 0)):
pass
else:
out.append(array[i,:])
en_point += 1
print(en_point)
cleaner(array)
You never call the function that returns the array. Try this, just input your own file name
...
filename = "my_array_file_here.array"
array = popt_reader(filename)
cleaner(array)
Variable array is defined within the popt_reader function and is not accessible within the cleaner function.
Add this line of code before cleaner(array) to make it work:
array = popt_reader(filename)
Which will assign output of popt_reader method to array variable.
Note that filename should also be defined beforehand
filename = "path to file"
Just add a signature(parameter) to the function cleaner()
second one should be:
def cleaner(array):
out = []
en_point = 0
for i in range(1,len(array)):
if np.all((array[i,1::] == 0)):
pass
else:
out.append(array[i,:])
en_point += 1
print(en_point)
cleaner(array)

Output should be 4 and 1 but it's returning 4 and 5?

In the following code i am try to find kth factor of given number it's works fine until i created function and pass value to it can anyone tell me why it's returning wrong output.
when you call function only ones no matter what number you pass it shows correct output but when call function two time it returning wrong output.
#Code
fact = []
def factor(N,k):
for i in range(1,N+1):
if N % i == 0:
fact.append(i)
if len(fact)<k:
print(1)
else:
print(fact[k])
factor(12,3)
factor(30,9)
You have defined the fact variable of type list outside your function. So it is being referenced and used by both functions calls when you call it twice.
If you declare fact inside the function the scope of the variable will not persist and the number of times it is called will not be an issue.
def factor(N,k):
fact = []
for i in range(1,N+1):
if N % i == 0:
fact.append(i)
if len(fact)<k:
print(1)
else:
print(fact[k])

How to decide whether to use return or plain variable manipulation inside functions?

I know that return is like throwing out a value at the end of an operation and that it actually stops the iteration or the function in which it's residing. I am having this very simple piece of code where classmethods & class variables are used.
class Person:
number_of_people = 0
def __init__(self, name):
#Person.number_of_people +=1
Person.add_person()
#classmethod
def get_person_count(cls):
return cls.number_of_people
#classmethod
def add_person(cls):
# return cls.number_of_people+1 <-- this does not work. Output is 0 and 0. Why?
cls.number_of_people += 1 #<-- this works
P1 = Person("Rups")
print(P1.get_person_count())
P2 = Person("RG")
print(P2.get_person_count())
As I have commented on the lines, why is my method giving output 0 both times and not the expected output(1 & 2), which is achieved using plan variable modification? Either way, I thought I should be able to use the value given out by add_person method in the init method, since there is no looping involved.
Returning a value does not mean it is modifying a variable. It just means that something can use what is returned. The difference is that cls.number_of_people += 1 changes number_of_people to it's value + 1 (due to the = sign), while return cls.number_of_people+1 takes number_of_people + 1 and "throws" it for something else to use.
What this means is that if add_person returns a value, anytime you call add_person(), there is a value that can be used.
# {...}
def add_person(cls):
return cls.number_of_people + 1
P1 = Person("Rups")
print(P1.add_person()) # prints 1 (number_of_people which is 0, then add 1)
print(P1.add_person()) # still prints 1

Changing global integer variable from inside function scope

I want to have a global variable changed form inside a function. The global variable is an integer. I am getting an error when trying to do so. This is a simplified version of what I am trying to do:
variable = 3
def test():
b = 5
if b > 0:
variable -= 1
print(variable)
else:
print('fail')
test()
Can anyone help me in finding a way to reduce the integer variable by 1 every time the function test runs?
When referring to a variable that's outside of a function that you don't pass in as a parameter, you must declare it as global before referencing it. Add global variable to the beginning of your function and it should work.
variable = 3
def test():
b = 5
global variable
variable -= 1
if b > 0:
print(variable)
else:
print('fail')
test()
test()
test()
test()
test()
test()
output:
2
1
0
-1
-2
-3
Note that the condition will not satisfy to fail because we are not doing anything with b that is equals to 5 forever.

How do you modify a variable that's a value in a dictionary when calling that variable by its key?

n = 3
d = {'x':n}
d['x'] += 1
print(n)
When I run it, I get
3
How do I make n = 4?
You can't do this, at least, not in any simple way.
The issue is very similar when you're just dealing with two variables bound to the same object. If you rebind one of them with an assignment, you will not see the new value through the other variable:
a = 3
b = a
a += 1 # binds a to a new integer, 4, since integers are immutable
print(b) # prints 3, not 4
One exception is if you are not binding a new value to the variable, but instead modifying a mutable object in-place. For instance, if instead of 1 you has a one-element list [1], you could replace the single value without creating a new list:
a = [3]
b = a
a[0] += 1 # doesn't rebind a, just mutates the list it points to
print(b[0]) # prints 4, since b still points to the same list as a
So, for your dictionary example you could take a similar approach and have n and your dictionary value be a list or other container object that you modify in-place.
Alternatively, you could store the variable name "n" in your dictionary and then rather than replacing it in your other code, you could use for a lookup in the globals dict:
n = 3
d = {"x": "n"} # note, the dictionary value is the string "n", not the variable n's value
globals()[d["x"]] += 1
print(n) # this actually does print 4, as you wanted
This is very awkward, of course, and only works when n is a global variable (you can't use the nominally equivalent call to locals in a function, as modifying the dictionary returned by locals doesn't change the local variables). I would not recommend this approach, but I wanted to show it can be done, if only badly.
You could use a class to contain the data values to enable additions. Basically you are creating a mutable object which acts as an integer.
It is a work around, but lets you accomplish what you want.
Note, that you probably need to override a few more Python operators to get full coverage:
class MyInt(object):
val = 0
def __init__(self,val):
self.val = val
def __iadd__(self,val):
self.val = self.val + val
def __repr__(self):
return repr(self.val)
n = MyInt(3)
print(n)
d = {'x':n}
d['x'] += 1
print(n)

Resources