0

I am trying to program a module for a class but my main() function does not work I presume the code is right but when I input a number it just goes to the next line, does not stop execution and just allows me to input further numbers, going to the next line afterward - ad infinitum.

I tread into the main function of python but I am still confused.

# Uses python3
import sys

def get_fibonacci_last_digit_naive(n):
    if n <= 1:
        return n

    previous = 0
    current  = 1

    for _ in range(n - 1):
        previous, current = current, previous + current

    return current % 10
def fast_fibL(b):
    a = []
    a.append(0)
    a.append(1)
    n = 0
    if (b == 0):
        return 0

    if (b == 1):
        return 1

    for i in range(b):
        c = a[i] + a[i + 1]
        a.append(c)
        n += 1

    return(a[n])

def get_fib_last_digit_fast(e):
    b = fast_fibL(e)
    return b % 10

def main():
    input = sys.stdin.read()
    n = int(input)
    print(get_fib_last_digit_fast(n))

if __name__ == '__main__':
    main()

I expect the code to return the the last digit of the n-th Fibonacci number entered.

CAM
  • 25
  • 9
  • You don't want to use `sys.stdin.read()` here... it will read until it hits the end of file (EOF). The enter key does not signify the end of the file, only the start of a new line. You can either try `sys.stdin.readline()` or use the built-in function `input()` instead (assuming you're using Python 3). – John Szakmeister Feb 11 '19 at 13:41

2 Answers2

4

Instead of input = sys.stdin.read(), use the built-in input() function:

def main():
    n = int(input('Enter an integer: '))
    print(get_fib_last_digit_fast(n))
Tim Klein
  • 2,538
  • 15
  • 19
2

The program is waiting for your input, since you're using stdin.read(). This waits until the input is terminated by (for instance) pressing ctrl-D. Normally you'd use input() for this, which reads one line from stdin.

def main():
    line = input('> ')
    n = int(line)
    print(get_fib_last_digit_fast(n))
khelwood
  • 55,782
  • 14
  • 81
  • 108