python eof when reading_EOFError: EOF when reading a line

问题

I am trying to define a function to make the perimeter of a rectangle. Here is the code:

width = input()

height = input()

def rectanglePerimeter(width, height):

return ((width + height)*2)

print(rectanglePerimeter(width, height))

I think I haven't left any arguments opened or anything like that.

回答1:

width, height = map(int, input().split())

def rectanglePerimeter(width, height):

return ((width + height)*2)

print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py

6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()

print(width)

height = input()

print(height)

Running echo "1 2" | test.py produces

1 2

Traceback (most recent call last):

File "/home/unutbu/pybin/test.py", line 5, in

height = input()

EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

回答2:

convert your inputs to ints:

width = int(input())

height = int(input())

回答3:

**The best is to use try except block to get rid of EOF **

try:

width = input()

height = input()

def rectanglePerimeter(width, height):

return ((width + height)*2)

print(rectanglePerimeter(width, height))

except EOFError as e:

print(end="")

来源:https://stackoverflow.com/questions/17675925/eoferror-eof-when-reading-a-line

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值