Python Forum
Please help my while loop does not work as expected
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please help my while loop does not work as expected
#7
I think your logic is wrong. If the input unit is 3, the values for unit as your program loops are:

3, 6, 18, 72, 360, 2160

Don't you want them to be:

3, 6, 9, 12, 15, 18, 21?

Also, you program may run forever if unit and mode are not relatively prime. For example, if unit is 3 and mod is 9, this code will print an infinite sequence:
unit = int(input("Please enter the unit: "))
mod = int(input("Please enter the mod: "))

i = 1
while (unit*i)%mod != 1:
    print((unit*i)%mod, end=' ')
    i += 1
else:
    print("Inverse =", i)
Output:
3 6 9 0 3 6 9 0 3 6 9 0 ...
I think the result has to be in the range 1 to mod, so I would rewrite the code like this:
unit = int(input("Please enter the unit: "))
mod = int(input("Please enter the mod: "))

for i in range(1, mod):
    if (unit*i)%mod == 1:
        print("The inverse is: ", i)
        break
else:
    print('There is no solution')
Reply


Messages In This Thread
RE: Python - by bowlofred - Sep-28-2020, 07:12 PM
RE: Python - by KingKhan248 - Sep-28-2020, 07:29 PM
RE: Python - by bowlofred - Sep-28-2020, 07:49 PM
RE: Please help my while loop does not work as expected - by deanhystad - Sep-28-2020, 09:12 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  While Loop Does Not Work Properly mactron 4 872 Jun-22-2023, 01:04 AM
Last Post: mactron
  For Loop Works Fine But Append For Pandas Doesn't Work knight2000 2 1,930 Dec-18-2021, 02:38 AM
Last Post: knight2000
  How can this for loop work without : ? Pedroski55 1 1,673 Dec-13-2020, 01:19 AM
Last Post: palladium
  For loop in my __init__ doesn't work as expected Jessy 2 2,320 Nov-18-2019, 10:07 AM
Last Post: buran
Question Why does modifying a list in a for loop not seem to work? umut3806 2 2,265 Jul-22-2019, 08:25 PM
Last Post: umut3806
  Why doesn't my loop work correctly? (problem with a break statement) steckinreinhart619 2 3,155 Jun-11-2019, 10:02 AM
Last Post: steckinreinhart619
  for loop just work one Faruk 1 1,974 Jan-19-2019, 05:34 PM
Last Post: Larz60+
  'Looping' does not work out within a 'for Loop' Placebo 4 3,272 Sep-15-2018, 08:19 PM
Last Post: Placebo
  Having issues getting a loop to work PLESSE HELP ASAP manthus007 1 2,086 Aug-25-2018, 10:44 AM
Last Post: j.crater
  Scoping Question: If else in for loop not evaluating i as expected datasundae 3 3,125 May-25-2018, 06:43 PM
Last Post: datasundae

Forum Jump:

User Panel Messages

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