python code

Can I shorten this code with the python "continue" construct. I'm thinking that
continue will eliminate having to repeat the prompt to re-enter the miles driven and gallons used - everything from "if choice == yes" on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# welcome message
print("The Miles Per Gallon Program")
print()


# get input from the user
miles_driven = float(input("Enter miles driven: "))
gallons_used = float(input("Enter gallons of gas used: "))

# verify input
if miles_driven <= 0:
    print("Miles driven must be greater than zero. Please try again.")
elif gallons_used <= 0:
    print("Gallons used must be greater than zero. Please try again.")
else:
    # calculate and display miles per gallon
    mpg = round((miles_driven / gallons_used), 2)
    print("Miles Per Gallon:  ", mpg)

    # lower() returns lower case character
    choice = "y"
    while choice.lower() == "y":
        choice = input("\nI can calculate mpg for the next leg of your travels! (y/n): ")
        if choice == "y":
            miles_driven = float(input("Enter miles driven: "))
            gallons_used = float(input("Enter gallons of gas used: "))

            mpg = round((miles_driven / gallons_used), 2)
            print("Miles Per Gallon:  ", mpg)
        else:
            print()
print("Okay, bye!")
Is there a do-while loop in Python?
It's perhaps the simpler workaround to avoid asking the user the same question twice. If there isn't, as I suspect, you can try something like this:
(BTW, using a user-friendly programming language should not encourage you to keep your code untidy: splitting it into functions is yet advisable)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <cctype>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <utility>

std::pair<double, double> getMilesAndGallons();
double calculateMpg(const std::pair<double, double>& milesgallons);
std::string& mytolower(std::string& tobeconverted);

int main()
{
    // welcome message
    std::cout << "The Miles Per Gallon Program\n";
    

    // mytolower() returns lower case std::string
    std::string choice;
    while(mytolower(choice) != "n") {
        std::pair<double, double> mgdata = getMilesAndGallons();
        std::cout << "Miles Per Gallon:  " 
                  << std::fixed << std::setprecision(2)
                  << calculateMpg(mgdata) << '\n';
        std::cout << "\nI can calculate mpg for the next leg of your travels! "
                     "(y/n): ";
        std::getline(std::cin, choice);
        if(mytolower(choice) != "y") { break; }
    }
    std::cout << "Okay, bye!\n";

    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return 0;
}


std::pair<double, double> getMilesAndGallons()
{
    double miles_driven {};
    while(miles_driven <= 0) {
        std::cout << "Please enter miles driven: ";
        std::cin >> miles_driven;
        std::cin.ignore(1);
        if(miles_driven <= 0) {
            std::cout << "Miles driven must be greater than zero. "
                         "Please try again.";
        }
    }

    double gallons_used {};
    while(gallons_used <= 0) {
        std::cout << "Please enter gallons of gas used: ";
        std::cin >> gallons_used;
        std::cin.ignore(1);
        if(gallons_used <= 0) {
            std::cout << "Gallons used must be greater than zero. "
                         "Please try again.";
        }
    }

    return std::make_pair(miles_driven, gallons_used);
}


double calculateMpg(const std::pair<double, double>& milesgallons)
{ return std::get<0>(milesgallons) / std::get<1>(milesgallons); }


std::string& mytolower(std::string& tobeconverted)
{
    if(tobeconverted.empty()) return tobeconverted;
    for(auto& c : tobeconverted) { c = std::tolower(c); }
    
    return tobeconverted;
}


Or, in Python:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#
def getMilesAndGallons() :
    miles_driven = 0;
    while miles_driven <= 0 :
        miles_driven = float(input("Enter miles driven: "))
        if miles_driven <= 0 :
            print("Miles driven must be greater than zero. Please try again.")

    gallons_used = 0;
    while gallons_used <= 0 :
        gallons_used = float(input("Enter gallons of gas used: "))
        if gallons_used <= 0:
            print("Gallons used must be greater than zero. Please try again.")
            
    return (miles_driven, gallons_used)
    
def calculateMpg(*mgdata) :
    return round((mgdata[0] / mgdata[1]), 2)

# welcome message
print("The Miles Per Gallon Program")
print()

# lower() returns lower case character
choice = "y"
while choice.lower() != "n":
    # get input from the user
    mgdata = getMilesAndGallons()
    # calculate and display miles per gallon
    mpg = calculateMpg(*mgdata)
    print("Miles Per Gallon:  ", mpg)
    choice = input("\nI can calculate mpg for the next leg of your travels! (y/n): ")
    if choice != "y":
        break;

print("Okay, bye!")


(I don't want to appear unwelcoming, but this is supposed to be a C++ forum)
Topic archived. No new replies allowed.