for i in range(5):
print(i, end=' ')
What does "for i in range" mean in Python?
python
for i in range(5, 0, -1):
for j in range(1, i + 1):
print(j, end="")
print()
Which of the following Python code will give different output from the others?
a. for i in range (0,5):
print (i)
c. N= [0,1,2,3,4,5]
for k in N:
print (k)
b. N= [0,1,2,3,4]
for j in N:
print (j)
d. for 1 in range (0,5,1):
B. Find error in the following code fragments.
for j in (10):
print (j)
for i in range [1; 10]:
print (i)
print (1)
while x != 3
print x
C. Give the output for the following code fragments.
for num in range (2,-5,-1):
print (num)
for i in "John":
print (i)
a = 100
while a > 90:
print (a)
a = a- 2
D. Answer the following questions.
i = 0
0
sum =
while i < 9:
if i % 4 == 0:
sum = sum + i
i = i + 2
print (sum)
What is the purpose of range() function? Give an example.
Differentiate between for and while loop.
What is an infinite loop? Give an example.
#OpenForum
A discussion on the 'Importance of Looping Constructs in Programming' can be take
up in the class.
102
Lab
3
So, I had a question where I was supposed to find the sum of the first natural numbers using Python.
Here's the problem:
Write a program to find the sum of the cubes of the first n natural numbers, where the value of n is provided by the user.
And this is the code that my professor used to allow the interpreter to produce the result:
= int(input("Enter a number:"))
sum = 0
for i in range (n+1): sum = sum + i*i*i
# for i in range starts as a loop, and then tries to get to (n + 1), whatever that may be
print("the sum of the first", n, "integers is", sum)
However, I can't seem to understand what "for i in range (n + 1): sum = sum + i * i * i" means. In other words, I don't understand what role this part of the code is doing to produce the result. Especially, I don't understand what the role of "for i in range (n + 1)" is doing. Does anyone mind explaining this to me?
I talked with my data science tutor for almost 20 minutes and he couldn't give me an answer beyond: "It just doesn't give you the last value. It's just something you remember."
If all we are dealing with here are strings then either of the two following methods will get you there.
Using a standard python for each loop, your code would look something like this:
for entry in entries:
print sql + entry
Using a list comprehension you can do this all in one line like this:
print [sql + entry for entry in entries]
However, if you intend to call entry.get(), you must make sure that "entries" is an iterable full of objects that contain the method get(). Then:
for entry in entries:
print sql + entry.get()
If you really want to use the i in range() syntax then it might look like this:
for i in range(len(entries)):
print sql + entries[i].get()
You can try print(sql, '\n'.join(entry.get() for entry in entries)).