简体   繁体   中英

Why does this Python code not work?

Please help, I cannot figure out why this code does not work. I think the first loop runs forever but I don't know why!

def NTN():
    list1 = []
    count = 0
    number = 0
    Start = input('Type Start Number')
    while number != Start:
        count = count + 1
        number = number + count
    Stop = input('Type Stop Number')
    while number != Stop:
        count = count + 1
        number = number + count
        if number != Stop:
            (list1).append(number)
    return (list1)

print(NTN())

You are increasing number by increasing amounts in every iteration. Here's an idea of how it is increasing. Assume Start = 4

After 1 loop, count = 1 and number = 1, increase of 1

After 2 loops, count = 2 and number = 3, increase of 2

After 3 loops, count = 3 and number = 6, increase of 3

Since number is never really equal to 4, the loop never ends. What you need probably is while number <= Start . That would terminate the loop after 3 iterations when number is past 4.

change "number != Start" and "number != Stop" to "number < Start" and "number < Stop" in all places, and it should work.

What went wrong: if Start is 2, then in the first iteration of the while loop, count becomes 0+1=1 and number becomes 0+1=1; in the second iteration, count becomes 1+1=2 and number becomes 1+2=3, which bypasses 2. Since your while loop only ends when number is equal to Start, it never ends.

A couple of side-points:

  1. By convention Python variable and function names are lower-case.
  2. input() returns a string; if you want a number you have to convert it ie with int() or float() . (Note: if you are using Python 2.x input() calls eval() which is really awful design - you should be using int(raw_input()) instead.)

so,

# This code assumes Python 3.x
from math import ceil, sqrt

def get_int(prompt):
    """
    Prompt until an integer value is entered
    """
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter an integer!")

def tri(n):
    """
    Return triangular number n,
      ie the sum of (1 + 2 + ... + n)
    """
    # using Gaussian sum
    return n * (n + 1) // 2

def reverse_tri(t):
    """
    For positive integer t,
    return the least positive integer n
      such that t <= tri(n)
    """
    # derived by quadratic formula from
    #   n * (n + 1) // 2 >= t
    return int(ceil(((sqrt(8 * t + 1) - 1) / 2)))

def ntn(start, stop):
    """
    Return a list of triangular numbers
      such that start <= tri < stop
    """
    a = reverse_tri(start)
    b = reverse_tri(stop)
    return [tri(n) for n in range(a, b)]

def main():
    start = get_int('Enter a start number: ')
    stop = get_int('Enter a stop number: ')
    lst = ntn(start, stop + 1)    # include stop number in output
    print(lst)

if __name__ == "__main__":
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM