0

The challenge is to square an input number.

import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...

def square(x):
    return print(x ** 2)

for line in sys.stdin:
    print(line, end="")

I don't know how to use sys.stdin I guess because I don't know how to pass through the challenge test inputs for x.

Apologies, but I can't find any answers.

gog
  • 10,367
  • 2
  • 24
  • 38
quigley
  • 11
  • You didn’t call your function. Try `square(int(line.strip()))`. – Samwise Dec 17 '22 at 17:50
  • 1
    You should also decide whether your function prints the answer to stdout or returns it to the caller. – Samwise Dec 17 '22 at 17:51
  • Thanks, I guess print to stdout...? Like the test inputs are 5 and 25, but I don't know how to make it so the coding interface passes through those numbers in the function. – quigley Dec 17 '22 at 17:58
  • Like I said, *call your function*. That's how you pass numbers *into* it. Once you've done that you can work on debugging what you get *out* of it. (You call a function by typing its name, `square`, and then putting the args in parens, so `square(line)` if you want to call `square` with the value of `line` as its `x` arg.) – Samwise Dec 17 '22 at 18:25
  • I hear what you're saying, and I appreciate your help. At the end of the day, HackerRank wanted an x = input('') so it could pass its predetermined values through the function. To test if it worked or not. – quigley Dec 19 '22 at 17:54
  • In that case you want to do `square(x)` to actually call the function with whatever value was assigned to `x`. (Hint -- you probably need to convert `x` from a string to an int before you can square it!) – Samwise Dec 19 '22 at 18:40

1 Answers1

1

If you want to read lines from standard input, you can use input. It will raise EOFError at end of file. To read lines successively and handle them you can just read in a loop with an exception handler for EOFError.

try:
  while True:
    line = input()
    x = int(line)
    print(square(x))
except EOFError:
  pass

Or for fun, wrap this up in a function that yields out the lines.

def read_stdin():
  try:
    while True:
      yield input()
  except EOFError:
    pass

for line in read_stdin():
  print(square(int(line)))
Chris
  • 26,361
  • 5
  • 21
  • 42