Getting different values in for loop when using (_) and (i) - python

I'm new to coding and I am wondering if someone could explain to me why I get different values when using "for i in range ()" compared to "for _ in range ()". When I execute:
for i in range (64):
i = i * 2
print(i)
I get 2,4,6,8,10, etc. But when I run:
i = 1
for _ in range (64):
i = i * 2
print(i)
I get 2,4,8,6,32,64,128, etc. I would expect these values but when I run this with the above code. What's the difference between using (i) and (_)?

In the for i in version, i gets reset to the current step in the range during each iteration step. It's equivalent to:
i = 0
i = i * 2
print(i) # prints 0
i = 1
i = i * 2
print(i) # prints 2
i = 2
i = i * 2
print(i) # prints 4
...
When you using for i in range(...), i doesn't keep any memory of its value from the previous iteration. The range object just returns the next value in the sequence, and this gets assigned to i each time.
But when you use for _ in, you're not assigning the i variable each time. This time it's like:
i = 1
_ = 0
i = i * 2
print(i) # prints 2
_ = 1
i = i * 2
print(i) # prints 4
_ = 2
i = i * 2
print(i) # print 8
...
This time, i keeps its value from the previous iteration, because the range element is being assigned to _ rather than i.
There's nothing special about _, it's an ordinary variable name. But by convention we use this when we need to assign to a variable but aren't going to use it further.

The difference between for i in range(64) and for _ in range(64) is the use of the loop variable.
In for i in range(64), i takes on the values of the numbers in the range from 0 to 63. This means that each time the loop is run, i is updated with the next number in the range.
In for _ in range(64), the loop variable _ is a placeholder that does not receive a value from the range. This is used when you want to run the loop a certain number of times, but you don't need to use the values generated by the range.
In simpler terms, i is used to keep track of the values in the range, while _ is just used to run the loop a certain number of times without using the values generated by the range.

Related

In python, executing the runtime input in for loop it prints all values. why?

I am new to python. I have executed for loop with runtime input.
Loop 1:
a = int(input("enter\n"))
for i in range(1, a+1):
print(i)
The output prints all values from 1 to 5.
Loop2:
for i in range(1, 5):
print(i)
The output print the values from 1 to 4.
Please someone explain the different between the above two for loop.
In the range function in python, the last argument is exclusive. This means that it represents the stopping point of the range but is not included in the output. Since the first loop has a+1 as the last argument, a will be included in the output.
Did you have a look at https://docs.python.org/fr/3/library/stdtypes.html#range ?
To keep things easy, range(a, b) will return an iterator that goes from a to b - 1.
Thus, your first loop will print 1 to (a + 1) - 1 = a, and your second loop will print 1 to 5 - 1 = 4.
for i in range(0,5):
print(i)
Prints values from 0 to 4 because when the iteration comes to the value 5 it becomes excluded and it won't print the value.
So we add 1 to the final value(maximum) to print till the value we want.
for i in range(0,6):
print(i)
GIVES:
0
1
2
3
4
5

Get "None" Instead of Zero Value in a Python Function

I want to make a program which puts an array(1x9 has numbers from 0 to 9) in memory and I want to check if an array I created is previously used. There will be 2 functions I will use.
addMemory(list,previousStates) adds the newly created array into memory and checkMemory(list,previousStates) checks if the array is previously used or not. It returns 1 if the array is used and 0 if it is not.
I convert the array to a number by assuming that every element of the array is a digit for a 9-digit number.
Ex: [2,5,3,4,1,6,8,9,7] is stored as 253.416.897. I want to test my functions. First print has the empty memory and the memory is checked and the array is added and the new memory is checked.
The output should have been
0
1
but I get
None
1
Why I get 'None' instead of 0? Can you help please?
def addMemory(newlist,previousStates):
count = 0
for i in range(0,8):
count += count + newlist[i] * 10**(8-i)
previousStates.append(count)
return previousStates
def checkMemory(newlist,previousStates):
count = 0
for i in range(0,8):
count += count + newlist[i] * 10**(8-i)
for i in range(len(previousStates)):
if(previousStates[i] == count):
return 1
return 0
def main():
a = [5,3,4,7,8,9,1,2,6]
previousStates = []
print(checkMemory(a,previousStates))
addMemory(a,previousStates)
print(checkMemory(a,previousStates))
main()
In your checkMemory function, because len(previousStates) is zero at first, your for statement is never executed and hence your function never reaches any return

Don't understand nested For Loop in Python

I don't understand how the i in the 2nd for loop of the code below works.
di = [96, 15, 33, 87]
for i in range(len(di)):
total = di[i]
for j in range(i+1,len(di)):
print(i)
0
0
0
1
1
2
Why is the output 0,0,0,1,1,2. How does i in the 2nd for loop get affected from the first loop? Is there some inheritance? Pardon the newbie here.
len(di) is 4. So the loop
for i in range(len(di)):
will repeat 4 times. Because of the way range works (from lower bound, which is 0 by default if not specified, to 1 below the upper bound), i will be 0 in the first repetition, 1 in the second repetition, and so on. To calculate out how many objects range(x, y) generates, in this case, how often for i in range(x, y)will repeat, you can simply do number of repetitions = y - x. So in this case: len(di) - 0 (default lower bound) = 4.
The loop
for j in range(i+1, len(di)):
print(i)
will repeat the print(i) command len(di) - (i + 1) times. Keep in mind, i is defined by the outer loop. So, during the first loop of
for i in range(len(di)):
i equals 0, so the print(i) command will be executed 4 - (0+1) = 3 times - it will print i(=0) 3 times. In the second loop, iequals 1, so it will be printed 2 times, and so on. So here's whats happening, formatted as code for better readability:
First outer loop:
i = 0
total = di[i] = di[0] = 96
--> first inner loop of first outer loop:
j = i + 1 = 1
i is printed -> prints 0
second inner loop of first outer loop:
j = j+1 = 2
i is printed -> prints 0 again
third inner loop of first outer loop:
j = j+1 = 3 --> since len(di) = 4, the upper bound of range(i+1, len(di)) is reached, so this is the last Repetition
i is printed -> prints 0 again
Second outer loop:
i = 1
total = di[1] = 15
--> first inner loop of second outer loop:
j = i+1 = 2
i is printed -> prints 1
second inner loop of second outer loop:
j = i+1 = 3 -> upper bound of range reached, last repetition
i is printed -> prints 1 again
Third outer loop:
i = 2
total = di[2] = 33
--> first inner loop of third outer loop:
j = i+1 = 3 -> upper bound of range is reached, only Repetition
i is printed -> prints 2
Fourth (and final) outer loop:
i = 3 -> upper bound of range(len(di)) reached, last Repetition
total = di[3] = 87
since j = i+1 = 4, the inner loop does not get executed at all (both bounds of range are equal), so 3 doesn't get printed
end of code.
In programming language, a variable is available for usage within a scope. When you start for loop with a new variable then it would be available for usage until you end it.
As you are beginning the journey to learn python, one of the really good practice is to read official document. https://docs.python.org/3/tutorial/controlflow.html
To help your understanding, try this:
di = [96, 15, 33, 87]
for i in range(len(di)):
print("first loop, i =", i)
total = di[i]
for j in range(i+1,len(di)):
print("second loop, j =", j)
print("second loop, i =", i)
The i is the same in both loops. each time the outer loop runs, it then runs the inner loop until the "for" statement is complete.

while loop isn't working

I have a quick question. I have the following code...
def abc(c):
a = 1
my = set()
while a <= c:
b = randrange(1, 365)
my.add(b)
a = a + 1
print(my)
Now c is in my main function. c is a integer that the user is prompted for. For instance, if c = 10, then as long as a < 10 it will run the while loop and print out the set with 10 numbers randomly generated between 1 and 365. The only problem is that it's not printing out the set my correctly.
a = a+1 should be what you want.
a + 1 just increments the value of a, but does not store it anywhere. So, using a = a+1, will increment the value of a and update the value of a.
The second part: You are generating the random numbers and storing them in a set, and printing them at last. To print each and every element in the list, use:
for i in my:
print i
This will print each value in the set

Random sampling from a set of integers

I am working with python 3.2 and I spent a lot of time trouble shooting this, and I still can't seem to wrap my brain around it.
number = random.randint ( x0 ,xn )
I'm generating a random number. It's purpose is to make my code come at me differently everytime.
For example I have 10 variables of text that I have written. I have solved the problem of not having these variables appear in the same order at each program run.
The issue I have is that they now appear randomly everytime. It picks one out of 10 everytime, instead the first time 10 and next 9. I can't seem to find out how to exclude the previous ones.
thelist = [0]
while i < x
if number in thelist:
>>>repeat<<<
else:
thelist.append (number)
if ( number == x0 ):
>>>something<<<
elif ( number == x1 ):
>>>something<<<
This is what I would imagine the code would look like, everytime you loop one more number gets appended to the list, so that everytime it picks a number already in the list it repeats the loop again until it then has used all the numbers that random.randint can pull.
Here's a shuffle function:
import random
max = 15
x = list(range(max+1))
for i in range(max, 0, -1):
n = random.randint(0, i)
x[n], x[i] = x[i], x[n]
This starts with a sorted list of numbers [0, 1, ... max].
Then, it chooses a number from index 0 to index max, and swaps it with index max.
Then, it chooses a number from index 0 to index max-1, and swaps it with index max-1.
And so on, for max-2, max-3, ... 1
As yosukesabai rightly notes, this has the same effect as calling random.sample(range(max+1), max+1). This picks max + 1 unique random values from range(max+1). In other words, it just shuffles the order around. Docs: http://docs.python.org/2/library/random.html#random.sample
If you wanted something more along the lines of your proposed algorithm, you could do:
import random
max = 15
x = range(max+1)
l = []
for _ in range(max+1):
n = random.randint(0,max)
while n in l:
n = random.randint(0,max)
l.append(n)
From what I understand of your description and sample code, you want thelist to end up with every integer between x0 and xn in a random order. If so, you can achieve that very simply with random.shuffle(), which shuffles a list in place:
import random
x0 = 5
xn = 15
full_range = list(range(x0, xn))
print(full_range)
random.shuffle(full_range)
print(full_range)

Categories

Resources