While loop won't stop looping - python

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```

Related

Area/Type of triangle python

I'm supposed to find a code that asks the user for the base, height, and side of a triangle and then tells the user "This (type) triangle has an area of (area)" and then keeps asking the user for more numbers until they decide to quit. The code I have so far is...
again = "y"
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
print("Equilateral triangle")
elif side1==side2 or side2==side3 or side1==side3:
print("isosceles triangle")
else:
print("Scalene triangle")
print('This %f of the triangle is %0.2f' %area, certaintype)
Well done, so a few comments...
(1) indentation throws it off because the entire code should be under the while loop, so that your entire game will repeat itself after every triangle
(2) Instead of directly printing the "isosceles", "scalene" etc, "certaintype" ...you can store the value (eg scalene) under the certaintype variable using certaintype='scalene'. That way, you can print the type of triangle in your sentence later.
(3) The final print should also be under the while loop as you want to tell your users the answer after every triangle information entry.
(4) The syntax for string interpolation is %s for string variables like certaintype while the syntax for number/decimals is %d for number variables like area. Check out how I rewrote the final print line.
Somethig like this should work:
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
certaintype = "Equilateral triangle"
elif side1==side2 or side2==side3 or side1==side3:
certaintype = "isosceles triangle"
else:
certaintype = "Scalene triangle"
print('This %d of the triangle is %s' % (certaintype, area) )

Checking multiple input's validity in Python

I wrote a program that draws a convex regular polygon in turtle (given no. of sides and length). I also wanted it to check for invalid inputs, such that it would immediately ask if the user would like to try a different one. Is there a way to check both input's validity in less code, while also accounting for ValueError?
Also, a Terminator error occurs after every successful run. What might be causing it, and is there even a way to fix it when using this import command?
from turtle import *
def inp():
while True:
try:
n = int(input("Enter the number of sides of the polygon: "))
except ValueError:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
continue
else:
print("Goodbye!")
break
if n >= 3:
pass
else:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
inp()
else:
print("Goodbye!")
break
try:
l = float(input("Enter the length of the side in pixels: "))
except ValueError:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
continue
else:
print("Goodbye!")
break
if l > 0:
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
break
else:
y_n = input("Invalid input, type \"y\" if you'd like to try again: ")
if y_n == "y":
inp()
else:
print("Goodbye!")
break
inp()
For efficient parameter inputs, here are some steps:
Start with the value as something invalid
Using a while loop, ask the user for valid input
If valid input, exit the loop
In you're code, both parameters have the the same validation check, so you can use a function to check both.
Try this code:
from turtle import *
def validnum(nm):
return str(nm).isdigit() and int(nm) > 0 # integer and greater than zero
def inp():
n = l = '' # both invalid
while not validnum(n): # loop first entry until valid
n = input("Enter the number of sides of the polygon or 'q' to quit: ")
if n == 'q':
print("Goodbye!")
exit()
if not validnum(n):
print("Invalid entry")
while not validnum(l): # loop second entry until valid
l = input("Enter the length of the side in pixels or 'q' to quit: ")
if l == 'q':
print("Goodbye!")
exit()
if not validnum(l):
print("Invalid entry")
n, l = int(n), int(l) # convert entries to integers
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
inp()
Since both parameters have the same validation and only differ in the message prompt, you can make your code even more compact by putting the prompts in a list.
from turtle import *
def validnum(nm):
return str(nm).isdigit() and int(nm) > 0 # integer and greater than zero
def inp():
lstinp = ['',''] # both invalid
lstmsg = ['Enter the number of sides of the polygon', 'Enter the length of the side in pixels'] # both msgs
for i in range(len(lstinp)): # each input value
while not validnum(lstinp[i]): # loop until valid entry
lstinp[i] = input(lstmsg[i] + " or 'q' to quit: ") # msg
if lstinp[i] == 'q':
print("Goodbye!")
exit()
if not validnum(lstinp[i]):
print("Invalid entry")
n, l = int(lstinp[0]), int(lstinp[1]) # convert entries to integers
for i in range(1, n + 1):
forward(l)
left(360/n)
exitonclick()
inp()
I did not receive any errors when running the code.

How to break out of this while loop in 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

Trying to create a confirmation for my code so that it will allow user to change answer

I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")

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.")

Categories

Resources