Apart from others, what I’ve realised so far about loops, is that great attention must be paid when we use “print”. Sometimes it is necessary to “print” inside the loop with indentation, but in other cases this brings trouble and “print” should be written outside loop without indentation.
To be more precise, about the loop with digits:
for item in single_digits:
…print(item)
…squares.append(item**2)
print(squares)
Here, the output seems normal. The first print(inside loop), gives the items from 0 to 9 in a vertical order and then, the second print (outside loop) gives the all squares in a list [0,1,4,9,16,…81]
However, if both “print” are inside loop, the output is complex:
0
[0]
1
[0, 1]
2
[0, 1, 4]
3
[0, 1, 4, 9] and so on…
I suppose this is because of the iterations. It is like every iteration in the loop consists of two “sub-iterations”, one for the print items and one for the print squares. Is it true?
If this is the case, why the result of the second “sub-iteration” is a list including all the squares so far and not the result of the squared item? i.e.
…
2
4
3
9
4
16…
Hello,guys!Help me with the code,please!Why can`t I use
single_digits=range(10)
for item in single_digits:
print(item)
squares=[]
for element in squares:
squares.append(item**2)
print(squares)
cubes=[item**3 for item in single_digits]
print(cubes)
instead of
single_digits = range(10)
squares = []
for item in single_digits:
print(item)
squares.append(item**2)
cubes = [item**3 for item in single_digits]
print(cubes)
Hello
when does the while loop stop.
for example this my code to find a factor using a while loop
def factorial(n):
if n == 0 :
return 1
if n < 0 :
ValueError(“Inputs 0 or greater only”)
result = n
while n != 0 :
print(‘{} * {}’.format(result,n-1))
result*= n-1
n-=1
return result
in my code the condition statement is while n != 0 and when n==0 he still excute the code i dont under stand why ? like (120 * 0) and ( 6 * 0) he excute the code as n == 0 ?
There is the fly in the ointment. The while condition is looking at n but the math is being done on, n - 1.
while n - 1 > 0:
should fix that.
Aside
Even though your situation is quite well controlled (decrement by 1, each iteration) we should avoid using equality in a loop condition. Safer to use inequality so that we don’t accidentally slip below zero (by some freak of nature) and end up with an infinite loop.
The output should be sufficient enough to explain the code. In the first example, the number is printed, then the list is appended with its square, then the list is printed. We can see it accumulate as the range is iterated.
Indentation is a fundamental part of Python syntax. It’s role is to set block scope. When the indent is removed from the last line it only prints when the loop is complete.
In Python Loops: Medical Insurance Project, there are 2 extra tasks to practice more using loops. The first extra task is to “Change the first for loop into a while loop.”
Can anyone give the solution for this? I think I’m still in confusion on converting for loops into while loops.
for loops iterate over a defined sequence, so there is a starting point and an ending point. To convert to a while loop we can establish the starting point and loop until we reach an ending point. But there is more. We can loop infinitely (an indefinite number of iterations) until a breaking condition is met. while has no fixed number of iterations like a for loop.
Please give us an example of your for loop for further examination and discussion.
In Python Loops: Medical Insurance Project, there are these lines of code: actual_insurance_costs = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0] total_cost = 0
the task is: Use a for loop to iterate through actual_insurance_costs and add each insurance cost to the variable total_cost.
so i wrote:
for actual in actual_insurance_costs:
total_cost += actual
the extra task is: Convert the first for loop in the code to a while loop.
Here is an example of a while loop that will do the same as your for-loop:
def solve():
# initialize an index counter
idx = 0
# initialize a total counter
tt = 0
#while index is less than or equal to (length of 'actual_insurance_costs') -1
while idx <= len(actual_insurance_costs)-1:
# increment total by indexed element
tt += actual_insurance_costs[idx]
# increment index by 1
idx += 1
# return total
return tt
One could do a straight across swap by using an index pointer that increments; or, one could exhaust the list:
temp = actual_insurance_costs[:]
total = 0
while len(temp):
total += temp.pop()
return total
The original list remains intact.
If temp.pop() looks foreign then revert to the index form until that built-in method comes up (which it does smack dab in the middle of a challenge); or, look it up on docs.python.org.
The method as used above removes the value from the right side of the list and assigns it to the variable. Gradually the list shortens to contain nothing.
I got stuck in the review section and had to go through the chapter to retake notes.
I had to realize there are essentially 4 ways to go about list comprehension, according to the module:
create a list with range()
create a list by new_list = [ for in ]
list comprehension with the conditional before the loop (acting as a filter) Examples of doubling number list
doubled = [num2 if num<0 else num3 for num in numbers]
4A. list comprehension with the conditional after the loop (acting as a transformation)
for num in numbers
if num<0
only_neg_doubled. append(num2)
4B.
neg_double= [num2 for num in numbers if num<0]
I posted the module review below and was wondering what’s the discrepancy between the two.
Your code below:
single_digits = range(10)
squares =
cubes=
#Guided
for items in single_digits: #print(items)
squares.append(items**2)
print(squares)
for items in single_digits:
cubes.append(items**3)
print(cubes)
#Seperation
print(‘\n’)
#Retry
single_digits = range(10)
square = [num2 for num in single_digits]
cube = [num3 for num in single_digits]
print(square)
print(cube)
Not sure we can append to a range object, but nonetheless, this is a bad idea since it is what we are iterating over (the range). Besides, you have a squares list so why not append the squared values to that?
I’m trying to subtract 5 from each price in prices using a loop, but I’m confused why the following code is giving me only an output of 30 for new_prices
for price in prices:
new_prices = price - 5
print(new_prices)
The hint says to use this: “new_prices = [price - 5 for price in prices]” but I’m confused why the above code won’t also work.
‘Clean this up’, how?
The function printed what you specified: single digits between 1-10 (not including 10) then squared each number and cubed each number, appended each to a list, and printed each number 1-9 as well as a list of those squared and cubed values.