0

Very new to python. I've created a simple program that makes use of a while loop to better learn about loops. The program:

  1. Ask the user if they'd like their miles per gallon calculated

As long as the user answers "yes" I want the program to keep performing the calculation. If they say no, the loop ends.

My problem is I cannot seem to get the loop to close.

calculate_question = input("Would you like to calculate your MPG? ")
miles_driven = float(int(input("How many miles did you drive ")))

while calculate_question == "yes" or calculate_question == "y" or calculate_question == "Yes" or calculate_question == "Y":
def mpg_calc():
    import random
    gallons_used = float(random.randint(1,1000))
    final_mpg = str(miles_driven/gallons_used)
    print("Your MPG is " + final_mpg)
mpg_calc();
calculate_question = input("Would you like to calculate your MPG? ")
miles_driven = float(int(input("How many miles did you drive ")))
else:
print("Then you'll never know!")

4 Answers 4

1
  • Keep running the loop with while True
  • Break the loop by checking the condition with if-else and use break
  • Keep functions separate, not inside the loop.
  • Use modern f-Strings: A New and Improved Way to Format Strings in Python (e.g. print(f'say something with a {variable}'))
  • Remove unnecessary conversions to int in float(int(input("How many miles did you drive "))) and float in float(random.randint(1,1000))
  • Instead of using a bunch of or conditions, calculate_question == "yes" or calculate_question == "y", use in, variable in [list of values]
def mpg_calc(miles_driven: float):
    gallons_used = random.randint(1, 1000)
    final_mpg = miles_driven / gallons_used
    print(f"Your MPG is {final_mpg}")

while True:
    calculate_question = input("Would you like to calculate your MPG? ").lower()
    if calculate_question in ['yes', 'y']:
        miles_driven = float(input("How many miles did you drive "))
        mpg_calc(miles_driven)
    else:
        print("Then you'll never know!")
        break
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much!
@TheodoreSteiner Glad to help. Check out RealPython for the best tutorials. I'm not affiliated, just a fan of their work.
Can you explain this line to me: " print(f"Your MPG is {final_mpg}")"? What is the f? I get that the { } are allowing me to include the string...
Those are f-strings. I'll add a link to the answer in just a sec
You're a lifesaver!
0

@Trentom_M gave a good example of a working code, here's the why.

You need to define the mpg_func before the while loop, and also need to give the right indentation to the statements you want to execute inside the while. Since python doesn't use brackets {}, it recognises the statements the follow the correct indentation, for example:

while condition:
    this statement is executed inside the while 
    this statement is executed inside the while
this statement is NOT executed inside the while

2 Comments

Ahhhh! That makes sense! I wasn't sure what was meant by indentation error
Thank you so much!
0

The two major issues with your code are:

  1. The loop's body is defined by indentation. Since you didn't indent anything, the loop does not do anything.
  2. You are defining a new function in the middle of the loop's statement body.

User experience-wise it would be better to ask for the miles only when the user has answered positively, and refresh the question at the end of the loop.

So the minimum changes to make are:

def mpg_calc(miles_driven):
    import random
    gallons_used = float(random.randint(1,1000))
    final_mpg = str(miles_driven/gallons_used)
    print("Your MPG is " + final_mpg)

calculate_question = input("Would you like to calculate your MPG? ")

while calculate_question == "yes" or calculate_question == "y" or calculate_question == "Yes" or calculate_question == "Y":
  miles_driven = float(int(input("How many miles did you drive ")))
  mpg_calc(miles_driven)
  calculate_question = input("Would you like to calculate your MPG? ")
else:
  print("Then you'll never know!")

There is a lot of room for improvement like using the .lower() function on the input to make the check case-insensitive altogether, but that is basically your code with minimal changes.

Comments

0

There was indentation error

calculate_question = input("Would you like to calculate your MPG? ")
miles_driven = float(int(input("How many miles did you drive ")))
#define function outside the loop
def mpg_calc():
    import random
    gallons_used = float(random.randint(1,1000))
    final_mpg = str(miles_driven/gallons_used)
    print("Your MPG is " + final_mpg)

while calculate_question == "yes" or calculate_question == "y" or calculate_question == "Yes" or calculate_question == "Y":

    mpg_calc();#this statement was not indented well
    calculate_question = input("Would you like to calculate your MPG? ")
    miles_driven = float(int(input("How many miles did you drive ")))
else:
    print("Then you'll never know!")

1 Comment

In fact you can use "else" after a while loop. The else statements will be executed once if the condition was evaluated to false. They will however not be executed if you leave the loop because of a break statement or an exception; that's why it has a limited use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.