我想用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