Chi*_*imp 16 python python-3.x
我试图定义一个函数来制作一个矩形的周长.这是代码:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Run Code Online (Sandbox Code Playgroud)
我想我没有留下任何论据或类似的东西.
unu*_*tbu 12
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Run Code Online (Sandbox Code Playgroud)
像这样运行会产生:
% echo "1 2" | test.py
6
Run Code Online (Sandbox Code Playgroud)
我怀疑IDLE只是将一个字符串传递给你的脚本.第一个input()是啜饮整个字符串.注意如果在调用之后放入一些print语句会发生什么input():
width = input()
print(width)
height = input()
print(height)
Run Code Online (Sandbox Code Playgroud)
跑步echo "1 2" | test.py产生
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Run Code Online (Sandbox Code Playgroud)
请注意,第一个print语句打印整个字符串'1 2'.第二次调用input()引发EOFError(文件结束错误).
因此,我使用的简单管道只允许您传递一个字符串.因此你只能打input()一次电话.然后,您必须处理此字符串,将其拆分为空格,并自行将字符串片段转换为int.那是什么
width, height = map(int, input().split())
Run Code Online (Sandbox Code Playgroud)
确实.
请注意,还有其他方法可以将输入传递给您的程序.如果您已经test.py在终端中运行,那么您可以单独键入1并且2没有问题.或者,您可以编写一个带有pexpect的程序来模拟终端,传递1和2编程.或者,您可以使用argparse在命令行上传递参数,允许您使用调用程序
test.py 1 2
Run Code Online (Sandbox Code Playgroud)
小智 8
**最好是使用try except块来摆脱EOF **
try:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
except EOFError as e:
print(end="")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108170 次 |
| 最近记录: |