2013-04-21 25 views
1

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

回答

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时int一个ValueError被提升到使用except块。

+0

在C++中“提高”等价于“throw”吗?感谢您的替代方法。指出。 – 2013-04-22 00:18:49

+1

@klandshome是的,我也建议您查看['signal'模块](http://docs.python.org/2/library/signal.html)来处理按键事件。 – 2013-04-22 01:04:00

+0

异步事件。我会阅读有关的。 – 2013-04-22 01:07:33

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的库,你应该不会感觉太大。

+0

这是深入的。感谢您的努力,因为我会研究您的代码。我现在有点倾向于使用python 2.7,因为它对Django框架有最好的支持。纠正我,如果我错了。 – 2013-04-22 06:52:57

+0

注意到使用浮标。 – 2013-04-22 06:54:03