简体   繁体   English

Python输入和例外与C ++

[英]Python input and exceptions vs. C++

I want to duplicate the following C++ code with input and exception handling as close as possible in a pythonic way. 我想以pythonic的方式尽可能接近地复制以下C ++代码以及输入和异常处理。 I achieved success but probably not exactly what I wanted. 我取得了成功,但可能不是我想要的。 I would have liked to quit the program similar to the C++ way of inputting a random char, in this case it was a 'q'. 我本想退出类似于输入随机字符的C ++方式的程序,在这种情况下,它是一个'q'。 The cin object in the while condition is different from the python way of making a while True. while条件下的cin对象与python将while设为True的方式不同。 Also I want to know if the simple line on converting the 2 inputs to an int was the an adequate way. 我也想知道将2个输入转换为int的简单行是否足够? Finally, in the python code, the "bye!" 最后,在python代码中,“再见!” never runs because of the EOF (control+z) method of forcing the app to close. 由于强制关闭应用程序的EOF(control + z)方法永远无法运行。 There are quirks and overall I am pleased with the less code needed in python. 有一些怪癖,总体而言,我对python所需的代码更少感到满意。

extra: if you look at the code in the last print statements, is that a good way to print var and strings together? 另外:如果您查看最后一个print语句中的代码,这是一起打印var和字符串的好方法吗?

Any simple tricks/tips are are welcome. 欢迎任何简单的技巧/提示。

C++ 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

For the function hmean I would try to execute the return statement, and raise the exception if a equals -b : 对于功能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"

To interpolate variables in a string, the method format is a common alternative: 要对字符串中的变量进行插值,方法format是一种常见的替代方法:

print "Harmonic mean of {} and {} is {}".format(x, y, z)

Finally, you might want to use an except block if a ValueError is raised when casting x or y to int . 最后,如果在将x或y转换为int时引发ValueError则可能要使用except块。

Here's a piece of code I'd like to toss at you. 这是我想向您介绍的一段代码。 Something like it is not easily possible in C++, but it makes things much clearer in Python by separating concerns: 诸如此类的东西在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.')

It uses a so-called generator function that only handles the input parsing to separate the input from the computations. 它使用所谓的生成器函数,该函数仅处理输入解析以将输入与计算分开。 This isn't "as close as possible" but rather "in a pythonic way" that you asked for, but I hope you will find this useful nonetheless. 这并不是您所要求的“尽可能接近”,而是“以Python方式”,但是我希望您仍然可以找到有用的方法。 Also, I took the liberty to use floats instead of ints to represent the numbers. 另外,我还是自由使用浮点数而不是整数来表示数字。

One more thing: Upgrade to Python 3, version 2 isn't developed any more but merely receives bugfixes. 还有一件事:升级到Python 3版本2不再开发,而仅收到错误修正。 If you don't depend on any libraries only available for Python 2, you shouldn't feel too much of a difference. 如果您不依赖于仅适用于Python 2的任何库,那么您应该不会感到太大的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM