Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why duplicate a variable??
#1
Hi, everybody.

Why do I have to duplicate the variable 'k' in the code below?
I tried NOT doing it, but the counter doesn't work properly unless I create the variable 'counter' to receive 'k'.
(The script is supposed to receive the inputs 'initial number', 'final number', 'step' and then print the whole progression).

Thanks in advance!


def counter(k, y, z):
    from time import sleep
    if z < 0:
        z *= -z

    if k < y:
        count = k  ## WHY?? WHEN I IGNORE THIS AND USE K ALONG THE LOOP, IT USES AN EXTRA (WRONG) VALUE IN THE END.
        while cont <= y:
            print(f'{count}', end=' - ' if count+z <= y else '')
            count += z
            sleep(0.333)

    while k >= y: 
        print(k, end=' - ' if k-z >= y else '')
        k -= z
        sleep(0.333)

while True:
    start = int(input('Initial number: '))
    end = int(input('Final number: '))
    step = int(input('Step: '))

    counter(start, end, step)

    flag = str(input('\nAgain? (S/N) ')).strip().lower()[0]
    if flag == 'n':
        break

Well, since I can't edit/delete my post, there goes the code again, now revised...

# encoding:utf-8

def counter(k, y, z):
    from time import sleep
    if z < 0:
        z *= -z

    if k < y:
        count = k  ## WHY DOESN'T IT WORK IF A SIMPLY USE K??
        while count <= y:
            print(count, end=' - ' if count+z <= y else '')
            count += z
            sleep(0.333)

    while k >= y:
        print(k, end=' - ' if k-z >= y else '')
        k -= z
        sleep(0.333)

while True:
    initial = int(input('Initial number: '))
    final = int(input('Final number: '))
    step = int(input('Step: '))

    counter(initial, final, step)

    flag = str(input('\nAgain? (Y/N) ')).strip().lower()[0]
    if flag == 'n':
        break
Reply
#2
You need the original value of k on line 15. You shouldn't need it if you use an else:

    if k < y:
        while k <= y:
            print(k, end=' - ' if count+z <= y else '')
            k += z
            sleep(0.333)
     else:
        while k >= y:
            print(k, end=' - ' if k-z >= y else '')
            k -= z
            sleep(0.333)
(untested)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Are you sure your line 6: z *= -z is what you want to do?
Reply


Forum Jump:

User Panel Messages

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