我想用pythonic的方式尽可能接近地复制下面的C++代码,并且输入和异常处理尽可能地接近。我取得了成功,但可能不是我想要的。我希望退出类似于C++输入随机字符的程序,在这种情况下它是'q'。 while条件中的cin对象与python创建while时的方式不同。另外我想知道将2个输入转换为int的简单行是否是一种适当的方式。最后,在Python代码中,“再见!”从未运行,因为强制应用程序关闭的EOF(控制+ z)方法。有怪癖,总体而言,我对python中所需的代码越少感到满意。Python输入和异常与C++
额外:如果您查看最后一次打印语句中的代码,是将var和字符串一起打印的好方法吗?
任何简单的技巧/技巧都是受欢迎的。
C++
#include <iostream>
using namespace std;
double hmean(double a, double b); //the harmonic mean of 2 numbers is defined as the invese of the average of the inverses.
int main()
{
double x, y, z;
cout << "Enter two numbers: ";
while (cin >> x >> y)
{
try //start of try block
{
z = hmean(x, y);
} //end of try block
catch (const char * s) //start of exception handler; char * s means that this handler matches a thrown exception that is a string
{
cout << s << endl;
cout << "Enter a new pair of numbers: ";
continue; //skips the next statements in this while loop and asks for input again; jumps back to beginning again
} //end of handler
cout << "Harmonic mean of " << x << " and " << y
<< " is " << z << endl;
cout << "Enter next set of numbers <q to quit>: ";
}
cout << "Bye!\n";
system("PAUSE");
return 0;
}
double hmean(double a, double b)
{
if (a == -b)
throw "bad hmean() arguments: a = -b not allowed";
return 2.0 * a * b/(a + b);
}
的Python
class MyError(Exception): #custom exception class
pass
def hmean(a, b):
if (a == -b):
raise MyError("bad hmean() arguments: a = -b not allowed") #raise similar to throw in C++?
return 2 * a * b/(a + b);
print "Enter two numbers: "
while True:
try:
x, y = raw_input('> ').split() #enter a space between the 2 numbers; this is what .split() allows.
x, y = int(x), int(y) #convert string to int
z = hmean(x, y)
except MyError as error:
print error
print "Enter a new pair of numbers: "
continue
print "Harmonic mean of", x, 'and', y, 'is', z, #is this the most pythonic way using commas?
print "Enter next set of numbers <control + z to quit>: " #force EOF
#print "Bye!" #not getting this far because of EOF
在C++中“提高”等价于“throw”吗?感谢您的替代方法。指出。 – 2013-04-22 00:18:49
@klandshome是的,我也建议您查看['signal'模块](http://docs.python.org/2/library/signal.html)来处理按键事件。 – 2013-04-22 01:04:00
异步事件。我会阅读有关的。 – 2013-04-22 01:07:33