我希望以pythonic方式尽可能接近地复制以下C ++代码,输入和异常处理。我取得了成功,但可能不是我想要的。我本来希望退出程序类似于C ++输入随机字符的方式,在这种情况下它是一个'q'。 while条件下的cin对象不同于make while while的python方式。另外我想知道将2个输入转换为int的简单线是否是一种适当的方法。最后,在python代码中,“再见!”永远不会运行,因为强制应用关闭的EOF(控制+ z)方法。有一些怪癖和整体我很高兴python中需要的代码更少。
额外:如果你看一下最后一个print语句中的代码,那么这是一个很好的方法来打印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
答案 0 :(得分:1)
对于函数hmean
,我会尝试执行return语句,并在a
等于-b
时引发异常:
def hmean(a, b):
try:
return 2 * a * b / (a + b)
except ZeroDivisionError:
raise MyError, "bad hmean() arguments: a = -b not allowed"
要在字符串中插入变量,方法format
是一种常见的替代方法:
print "Harmonic mean of {} and {} is {}".format(x, y, z)
最后,如果在将x或y投射到except
时引发ValueError
,您可能希望使用int
阻止。
答案 1 :(得分:1)
这是我要向你抛出的一段代码。类似的东西在C ++中并不容易实现,但它通过分离关注点在Python中使事情变得更加清晰:
# so-called "generator" function
def read_two_numbers():
"""parse lines of user input into pairs of two numbers"""
try:
l = raw_input()
x, y = l.split()
yield float(x), float(y)
except Exception:
pass
for x, y in read_two_numbers():
print('input = {}, {}'.format(x, y))
print('done.')
它使用一个所谓的生成器函数,它只处理输入解析以将输入与计算分开。这不是“尽可能接近”,而是你所要求的“以pythonic方式”,但我希望你会发现它仍然有用。此外,我冒昧地使用浮点数而不是整数来表示数字。
还有一件事:升级到Python 3,版本2不再开发,只是接收错误修正。如果您不依赖于仅适用于Python 2的任何库,那么您应该感觉不太大。