Python Forum

Full Version: Explain range in this code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I created this code to calculate a product used two input of user :

factor = int(input())
multiple = int(input())

for p in range ( 1, multiple + 1):
  print ('{} x {}={}'.format(factor, p, factor *p))
The for lo cycle seen in a solution and the thing that does not enter my head is the reason why I used it in a in range (multiple + 1), I thought it was to iterate until I reached the value that was passed in input.
I was wondering if my reasoning is correct.
Regards,
RavCoder
If you have range(x, y), it starts with x, and keeps going as long as the result is less than y. When the result is equal to (or greater than) y, it stops without returning a value. So if you want the last number to be multiple, you have to do range(x, multiple + 1).
did you check the docs? It's your best friend and first place to turn to if something is unclear....
I checked the documentation, but I didn't understand this passage of the reason why to put multiple + 1 instead I don't know type multiple and enough or to add a number to stop the cycle.
Translation:
Python:
for count in range(a,b)
Other languages, variation of:
Quote:for (count=a;count<b,count++)

Point being, it is not count <= b, it's count < b, which is why you add 1.