How to break out of this while loop in python - python

I wrote a simple program for class; it gives the user the choice of 5 different questions to solve, area of a circle, volume of a cylinder/cube, or surface area of cylinder/cube. The user has to decide which problem they want to solve, and if they make an invalid decision the program loops back to the start to let them try again. However, I can't figure out how to break the loop; after solving one of the problems it still loops back to the start of the program.
invalid_input = True
def start () :
#Intro
print("Welcome! This program can solve 5 different problems for you.")
print()
print("1. Volume of a cylinder")
print("2. Surface Area of a cylinder")
print("3. Volume of a cube")
print("4. Surface Area of a cube")
print("5. Area of a circle")
print()
#Get choice from user
choice = input("Which problem do you want to solve?")
print()
if choice == "1":
#Intro:
print("The program will now calculate the volume of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate volume
if radius > 0 and height > 0:
import math
volume = math.pi * (radius**2) * height
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Inputs, please try again.")
print()
elif choice == "2":
#Intro:
print("The program will calculate the surface area of your cylinder.")
print()
#Get radius and height
radius = float(input("What is the radius?"))
print()
height = float(input("What is the height?"))
print()
#Calculate surface area
if radius > 0 and height > 0:
import math
pi = math.pi
surfaceArea = (2*pi*radius*height) + (2*pi*radius**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + " units." )
invalid_input = False
elif radius < 0 or height < 0:
print("Invalid Inputs, please try again.")
print()
elif choice == "3":
#Intro:
print("The program will calculate the volume of your cube.")
print()
#Get edge length
edge = float(input("What is the length of the edge?"))
print()
#Calculate volume
if edge > 0:
volume = edge**3
roundedVolume = round(volume,2)
#Print volume
print("The volume is " + str(roundedVolume) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "4":
#Intro:
print("The program will calculate the surface area of your cube.")
print()
#Get length of the edge
edge = float(input("What is the length of the edge?"))
print()
#Calculate surface area
if edge > 0:
surfaceArea = 6*(edge**2)
roundedSA = round(surfaceArea,2)
#Print volume
print("The surface area is " + str(roundedSA) + (" units."))
invalid_input = False
else:
print("Invalid Edge, please try again")
print()
elif choice == "5":
#Intro
print("The program will calculate the area of your circle")
print()
#Get radius
radius = float(input("What is your radius?"))
if radius > 0:
#Calculate Area
import math
area = math.pi*(radius**2)
roundedArea = round(area,2)
print("The area of your circle is " + str(roundedArea) + " units.")
invalid_input = False
else:
print("Invalid Radius, please try again")
print()
else:
print("Invalid Input, please try again.")
print()
while invalid_input :
start ()

The preferred way for this kind of code is to use a while Truestatement like so,
while True:
n = raw_input("Please enter 'hello':")
if n.strip() == 'hello':
break
This is an example, that you can correctly change for your needs.Here is the link to documentation.

You can add an option to exit.
print('6. Exit')
...
if choice=='6':
break
Or you can break on any non-valid input.
else:
break

invalid_input = True is a global variable (outside any function).
Setting invalid_input = False in your function sets a local variable, unrelated to the global one. To change the global variable, you need the following (greatly simplified) code:
invalid_input = True
def start():
global invalid_input
invalid_input = False
while invalid_input:
start()
Global variables are best to be avoided, though. Better to write a function to ensure you have valid input:
def get_choice():
while True:
try:
choice = int(input('Which option (1-5)? '))
if 1 <= choice <= 5:
break
else:
print('Value must be 1-5.')
except ValueError:
print('Invalid input.')
return choice
Example:
>>> choice = get_choice()
Which option (1-5)? one
Invalid input.
Which option (1-5)? 1st
Invalid input.
Which option (1-5)? 0
Value must be 1-5.
Which option (1-5)? 6
Value must be 1-5.
Which option (1-5)? 3
>>> choice
3

Related

How can I go back to a specific line of code in python?

while True:
def main():
userinp = str(input("Distance in km or miles?: "))
km = 1
miles = 0.621371
formula = km / miles
if userinp == "km":
kminp = int(input("Enter a distance in km: "))
kmans = kminp / formula
print(kmans)
elif userinp == "miles":
mileinp = int(input("Enter a distance in miles: "))
milesans = mileinp * formula
print(milesans)
else:
print("I didn't get that, please try again")
main()
I'm new to python. The code above is supposed to convert miles to km or km to miles depending on the input from the user at the start. The calculating part works, but I want to make it so that when the user inputs "km" or "miles" then the program ends after the if or elif statements. It loops back to the start when userinp isn't "km" or "miles" which is what I want but keeps looping even if the inputs are right.
It generally is not good programming practice to have a while True: statement or to define functions within a loop.
Use conditions to exit out of while loops. Here is one possible solution to your problem:
def main():
stay_in_program = True
userinp = str(input("Distance in km or miles?: "))
km = 1
miles = 0.621371
formula = km / miles
if userinp == "km":
kminp = int(input("Enter a distance in km: "))
kmans = kminp / formula
print(kmans)
stay_in_program = False
elif userinp == "miles":
mileinp = int(input("Enter a distance in miles: "))
milesans = mileinp * formula
print(milesans)
stay_in_program = False
else:
print("I didn't get that, please try again")
stay_in_program = True
return stay_in_program
while main():
pass
In the example above, the main() function will return either True or False depending on the value of the stay_in_program variable. This variable is set at different parts of the if-statement. The main() function will continue to re-run until the stay_in_program variable is set to False.
You might want to wrap just the "ask for one of these choices" loop in a second function:
def prompt_choice(prompt, choices):
while True:
choice = input(prompt)
if choice in choices:
return choice
print("I didn't get that, please try again")
def main():
userinp = prompt_choice("Distance in km or miles?: ", ["km", "miles"])
km = 1
miles = 0.621371
formula = km / miles
if userinp == "km":
kminp = int(input("Enter a distance in km: "))
kmans = kminp / formula
print(kmans)
elif userinp == "miles":
mileinp = int(input("Enter a distance in miles: "))
milesans = mileinp * formula
print(milesans)
(Also, in general, it's not good form to wrap functions in loops (while ...: def....:)

While loop won't stop looping

I'm kind of new to python or coding in general and I have run into a problem in my while-loop. I want to point out that the while-loop only works when the variable "loop" = True
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
When I write "No" when the program asks me if I want to do this again, it still loops the sequence, even though the variable "loop" is supposed to be false when i type "No" which is supposed to stop the loop.
Full code (while loop at the bottom of the code):
#Solving for the area in a shape automatically
import math
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
def sqr_area(): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop_again()
def rec_area(): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop_again()
def tri_area(): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop_again()
def cir_area(): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop_again()
while loop == True: #While loop, asking sequence
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose
Thanks in advance!
Don't use recursion when you should be using a loop, and loop_again should return a value instead of setting loop globally.
import math
# Returns true once the input is Yes or false once the input is No
def loop_again():
while True:
response = str(input("Do you want to do this again? Yes or No: "))
if response == "Yes":
return True
elif response == "No":
return False
else:
print("Please answer yes or no: ")
loop_again should be called after the relevant *_area function has returned, not inside each function. The functions don't need to know or care
about the value of choose; they are only called when they are intended to be called.
# Print the area of a square
def sqr_area():
a = float(input("Input the length of the side here: "))
print(a ** 2)
# Print the area of a rectangle
def rec_area():
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
# Print the area of a triangle
def tri_area():
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
# Print the area of a circle
def cir_area():
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
The final loop can run indefinitely, until loop_again returns True.
# Loop until the user chooses to not run again
while True:
choose = input("Input what shape that you want to figure out the area of here: ")
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
continue
if loop_again():
break
In the loop_again() function you have to add this at the beginning:
global loop
Otherwise, the variable is considered local and won't have any effect on the other loop variable that's in the outer scope.
It's a context variable problem. The loop variable you have in loop_again() and the one inside the while loop are different ones.
Every variable inside a function, in python, is local variable, unless its an argument, or if you use global variable in the main and in inside the functions.
So make it global or pass and return it inside the functions
#Solving for the area in a shape automatically
import math
global loop
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
global loop
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
def sqr_area(): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop_again()
def rec_area(): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop_again()
def tri_area(): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop_again()
def cir_area(): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop_again()
while loop == True: #While loop, asking sequence
global loop
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose
you need to say in every function that loop is the global one, otherwise python you interpret it as a local variable.
the other way is:
import math
loop = True #Makes the asking sequence work
def loop_again(loop ): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
return loop
def sqr_area(loop): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop = loop_again()
return loop
def rec_area(loop): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop = loop_again(loop)
return loop
def tri_area(loop): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop = loop_again()
def cir_area(loop): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop = loop_again()
while loop == True: #While loop, asking sequence
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
loop = sqr_area(loop )
elif choose == "Rectangle":
loop = rec_area(loop )
elif choose == "Triangle":
loop = tri_area(loop )
elif choose == "Circle":
loop = cir_area(loop )
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose```

Score system in game. PYTHON 3.5

def LoginScreen():
global User_Points
User_Points = 5
print("Welcome to Area Trainer")
print("Please enter the username for your account")
global user_name
user_name = str(input())
save = open(user_name + '.txt', 'w')
points = open(user_name + 'Score' + '.txt', 'w+')
points.write(str(User_Points))
PasswordCheck= True
while PasswordCheck:
user_password = input("type in your password: ")
if len(user_password) < 8:
print("your password must be 8 characters long")
elif not any(i.isdigit() for i in user_password):
print("you need a number in your password")
elif not any(i.isupper() for i in user_password):
print("you need a capital letter in your password")
elif not any(i.islower() for i in user_password):
print("you need a lowercase letter in your password")
else:
PasswordCheck = False
def MenuTriangle():
global User_Points
print('''Here is a triangle with a height of 12cm and a width of 29cm
/\ | *Not to scale.
/ \ |
/ \ | 12cm
/ \ |
<------->
29cm
You must find out the area and select the correct answer from these options''')
print('''A) 175
B) 174
C) 2000
D) 199
''')
user_input = input().upper()
if user_input == "A":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "C":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "D":
print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
MenuTriangle2()
elif user_input == "B":
print("Congratulations! You got it right, someone's a smart cookie. Here have two points!")
reading = open(user_name + 'Score' + '.txt')
score = reading.read()
score = int(score) + 2
print("Your score is", score)
points = open('ok' + 'Score' + '.txt', 'w+')
points.write(str(score))
MenuStart()
def MenuStart():
print("Welcome to the mathematical area game!")
print("In this game you will be required to calculate the area of multiple shapes.")
print("To do this you must know how to calculate the area of different shapes with increasing difficulty")
print('''Please select a shape you want to play,
A) Triangle
B) Square
C) Circle''')
user_input = input().upper()
if user_input == "A":
print("You have chosen to calculate the area of a triangle!")
MenuTriangle()
elif user_input == "B":
print("You have chosen to calculate the area of a square!")
MenuSquare()
elif user_input == "C":
print("You have chosen the calculate the area of a circle!")
MenuCircle()
else:
print("Oops! I didn't understand that >:")
MenuStart()
LoginScreen()
MenuStart()
Hello, I am trying to make a small game where the user has to guess what the area of the shape is and if they get it right then they get 2 points however, I am using an external file to store the score of the game in but every time I play through the game by entering my name, password I will see that the value of the score will be changed to 2 after I get the answer right but then when it calls the menu function the score in the file is reset and I don't know why
CORRECT ANSWER TO SAVE PRESSING BUTTONS IS B
THE ONLY OPTION AVAILABLE TO PLAY IS TRIANGLE FOR NOW. If anyone could please figure this out it would be greatly appreciated.
This is because Python automatically overrides data in a file every time it is being opened. You are opening the file multiple times by calling the function multiple times.

Asking the user what kind of function they want

I have an area calculator and I want the user in the beginning choose what thing to calculate instead of going down the list. is there a code for to ask the user, and stop the other code. And after the user chooses, take the user to that specific function. Then afterwards, take them back to the ask screen? Need some advice.
import math
def square():
print ("Area of Square")
print ("")
S = float(input("Enter Length of Square:"))
A = round((S**2),3)
print (A, "is the Area of the Square")
print("")
print("")
square()
def rectangle():
print("Area of Rectangle")
print ("")
L = float(input("Enter Length of Rectangle:"))
W = float(input("Enter Width of Rectangle:"))
A = round((L*W),3)
print (A, "is the Area of the Rectangle")
print("")
print("")
rectangle()
def paralelogram():
print("Area of Paralelogram")
print("")
B = float(input("Enter Base of Paralelogram:"))
H = float(input("Enter Height of Paralelogram:"))
A = round((B*H),3)
print (A, "is the Area of the Paralelogram")
print("")
print("")
paralelogram()
def triangle():
print("Area of Triangle")
print("")
B = float(input("Enter Base of Triangle:"))
H = float(input("Enter Height of Triangle:"))
A = round(((B*H)/2),3)
print (A, "is the Area of the Triangle")
print("")
print("")
triangle()
def circle():
print("Area of Circle")
print("")
r = float(input("Enter Radius of Circle:"))
A = round(math.pi*(r**2),3)
print (A, "is the Area of the Circle")
print("")
print("")
circle()
def trapezoid():
print("Area of Trapezoid")
print("")
B1 = float(input("Enter Base 1 of Trapezoid:"))
B2 = float(input("Enter Base 2 of Trapezoid:"))
H = float(input("Enter Height of Trapezoid:"))
A = round((((B1+B2)/2)*H),3)
print (A, "is the Area of the Trapezoid")
print("")
print("")
trapezoid()
def sphere():
print("Area of Sphere")
print("")
r = float(input("Enter Radius of Sphere:"))
A = round((((r**2)*4)*math.pi),3)
print (A, "is the Area of the Sphere")
print("")
sphere()
A more Pythonic way of doing this is to store references to the functions in a dictionary:
area_func = {'triangle': triangle, 'square': square, 'rectangle': rectangle,
'paralelogram': paralelogram, 'circle': circle, 'trapezoid': trapezoid,
'sphere': sphere}
while True:
shape = input('What shape do you want to calculate the area of ("stop" to end)?')
if shape == 'stop':
break
try:
area_func[shape]()
except KeyError:
print("I don't recognise that shape.")
continue
This works because functions, like everything else in Python, are objects. So you can store them as values in a dictionary, assign variable names to them, etc. The expression area_func[shape] is thus a reference to a function, for example, triangle, which can then be called (by appending (), an empty set of parentheses since your functions don't take any arguments).
As others have noted, you probably don't want the function calls after each definition. And, to be pedantic, parallelogram is the correct spelling.
You can do that with a while loop.
#your functions here
options="""1-)Square
2-)Rectangel
3-)Paralelogram
4-)Triangle
5-)Trapezoid
6-)sphere
"""
while True:
print (options)
user=input("Please choose a valid option: ")
if user=="1":
square()
continue
elif user=="2":
rectangel()
continue
..
..
.. #same codes with elif statement till 6.
..
else:
print ("It's not a valid choose.Please choose a valid one.")

Expected an indented block [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 6 months ago.
I'm getting an Expected an indented block here's the code, thank you for any help.
#Given the menu the user will calculate the area of square, circle, rectangle
from math import pi
def main ():
#declare and initialize variables
#float radius = length = width = base = height = 0.0
radius = length = width = base = height = 0.0
#float areaCircle = areaRectangle = areaTriangle = 0.0
areaCircle = areaRectangle = areaTriangle = 0.0
#int menuChoice = 0
menuChoice = 0
#display intro
while menuChoice != 4:
#Display menu
print("Geometry Calculator")
print("1) Calculate the Area of a Circle")
print("2) Calculate the Area of a Rectangle")
print("3) Calculate the Area of a Triangle")
print("4) Quit")
#Prompt for menuChoice
if menuChoice == 1:
while radius < 0:
#prompt for radius
radius = eval(input("What is radius of circle: "))
if radius < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaCircle
areaCircle = pi*r**2
#display areaCircle
print("The area of the circle is: ", areaCircle)
elif menuChoice == 2:
while length < 0:
#prompt for length
length = eval(input("What is the length of the rectangle: "))
if length < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while width < 0:
#prompt for width
width = eval(input("What is the width of the rectangle: "))
if width < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaRectangle
areaRectangle = length * width
#diplay areaRectangle
print("The area of the rectangle is: ", areaRectangle)
elif menuChoice == 3:
while base < 0:
#prompt for base
base = eval(input("What is the length of the base of the triangle:"))
if base < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while height < 0:
#prompt for height
height = eval(input("What is height of triangle"))
if height < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaTriangle
areaTriangle = 1/2 * base * height
#display areaTriangle
print("The area of the triangle is: ", areaTriangle)
elif menuChoice == 4:
#display exit message
else:
#display invalid
print("You must choose a number between 1-4 from the menu")
The error pops up at else. I've tried indenting one at a time, probably something small i'm overlooking third week into programming.
You need some sort of placeholder for the final elif block. You may use the standard Python non-op, pass:
elif menuChoice == 4:
#display exit message
pass
I'm assuming this will eventually be replaced by some other code, so the problem would have resolved itself had you continued working. If you are not planning on putting anything in this block, omit it entirely. There is no need for a conditional branch that does nothing.
It's the last line (#display exit message). Add a correctly indented pass statement, until you know what to do here. You need an actual python statement here, not a comment.

Categories

Resources