Nested for loop in python when range is not a number - python

I have a hard time understanding this:
for i in range(1, 4):
for j in range(i):
print(i)
when the inner loop's range is a number I understand it, but on the code above, the inner loop is running in range(i). What does that mean? Thank you.

Let's go step by step:
The function range(start, stop, step) has these 3 parameters.
The parameters start and step are optional, but the parameter stop is required.
If you only send one parameter to the function, for example, range(5), the function automatically will set start = 0 and step = 1. Then, range(5) is equal to range(0, 5, 1).
The parameters start, stop and step must be integers. In your case, i is an integer variable that is taking the values 1, 2 and 3, and that's why range(i) is valid.

i is a variable set by the loop it is inside of. i is the number iterating (that's why it's commonly called i). j then iterated through all the numbers up to i.
For example, range(1,4) could be 3 sizes of sweets where each size up has one more sweet (1 packet with 1 sweet, 1 packet with 2 sweets, 1 packet with 3 sweets). The second loop iterates through each of the sweets in the packet (where packet is i and sweet is j). You're then printing the packet you ate.

Related

Python homework regarding prime numbers

My homework is simple, declare a function named printPrimeNumbersTo with a single argument named to
I created the skeleton of the code itself, however, I needed some help from the net.
GeeksforGeeks was the site where I "borrowed" a line of code, which I don't completely understand. (Site: https://www.geeksforgeeks.org/python-program-to-print-all-prime-numbers-in-an-interval/)
My code looks like this (I have comments on nearly every line, describing what I think that the line of code does):
def printPrimeNumbersTo(to):
x = 0
prime_list = [] # This was a string, however, I changed it to a list so I won't have to convert the numbers to a string every time I wanted to append it to the list
for i in range(x, to + 1): # Create a for loop, using the function range an starting the loop at number 0. Add 1 to 'to', because range excludes the end integer
if i == 0 or i == 1:
continue
else:
for j in range(2, i // 2 + 1): # <--
if i % j == 0: # If 'j' is divided by any number in the list and remainder is 0, then the number is not a prime number, which means I can break the loop
break
else:
prime_list.append(i) # Append the prime number to the list
return str(prime_list)[1:-1] # Returns '[2,3,5,7..]', I use the square brackets the get rid of the brackets themselves
print(printPrimeNumbersTo(7)) # >>> 2, 3, 5, 7
The one line I don't understand is marked with an arrow, it's the 8th line of the code.
Why am I dividing the number by 2? And then making it an integer? When I do the calculations, it works, but... where is the logic? Anybody help?
The biggest number which could possibly be an even factor of a number is the half of that number. The integer division operator // produces this number as an integer.
Because of how range works, the ending index needs to be the desired number plus one.
There are two points to note:
the code needs to be indented correctly, in Python indentation matters as it forms the code blocks.
aside from this and specifically adressing the question: the range function that you refer to requires integers otherwise it would throw an typeerror like this: 'float' object cannot be interpreted as an integer .
# this will throw an error
for i in range(1, 10.5):
print(i)
# this will work
for i in range(1, 10):
print(i)
So the reason why the line of code you queried was written like that was to ensure that the upper bound of the range was an integer.
You should also note that the // has a meaning, for example try this:
x = 5//2
print(x)
y = 5/2
print(y)
x is the integer part only (x=2)
y is the full number (y=2.5)
In terms of implementaiton, there are a number of methods that would be better (suggested here):
Print series of prime numbers in python
Dividing the number by 2 is done to reduce the number of iterations. For example, the number 12 you can divide it without a remainder by 1,2,3,4,6. Notice that there is no number bigger than (6) which is 12 / 2. And this goes on with all of the numbers.
16 ---> 1,2,8 no number bigger than its half (8)

How this nesting for loop works in Python?

I can't understand the second for loop:
for k in range(2, n//2 + 1):
print(n%k, end=" ")
How did this formula produce such result?
range() has multiple parameters, first is start, second is stop, third is step (which is not present in this example, so the default value is used: 1).
So your range will generate numbers from 2 to n//2 + 1.
To learn more about range, and for loops:
https://www.w3schools.com/python/ref_func_range.asp
https://www.w3schools.com/python/python_for_loops.asp
The second for loop prints the reminders of dividing n by all of the numbers from 2 to n/2.
check the documentation of range

What does for i in range(1, len(motels)): mean where there are multiple parameters in the range

I am looking at some code but don't understand what passing in multiple parameters means in the range of a for loop in Python
for i in range(1, len(motels)):
The built-in function range takes 1, 2, or 3 parameters.
With only one parameter, it's range(stop) and is equivalent to range(0, stop, 1).
With two parameters, it's range(start, stop) and is equivalent to range(start, stop, 1).
With three parameters, it generates numbers starting from start, with an increment step of step (3rd argument) and stops before the number goes greater or equal to stop. So range(1, 11, 3) will generate 1, 4, 7, 10.
If you have
for i in range(1, len(motels)):
The variable "i" is going to be some number (in this case) from 1 to whatever is the length of the variable motels.
So if len(motels) = 5, and the code looked like this:
for i in range(1, len(motels)):
print(i)
The output would be:
1
2
3
4
By default the first parameter in range is 0. So for example, for i in range(5) is equivalent to for i in range(0, 5).

When using a for loop range with an increment of three, why does the first number 'group' to itself?

We are using the following book in a class I am TA-ing for:
craftbuzzcoder.
In Part 3 (Loop), section Wall & cube, they have a challenge of creating an inverted pyramid.
The following is the book solution:
for j in range(0,10,3):
for i in range (-j, j+1, 3):
for k in range(-j, j+1, 3):
game.set_block(Position(i, j+1, k), 45)
From what I can tell, it seems to be that the first number in the sequence of the respective range (for example, the y-axis/j variable) is counted/grouped by itself rather than by the increment of 3.
Why is this?
tl;dr
I would expect it to increment like this:
Instead it seems to be increment like this:
Why?
The step part of the range is applied after each value is yielded. The first thing in range(0,10) is 0, then you add 3 to get 3, then 6, etc. You are not choosing how large the groups are -- just how much the value is incremented each step.
You need to understand how python range works and this will become easier for you.
range(start, stop[, step])
start is from where you want to start the iteration
stop is at where you want to stop the iteration, exclusive
step means how much you want to add to start
but there is a small catch with this, if step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero and step defaults to 1
So in your case it is working like -
for j in range(0,10,3):
print j
We get -
j = 0 -> add 3, j becomes 3 -> add 3, j becomes 6 -> add 3, j becomes 9, add 3, j becomes 12 which is greater than stop -> exit
More examples of range.

range countdown to zero

I am taking a beginner Python class and the instructor has asked us to countdown to zero without using recursion. I am trying to use a for loop and range to do so, but he says we must include the zero.
I searched on the internet and on this website extensively but cannot find the answer to my question. Is there a way I can get range to count down and include the zero at the end when it prints?
Edit:
def countDown2(start):
#Add your code here!
for i in range(start, 0, -1):
print(i)
The range() function in Python has 3 parameters: range([start], stop[, step]). If you want to count down instead of up, you can set the step to a negative number:
for i in range(5, -1, -1):
print(i)
Output:
5
4
3
2
1
0
As another option to #chrisz's answer, Python has a built-in reversed() function which produces an iterator in the reversed order.
start_inclusive = 4
for i in reversed(range(start_inclusive + 1)):
print(i)
outputs
4
3
2
1
0
This can be sometimes easier to read, and for a well-written iterator (e.g. built-in range function), the performance should be the same.
In the below code n_range doesn't need to be told to count up or down, it can just tell if the numbers ascend or descend through the power of math. A positive value divided by it's negative equivalent will output a -1 otherwise it outputs a 1.
def n_range(start, stop):
return range(start, stop, int(abs(stop-start)/(stop-start)))
An input of 5, -1 will output
5
4
3
2
1
0

Categories