我想以 Python 的方式尽可能接近地复制以下 C++ 代码,并进行输入和异常处理。我取得了成功,但可能不是我想要的。我本来想退出类似于输入随机字符的 C++ 方式的程序,在这种情况下它是一个“q”。while 条件下的 cin 对象不同于 python 的方式使 while 为真。此外,我想知道将 2 个输入转换为 int 的简单行是否合适。最后,在 python 代码中,“再见!” 由于强制应用程序关闭的 EOF (control+z) 方法,从不运行。有一些怪癖,总的来说,我对 python 所需的代码更少感到满意。
额外:如果您查看最后打印语句中的代码,这是将 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