[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

On 14Jan2019 21:29, caigy84 at gmail.com <caigy84 at gmail.com> wrote: >So I was given this question to be solved in Python 3 : Pick any > 3 random ascending numbers and write out a loop function that prints > out all 3 numbers. This was the code and solution presented to me. > Can anyone understand it and explain it to me please ? I have looked > at it but cannot see how it was derived and why the correct solution > was printed. Thanks alot ! Indentation is vital in Python; it is used to delineate the start and end of loops and control structures etc (where other languages might use curly braces). So because your pasted code has no indentation we must guess. I'm going to reindent to express what I'm guessing: # any 3 ascending numbers , counter must start at 0. # 400 467 851 i = 0 x = 400 while x < 852: print(x) if i > 0: x = x + ((i + 4) * 67) + (i * 49) else: x = x + 67 i = i + 1 The other thing is that I do not think you have described the problem correctly, or if that _is_ how it was expressed to you then it is a terrible terrible problem description. All the code above does is (a) start "x" at 400, which is your first arbitrary value and (b) stop the loop when "x" >= 852, which _prevents_ it printing any numbers above your last arbitrary value (851). The bit in the middle is just contrived. The important things about the code seem to be: "x" is always increased. This ensures that the loop will finish, because "x" starts below the limit (852) and always gets closer to it, and eventually exceeds it ==> loop exits. The first pass through the loop when "x" == 0 just adds 67 to it, getting from 400 to 467, your second arbitrary number. So this isn't some clever bit of code that does something to generate 3 values, it is a loop that runs three times to get exactly the 3 values in your comment. I suspect we're missing the larger picture here. Cheers, Cameron Simpson <cs at cskk.id.au>

- Prev by Date:
**3 random numbers** - Next by Date:
**python package management confusion** - Previous by thread:
**3 random numbers** - Next by thread:
**3 random numbers** - Index(es):