Python Forum
Help change from a while loop to a for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help change from a while loop to a for loop
#6
(Nov-09-2018, 12:33 AM)Larz60+ Wrote: show what you have tried

here'a a simple for loop that starts at 2 increments by 6 up to 38
Since it is zero based, terminator is one more (39)
>>> for x in range(2, 39, 6):
...     print(x)
... 
2
8
14
20
26
32
38
>>>

Hi,
All I can achieve are various versions of this. Thanks again
def displayDigits(number):

    for i in range(number):
        number = number // 10

    print(number)

displayDigits(26)

(Nov-09-2018, 02:44 AM)stullis Wrote: An obvious implementation of a for loop would limit the number of digits you could count. To prevent that, your iterable should be based upon the number passed in. That would ensure that you have enough iterations for effectively cover the number of digits of any number you could provide.

Instead of repeatedly doing floor division, you could use the values in a range as exponents. This way, each iteration increases the divisor by a magnitude of ten and you simultaneously have your "count" for the output:

for x in range(20):
    divisor = 10 ** x
    print(f"For {x}, the divisor is {divisor}.")
Now, how could you use that idea in your function?

On a side note, a function should always have a return. The print() call should be replaced by a return and then you call the function like this:

print(displayDigits(26))

Thanks for your advice but I honestly don't know how to use what you have shown me. I am totally stuck here.
Reply


Messages In This Thread
RE: Help change from a while loop to a for loop - by captwiggum - Nov-09-2018, 09:20 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop to find the best combination/score KoinKoin 21 28,576 Jan-05-2023, 10:31 AM
Last Post: KoinKoin
  Many iterations for loop question adesimone 9 1,889 Nov-12-2022, 07:08 PM
Last Post: deanhystad
  Please check whether the code about the for loop question is correct. (SyntaxError) lilliancsk01 10 2,657 Nov-08-2022, 01:25 PM
Last Post: deanhystad
  while loop idddj 8 1,749 Oct-03-2022, 05:03 PM
Last Post: jefsummers
  Beginner Python Question: FIzz Buzz using while loop camoyn13 2 1,856 Sep-20-2022, 09:00 AM
Last Post: deanhystad
  Function combining file manipulation and loop Leyo 5 1,839 Mar-23-2022, 09:47 AM
Last Post: Leyo
  Using If Statements Instead of While Loop in Simple Game Program new_coder_231013 5 3,228 Dec-14-2021, 12:23 AM
Last Post: supuflounder
Big Grin for loop nadun 3 1,918 Nov-22-2021, 03:36 PM
Last Post: deanhystad
  How to compile following python loop program reinispl 3 1,989 Oct-27-2021, 01:57 PM
Last Post: DeaD_EyE
  Printing During a Loop apeltes 16 5,399 Oct-21-2021, 12:19 AM
Last Post: apeltes

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020