How this nesting for loop works in Python? - 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

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)

Nested for loop in python when range is not a number

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.

What is wrong with the range of j?

This is my first code in python and i completely can't get why the code in 5-th string must contain math.sqrt(i))+1 instead of just math.sqrt(i), because otherwise squares of prime numbers are added to the result.
How to solve this is the easiest and most natural way? Thanks you all in advance
import math
n=int(input("Print n: "))
prime_list=list(range(2,n))
for i in range(2,n):
for j in range (2, math.ceil(math.sqrt(i))+1):
if i % j == 0:
try:
prime_list.remove(i)
except:
j+=1
continue
print(prime_list)
You need j to run all the way through the sqrt of i. Remember that a Python range does not include the terminal value.
For instance, range(2, 7) does not include 7. To find that 49 is not a prime, you need range(2, 7+1), so that j will take on the value 7.
It's because it's Python.
In Python, the syntax range(x, y) generates a sequence of
x, x+1, x+2, ..., y-2, y-1
So if you want a value to be included in the range, the second parameter must be greater than the value (not equal), and that's why you should use math.floor(...) + 1 and cannot omit the +1 part. Otherwise when i is the squate of a prime, j will not iterate over that prime, thus causing the error you're facing.

How do I write an iterative function that computes the sum of the first n odd numbers it returns 1 + 3 + .... + (2n - 1), using a for loop?

Assuming that n is a positive integer
this is my code:
def sum_odd_n(n):
x =1
for x in range(n):
if x%2==1:
continue
return x + 2
but when I run it on Python it gives me the answer 2. Could you help me by telling me what's wrong and what I should do to solve this?
Since you want to find the sum of first 'n' odd numbers, I suggest you to use range function with step=2. I'll elaborate:
def sum_n(n):
addition=0
for x in range(1,2*n,2):
addition+=x
return addition
s=sum_n(5)
print(s)
This gives output as: 25
Here, in range function, 1st attribute provides starting point, 2nd attribute provides the end point, and 3rd attribute gives the Difference between each number in the sequence.
I hope this helps.
There are a few problems with your code.
The first is that you have a return statement inside the for loop.
Secondly, you just visit the first n integers and check which of them are odd. You won't visit all the first n odd integers.
A list comprehension solution solution is as follows.
def sum_odd_n(n):
# sum up the first n odd numbers
return sum([2*i + 1 for i in range(n)])
Check this program it will work:
a=int(input("how many first odd number sum you want"))
x=1
i=0
def OddSum():
global i
global x
while i<=a:
x+=2
i+=1
print(x)
OddSum()

Writing a Python program that finds the square of a number without using multiplication or exponents?

thank you for reading and hopefully responding to my question. I'm stuck trying to write this Python program that finds a number's square without using multiplication or exponents. Instead, I have to get the summation of the first odd n numbers starting from 1. This is what I have so far:
def square():
print("This program calculates the square of a given number")
print("WITHOUT using multiplication! ")
odd = 1
n = eval(input("Enter a number: "))
for odd in range(0, n + 1, 2):
odd = odd + 2
final_square = n + odd
print(n, "squared is", final_square, ".")
EDIT: Hi guys, I can't do 4 + 4 + 4 + 4. I have to do 1 + 3 + 5 + 7, and I'm not sure how. It gives me 4 squared is 11 or something.
Just some tips:
Try not to use eval(), it will evaluate any input given and so it can do something you don't want to do. Instead, use int().
Remember that, say 4*4, is just 4 + 4 + 4 + 4. You're on the right track with a for-loop, but now make the loop iterate n times adding n to itself.
new = 0
for _ in range(n):
new += n
Note that this won't work with negative numbers. If you're going to be dealing with those, perhaps get the absolute value of n at the beginning:
def square(n):
n = abs(n)
....
Since you have been told you have to get the answer by producing the first n odd numbers, then you need to think about how to do that - certainly your loop isn't doing that :
several issues :
you do odd =1, and then use odd in your for loop, the two can't co-exist, so the initial value of odd = 1 is overwritten.
Your loop doesn't produce the first n odd numbers that I can see.
My suggest would be to rework your loop : the first 'n' odd numbers are in the form :
1, 3, 5, ... n*2-1
(Counting from 1 not from zero)
so a loop like this :
final = 0
for c in range(1, n+1): #start counting from 1 to do 1 to n+1
odd = c*2 -1 #Use the series above to generate each odd number.
final += odd
should work
a much more 'pythonic' way to do this is :
final = sum(c*2-1 for c in range(1,n))
This uses a generator to create all of the odd numbers (the equivalent of the loop), and sum the values as they get created.
Go back to the original definition of multiplication.
Just add the number n to itself n times. What's so hard? It's inefficient has hell, but it'll work.
I'm sure there's a more Pythonic way:
def square(n):
sum = 0
for i in range(0,n):
sum = sum + n
return sum

Categories