What does "x" mean in "for x in range(10):"? - python

I'm curious what x means when you look at this:
import random
for x in range(10):
print random.randint(1,101)

x itself has no special meaning, it simply (as a part of the for loop) provides a way to repeat
print random.randint(1,101)
10 times, regardless of the variable name (i.e., x could be, say, n).
In each iteration the value of x keeps increasing, but we don't use it. On the other hand, e.g.,
for x in range(3):
print(x)
would give
0
1
2

For x in range(3) simply means,
for each value of x in range(3), range(3) = 0,1,2
As it is range(3), the loop is looped three times and at each time, value of x becomes 0, then 1 and then 2

Here, x is just a variable name used to store the integer value of the current position in the range of loop and it iterates through out the range of a loop.
Like in for x in range(10):
x iterates 10 times and for instance in your for loop above, during the first iteration of the loop x = 1, then x=2 for the next iteration then, x= 3 and so on...
It is not neccessary to take x as a variable only you can take any variable name like i,a etc...

X is a variable name, so could be any name allowed by python for variable names. As a variable , it’s value will be different every time the loop circle ends, in this particular loop range(10) the value of x will start in 0 and next 1 , and next 2, until reach value of 10
so If you want to print a random int:
for x in range(10):
print(random.randint(x))
also, if it is python3.X, print(x) not print x, second is python2.X

I am coming from a short intro in C, and I was confused by the 'x' as well. For those coming from C,C++,C# etc.:
The 'x in range(10)' is the same thing as doing this in C:
for (x = 0; x < 10; x++)

Related

How to print the value of number during a "x" number of loops?

basically, Im trying to use a while loop to make an arithmetic sequence of numbers the code i made being rather simple:
x=2
while True:
x=x+3
print(x)
but a problem with this code of course is that there is no way i can find the value of x during a certain number of loops and rather this code prints every possible value in the sequence.
Does anyone know how i can make the code in a way that i can choose to print the value of x after a certain number of loops?
The easiest for a known nuber of iterations is a for-loop:
x = 2
iterations = 5
for _ in range(iterations):
x = x + 3
print(x)
This of course can be shortened in this particular example:
x = x + 3 * iterations

Making a for loop print with an index

I made a program which displays a user-provided number of the fibonacci series. I wanted to format it into an indexed list, but I don't what could I use to do so. I found the enumerate() function, but seems it only works for premade lists, whereas mine is generated accordingly to the user.
Do I use a for loop to generate a variable along with the series, then put the variable in the for loop that prints the numbers, like so:
print("{0}. {1}".format(index_variable, wee(n)))
or am I going an entirely wrong road here?
def fib(n):
x = 0
y = 1
for i in range(n):
yield y
tmp = x
x = y
y += tmp
def main():
n = input('How many do you want: ')
for i, f in enumerate(fib(n)):
print("{0}. {1}".format(i, f)
Make a generator that yields the values you want and then pass that to enumerate

For loop in CS Circles section 7C coding exercise: One Triangle

Here is an example of a for loop inside another for loop.
Example
This code prints a 5×5 square of ones.
Note: when we multiply a number X by ten and add one, we're essentially putting an extra 1 digit at the end of X. For example, (1867*10)+1=18671.
for i in range(0, 5):
X = 0
for j in range(0, 5):
X = (X*10)+1
print(X)
Modify the previous program in two ways. First, instead of a square, make it draw a triangle shaped like this: ◤. Second, instead of always having 5 lines, it should take the desired size as input from input(). For example, if the input is 3, then the output should be
111
11
1
So far the code that I have got is:
X=input()
for i in range(0, 3):
X = 0
for j in range(0, 3):
X = (X*10)+1
print(X)
However this code outputs:
1
11
111
When the expected output should be:
111
11
1
I can't seem to figure out how to change my code that I have so far to get the expected output?
This can solve the problem for you:
def test(X,_range):
x = X
for j in range(0, _range):
print int(str((x*10) +1) + ("1"*(_range-1-j)))
test(0,3)
>>>
111
11
1
>>>
In every loop step the number starts with (X*10)+1
In the next step X has changed and you add the digit 1 to the right side
If want to reverse it, you need to use ("1"*(_range-1-j))
The for iterator changes the X content every step. (he don't use i and j, "For" only for step derivation )
Here's the solution:
n=int(input())
for i in range(0, n):
X = 0
for j in range(0, n-i):
X = (X*10)+1
print(X)
As you said, 10*X + 1 means putting extra 1 at the end of X. You need an inverse operation: how to remove the last digit of a number. Hint: integer division. Google "python integer division" to get to pages such as Python integer division yields float.
So, then all you've to do is construct 111...11 of the right length, and then iteratively print and remove digits one by one.
This block is very confusing, here's what happens:
X=input()
Get value of X from input.
for i in range(0, 3):
X = 0
Now set the value of X to 0 three times (overwriting your input)
for j in range(0, 3):
X = (X*10)+1
print(X)
Now X is being set to 1, then 11 and then 111.
Even if you meant to nest the for loops, this wont behave right. Instead, you want to get the i value to loop backwards, using the slice operator [::-1]. You should then make j's range be zero to i.
You'll also need to compensate by increasing the value of both numbers in i's range (otherwise the last line will be a zero) but this will work:
for i in range(1, 6)[::-1]:
X = 0
for j in range(0, i):
X = (X*10)+1
print(X)
Note that I moved the print out of the j loop, as that wasn't how the original code was (and generated the wrong output), pay attention to whitespace. Using 4 spaces is preferable to just 2 for reasons like this.
If you are doing CS Circles than these other answers probably contain code you still haven't come in contact with, at least I haven't, so I'll try to explain it with the knowledge I've gathered so far (couple weeks doing CS Circles).
You are ignoring the first loop and it is where your answer lies. Notice that if you put the print command outside of the loop body it would just output:
111
That it because your second loop is not in the body of the first, so python just loops the first one 3x and than moves to the second loop. Instead it should be:
for i in range(0, 3):
X = 0
for j in range (0, 3):
X = (X*10)+1
print(X)
Now the program outputs:
111
111
111
But you want one less digit each time print is called again. This is achieved by subtracting the value of "i" (since it neatly goes from 0 to 2) from second loop's range tail value. So now you have :
for i in range(0, 3):
X = 0
for j in range(0, 3-i):
X = (X*10)+1)
print(X)
Finally the output is:
111
11
1
Protip: use the visualizer in CS Circles, it helps you better understand the way code is executed in python, and can provide insight to your problems. Best of luck!
The easiest way is to use the following code;
p = int(input())
for i in range(0,p):
x = 0
for j in range(i,p):
x = (x*10)+1
print(x)

Confused as to these loops are equal

Confused as to why one for loop works but one doesn't? Aren't they doing the same thing? Like shouldn't x = y?
x = 3
for i in range(8):
if i > x:
print i, ">", x
i = x
print x
y = 3
for i in range(8):
if y < i:
print y, "<", i
y = i
print y
Both are not same in first you have assignment (every time 3 to i) i = x, while in second you assign counter's i value to y as y = i.
shouldn't x = y?
No, after first loop x remains 3 whereas after second loop y becomes 7.
No.
In the first loop you are not reassigning the value of x. So x is unchanged in the loop.
In the second loop, you are updating y every time y is less than i

Iterate through 2D List, assign each value on a row in the list to a variable, repeat for each row - python

I have a list comprising a number of X,Y values
aList = [[1, 2],[3, 4],[5, 6],[7, 8]]
i.e. X = 1, Y = 2
I need to extract each X and Y value on a row separately, assign those values to an X and Y variable respectively, and then act on the X and Y values.
This should then loop to the next row where the same process would occur again. I'll use print instead of the excessive code that needs to occur after this loop.
i.e. loop starts, X is assigned 1, Y is assigned 2, X and Y are used as inputs in formula, loop ends (and repeat for the remaining values in this list)
aListLen = len(aList)
aListRows = len(aList)
aListCols = len(aList[0])
The following code only extracts values 1 by one in the list
for row in range(aListRows):
for column in range(aListCols):
X = aList[row][column]
print X
adding a Y variable as follows results in an error
for row in range(aListRows):
for column in range(aListCols):
X = a[row][column]
Y = a[row][column+1]
print X
print Y
Looking at it now, I'm not sure the following if/elif loop would work as the X and Y values need to go in a formula together.
I could add an if/elif statement under the 2nd loop, but I'd still need to have a way of forcing the 2nd loop to repeat. (Which brings us back to the original problem anyway)
for row in range(aListRows):
for column in range(aListCols):
if column == 0:
X = aList[row][column]
elif column == 1:
Y = aList[row][column]
How can I force the loop to restart once the X value has been provided?
I assume the loop would then repeat, this time providing the value for Y.
Is there a better way of doing this?
Should point out this is Python 2.7 (so I cannot use anything exclusive to Python 3)
You're looping over the indices of the inner list and adding 1 to them. This will cause an IndexError when column contains the value of aListCols, since len(a[row]) == column+1
I think you are looking for this:
In [17]: aList = [[1, 2],[3, 4],[5, 6],[7, 8]]
In [18]: for X,Y in aList:
....: print "X value is %s, Y value is %s" %(X, Y)
....:
X value is 1, Y value is 2
X value is 3, Y value is 4
X value is 5, Y value is 6
X value is 7, Y value is 8
To assign the variables instead of printing them you could do:
for X,Y in aList:
tempX = X
tempY = Y
At the first iteration tempX will have a value of 1, tempY will have a value of 2. At the second iteration tempX will be 3, tempY will be 4...
You could, instead of a loop, use a recursive function.
Basically, that is a function that calls itself. For example:
def myfunction():
(something happens that wants you to start the function over)
myfunction()
Hence, it will call the function again, forcing the code to go back to the top.

Categories

Resources