简体   繁体   中英

What is wrong with my code on calculating area of square/rectangle?

shape = input("Square or Rectangle ? : ")

width = float(input("Enter The Width : "))

if input in shape :

 "Square, square"

 area = width * width

 print ("")

 print ("The Area Of The Given Square is" + area)








length = float(input("Enter The Area : "))

area = width * length

print ("")

print ("The Area Of The given Rectangle is ", area)

input("Enter To Exit")

I am new to Python scripting and wanted to make a simple py that calculates the area of a square or rectangle. But when I open it, it asks for the "Square or Rectangle ?" I input Square, then it asks for width and it abruptly closes. Same happens when I put in Rectangle. Again I am a noobie at python and just going off of what I can find. I am not sure on how to frame a question for this to search and find an answer so I resorted to making one.

This can work:

shape = raw_input("Square or Rectangle : ")

if shape == 'Square':
    width = float(raw_input("Enter The Width : "))
    area = width * width
    print ("")
    print ("The Area Of The Given Square is " + str(area))

if shape == 'Rectangle':
    width = float(raw_input("Enter The Width : "))
    length = float(raw_input("Enter The length : "))
    area = width * length
    print ("")
    print ("The Area Of The given Rectangle is " + str(area))

Rest you can improve accordingly.

There are a couple of problems with your code.

1) The condition

if input in shape:

You never defined a variable "input". Furthermore, I'm not real sure why you are checking a condition here anyways. If you're trying to verify that shape is either a rectangle or square consider this code instead:

if shape in ["rectangle", "square"]:

2) The code

"Square, square"

does nothing, and is in fact invalid syntax.

3) The line

print("The area of the given square is" + area)

is invalid string concatenation for the print function. (note you can concatenate this way OUTSIDE of the print function) Use commas instead.

print("The area of the given square is", area)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM