It will increment by 1. When you use an iterator like range(), you assign the next value from the iterator each time, and whatever you assigned to i in the loop is ignored.

If you want it to double each time, don't use range(), do your own updating and end test.

i = 1
while (i < 100):
    print(i)
    i *= 2
Answer from Barmar on Stack Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 46699420 โ€บ python-for-loop-multiplication
Python for loop multiplication - Stack Overflow
That also means you need to initialize the result with 1, not 0, because multiplying by 0 is always 0. n = int(input('Enter a negative number: ')) result = 1 for i in range(n, 0): result *= i print(result) ...
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 55dfe28086f552612b00043f
how do i increment for loop in powers of 2? | Codecademy
my_list = [0,1,2,3,6,5,7] for i in range(0,len(my_list),2**i): print my_list[i] this code gives an error
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ ways-to-increment-iterator-from-inside-the-for-loop-in-python
Ways to increment Iterator from inside the For loop in Python - GeeksforGeeks
April 22, 2020 - In Python, a for loop iterates over an iterator object rather than using a manual counter. As a result, modifying the loop variable inside the loop does not affect iteration, and controlled stepping must be handled explicitly. Example: Why Incrementing the Loop Variable Does Not Work
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to multiply printed for loop values with each other?
r/learnpython on Reddit: How to multiply printed for loop values with each other?
December 7, 2022 -

Hi,

I am trying to write a code to run factorials for any integer values inputted.

What works:

  1. Input a value statement (x)

  2. For loop (outputs the x value in descending order up to minimum value 1)

So now when I input 5, I get the list 5, 4, 3, 2,1

If I input 3, it prints 3, 2, 1

How can I get printed numbers to multiply with each other e.g., 5 * 4 * 3 * 2 * 1

When I input 3, I

๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ how to increment for loop in python
How to Increment For Loop in Python - Spark By {Examples}
May 31, 2024 - To increment a for loop based on the length of a sequence, you can use the len() function to get the length of the sequence and then use the obtained length in the range of the for loop.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ incrementing with a for loop
r/learnpython on Reddit: Incrementing with a for loop
April 22, 2020 -
import numpy as np
from pandas import *
import matplotlib
import math
import random
import statsmodels
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
###########################################################################################################

weights = read_excel('/home/user/Documents/weights.xlsx',index_col = 'Date') #loading weights file
tickers=(weights['RIC']) #load securities in portfolio
weights = (weights['Fund1'])
Results_data = DataFrame()
Position_size = 10000


new_data = DataFrame()
for t in tickers:
    new_data[t] = pdr.get_data_yahoo(t, start="2017-01-01", end="2021-04-30")['Adj Close'] # downloading pricing data


for t in tickers:
        Results_data[t] = (new_data[t]/new_data[t].shift(1))-1 #Calculation of simple return
        Position_size = (Position_size * (1 + Results_data))

New to python and I'm having a little bit of an issue with the last for loop.

I now understand that python resets my position size variable at each iteration unlike say vba in which it would not reset to 10000. Is there any known workaround for this that I'm missing ?

Top answer
1 of 4
16
If you just learned loops, what you are looking for is a for loop. Since you mentioned functions we'll go ahead and make this a function. What do we want in our function? Well, we want it to take a list and return the multiplied values. NOTE: For simplicity, I'm going to assume your list is valid (numbers only), but in an actual function you'd want some error checking. How does our function definition look? def multiply_list_values(number_list): OK! We have the basics. So let's think through what we want to do. We want to go through each value of the list and multiply it with the previous total. We could also easily use recursion here, but since you didn't mention learning that I won't. It's fairly simple in either case. So how do you go through all the values of a list? Using a for...in loop. It will look something like this: def multiply_list_values(number_list): for number in number_list: print(number) If you run this, and have number_list as a list of numbers, you will see each individual number printed out in order. That's a good start, but it doesn't really do what we want. So lets think about our base case, where we want the very first number multiplied. If we were adding, we'd start at 0, but since we're multiplying, we need to start with 1, as 1 * X = X. Let's see how this looks: def multiply_list_values(number_list): result = 1 for number in number_list: print(result * number) Well, we get the same thing. What we need to do is multiply the value by each subsequent number to continually increment the result. How do we do this? We can assign a variable the result of a calculation involving itself. This doesn't work like a math equation. For example, if you had a variable x = 1 and wanted to add 2 to that value, you could do this: x = x + 2 and now x would be 3. So let's try the same thing with multiplication: def multiply_list_values(number_list): result = 1 for number in number_list: result = result * number print(result) So what do we have now? If you run this, you'll see the multiplied values getting higher and higher, and it will run through the whole list. Great! That's exactly what we want. Incidentally, this is such a common thing to do there is a shorthand way built into Python to make this easier. Instead of result = result * number you can remove the result on the right side and put your math operator before the equals sign like this: result *= number. This does the exact same thing. In our x example, you could change the x = x + 2 to x += 2 for the same result. Now that the math is finished, we just need to return the result after the loop, making our simplified and final function look like this (with test usage): def multiply_list_values(number_list): result = 1 for number in number_list: result = result * number return result def main(): number_list = [1, 2, 3, 4, 5] print(multiply_list_values(number_list)) # Output # 120 if __name__ == '__main__': main() There are many problems in Python (and programming in general) that can be solved this way. The for..in loop is extremely useful and can be used for all sorts of operations, not just mathematical ones, so keep it in mind whenever you want to do operations on every element of a list or dictionary. Let me know if you have questions!
2 of 4
4
Well, loops are indeed the right thing to do here. One approach would be to keep a running total: start with a value of 1, then loop through the list and multiply your total by the current value each time.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
For Loop in Python - Python Help - Discussions on Python.org
September 7, 2023 - Pardon if I have been posting series of questions. Newbie Python learner here, and am going through PCEP materials, and having some questions along the wayโ€ฆ Thank you in advance for the help. In these two codes, I confused why the answer is such: Code 1: my_list = [0,1,2,3] x = 1 for elem in my_list: x *= elem print (x) Answer: [0] Code 2: my_list = [0,1,2,3] x = 1 for elem in my_list: new_list = x * elem print (new_list) Answer: [3] Question 3: I want to create a code that multi...
๐ŸŒ
Datamentor
datamentor.io โ€บ python โ€บ for-statement
Python for Loop (With Examples)
The above code can create the multiplication table of any value that is provided as input. Python allows us to include one for loop inside another, known as nested for loop.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-create-a-multiplication-table-for-any-number-in-python
How to create a multiplication table for any number in Python
The range() function generates a sequence of numbers automatically. We can loop through this sequence, running specific code for each number until we reach the final number in the series.
๐ŸŒ
Thinglabs
thinglabs.io โ€บ python-increment-by-1-a-guide-to-simple-counting-in-code
Python Increment by 1: A Guide to Simple Counting in Code - thinglabs
November 7, 2024 - If score was zero, it now holds the value 1. For multiple additions, the += operator can be used repeatedly: counter = 10 counter += 1 # counter is now 11 counter += 1 # counter is now 12 ยท In both examples, the += operator serves to add 1 ...
Top answer
1 of 5
22

It seems that you want to use step parameter of range function. From documentation:

range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. 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 (or else ValueError is raised). Example:

 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
 >>> range(0, 10, 3) [0, 3, 6, 9]
 >>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
 >>> range(0) []
 >>> range(1, 0) []

In your case to get [0,2,4] you can use:

range(0,6,2)

OR in your case when is a var:

idx = None
for i in range(len(str1)):
    if idx and i < idx:
        continue
    for j in range(len(str2)):
        if str1[i+j] != str2[j]:
            break
    else:
        idx = i+j
2 of 5
11

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1
๐ŸŒ
365 Data Science
365datascience.com โ€บ blog โ€บ tutorials โ€บ python tutorials โ€บ working with loops in python
Working With Loops in Python โ€“ 365 Data Science
April 24, 2023 - Well, it is obvious weโ€™ll need to multiply the quantity of each food by its price. You must have noticed that our dictionaries have exactly the same keys. This is one of the strong points in our case and we should exploit this. The procedure: Go to the box of spaghetti in the first dictionary ... Multiply those two. This operation must be repeated for each food product. This is exactly why it is easier to use a loop.
๐ŸŒ
Medium
medium.com โ€บ @tiaraoluwanimi โ€บ python-while-loops6420e2f913a3-6420e2f913a3
Python While Loops: Common Errors & How to Fix Them | Medium
November 10, 2021 - def times_table(number): # Initialize the starting point of the multiplication table multiplier = 1 # Only want to loop through 5 while multiplier <= 5: result = number * multiplier print(str(number) + "x" + str(multiplier) + "=" + str(result)) # ...
๐ŸŒ
Alma Better
almabetter.com โ€บ bytes โ€บ tutorials โ€บ python โ€บ for-loop-in-python
For Loop in Python
December 13, 2023 - A for Loop needs a starting point, ending point, and increment to determine how many times it will run. For loops, iterate over a collection of data like arrays or lists. For loops are useful for performing operations on multiple data points or counting over a range of numbers.