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.")
Related
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) )
import circle
pi = 3.1415
def main():
area(radius)
circumference(radius)
def menu():
print("Type a for area of circle")
print("Type b for circumference of a circle")
print("Type c to END PROGRAM")
loop=True
while loop:
menu()
choice = input('Please enter your choice: ')
if choice=="a":
radius = float(input ("Input the radius of the circle : "))
print(circle.area(radius))
elif choice=="b":
radius = float(input ("Input the radius of the circle : "))
print(circle.circumference(radius))
else:
print("Goodbye!")
def area(radius):
return pi * radius**2
def circumference(radius):
return 2 * pi * radius
main()
I am trying to make a simple menu that either gives the user one of the instructed outputs if they type one of the three letters. So if I were to type the letter 'a', I would be asked to input the radius of the circle and then be given the area in return. I hope that makes sense.
However, when I try to test this menu, I am told none of the letters are defined, so I'm kind of confused why it's not working.
You are very close, just a couple of things are derailing your program.
First: Because you have created functions, you don't need to import a 'circle' mod. Where does this come from? Are you trying to define a Class object or modual?
Second: Your functions need to be defined in the program BEFORE they are called. You had them placed after, which was causing errors.
Third: You forgot to set loop to False when "c" is entered. Lacking this, then loop never ends.
Hope this helps!
def area(radius):
return pi * radius**2
def circumference(radius):
return 2 * pi * radius
#import circle
pi = 3.1415
def main():
area(radius)
circumference(radius)
def menu():
print("Type a for area of circle")
print("Type b for circumference of a circle")
print("Type c to END PROGRAM")
loop=True
while loop:
menu()
choice = input('Please enter your choice: ')
if choice=="a":
radius = float(input ("Input the radius of the circle : "))
print(area(radius))
elif choice=="b":
radius = float(input ("Input the radius of the circle : "))
print(circumference(radius))
else:
print("Goodbye!")
loop = False
import circle
pi = 3.1415
def main():
area(radius)
circumference(radius)
def menu():
print("Type a for area of circle")
print("Type b for circumference of a circle")
print("Type c to END PROGRAM")
loop=True
while loop:
menu()
choice = input('Please enter your choice: ')
if choice== "a":
radius = float(input ("Input the radius of the circle : "))
print(circle.area(radius))
elif choice== "b":
radius = float(input ("Input the radius of the circle : "))
print(circle.circumference(radius))
else:
print("Goodbye!")
def area(radius):
return pi * radius**2
def circumference(radius):
return 2 * pi * radius
main()
In my last question, I recieved help on my menu (which is working now!) However, when I input the radius, I recieve the error:
AttributeError: partially initialized module 'circle' has no attribute 'area' (most likely due to a circular import)
I've made some changes to your code and it should work as intended. Let me know if you have any questions!
Basically, remove the import, remove the main() function, and shift the area() and circumference() to the top.
pi = 3.1415
# function to print the menu options
def menu():
print("Type a for area of ")
print("Type b for circumference of a circle")
print("Type c to END PROGRAM")
# function to calculate area
def area(radius):
return pi * radius**2
# function to calculate circumference
def circumference(radius):
return 2 * pi * radius
# menu loop
while True:
# display menu
menu()
# prompt for user's choice
choice = input('Please enter your choice: ')
if choice == "a":
radius = float(input("Input the radius of the circle : "))
print(area(radius))
elif choice == "b":
radius = float(input("Input the radius of the circle : "))
print(circumference(radius))
else:
print("Goodbye!")
break
Kill import circle line. Change circle.area to area and circle.circumference to circumference. Move definitions of area and circumference functions to the top, so they are defined before they are used. Kill main() line in the end. Read https://docs.python.org/3/tutorial/index.html instead of typing magic spells you don't understand and hoping that they'll work somehow :)
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```
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