Perimeter of a quadrilateral and other shapes - python

So today in science class I thought of making a python script for basic perimeter of a quadrilateral. Later in future I want to expand into circle and other shape but I got stuck in error. Please help.
My code:
print ("This is a program to find the perimeter of a quadrilateral. Input the length and breath and get the desired perimeter")
len = input("What is the length?")
bre = input("What is the breath?")
length = len + len
breath = bre + bre
perimeter = length + breath
print ("The perimeter of the quadrilateral is :" + perimeter)
https://repl.it/xHG
And the output comes funky. If l=2 and b=1 then output comes as 2211.
Also, how do you expand it into different shapes? I was thinking of using if and else options so if choice = circle then execute circle code elif if choice = triangle then execute triangle code. Does anyone have a better idea?

You need to convert you input to an int or float.
len = float(input("What is the length?"))
In your code
len = input("What is the length?")
len is a string, and therefor when you perform len + len you are performing String concatenation

Remember to convert data types
print ("This is a program to find the perimeter of a quadrilateral. Input the length and breath and get the desired perimeter")
len = input("What is the length?")
bre = input("What is the breath?")
len=int(len)
bre=int(bre)
length = len + len
breath = bre + bre
perimeter = length + breath
print ("The perimeter of the quadrilateral is :" + str(perimeter))

In Python 3, input returns a string (this is different in Python 2.x, which may be part of the confusion).
That means that length = len + len is actually performing string concatenation, ie. '2' + '2' = '22'.
Using either int(input("...")) or float(input("...")) will turn them into numbers. (note that both functions will create errors if the user puts in strings that can't be converted to numbers.

Related

"Too many values to unpack" when trying to write a code for length and width in Python

I am creating a code for L & W in Python. However, after I enter the L & W that is asks me to enter, it just gives me an error of "too many values to unpack" but I do not know what I may be doing wrong!
def main():
l,w = input("Enter length and width:")
result = rectangleAP(float(l), float(w))
print("The area is", result[0])
print("The perimeter is", result[1])
def rectangleAP(length, width):
Area = length * width
Perimeter = (length + width) * 2
return [Area, Perimeter]
if __name__ == "__main__":
main()
The input() function returns a singular value, a string. However, you are trying to assign one value (the return value of input()) to two variables, l and w. So, you probably want to split the string at some delimiter using the str.split() method:
length, width = input("Enter length and width ('length,width')").split(",")
Alternatively, you could do two input() calls:
length, width = input("Enter the length:"), input("Enter the width:")
(Which could also be separated out into two lines.)
Taking input of length and width separately can help you,
As well as using .split() as suggest by #quamrana can also help to take input using a separator such as comma(',')
def main():
l = input("Enter length:")
w = input("Enter width:")
#or
#l,w = input("Enter length and width:").split(',')
result = rectangleAP(float(l), float(w))
print("The area is", result[0])
print("The perimeter is", result[1])
def rectangleAP(length, width):
Area = length * width
Perimeter = (length + width) * 2
return [Area, Perimeter]
if __name__ == "__main__":
main()
Closest thing to what your are trying to do:
As Jacob Lee said, input() only returns one value, and you are giving it 2 variables to unpack.
Answer:
l, w = input("length: "), input("width")

Python If/else statements with math

I've been trying to make a circle area calculator, and I've got the basics. But if the user enters something like 5m, then I see an error. Instead of exiting with an error, I want to return "Enter a Number". Here is my code.
from math import pi
r = float(input("Input the radius of the circle : "))
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
if r==(str):
print("Enter a Number")
This here
if r==(str):
doesn't do what you are expecting.
You want to use string module for this check (Note that this should be done before attempting to convert input to a float):
import string
if set(r).issubset(string.digits)
Or there is a method on string object for this check:
r.isdigit()
But there is a better way:
from math import pi
try:
radius = float(input("Input the radius of the circle : "))
except ValueError:
print("Invalid input, enter a Number!")
else:
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
This shows how to handle invalid inputs. You may want to put this in a loop until you get a valid input.
You can repeatedly ask until a string that can be converted to a float is entered. You can detect failure to convert the string to a float by catching ValueError, which is the exception thrown when a type conversion fails.
while True:
try:
r = float(input("Input the radius of the circle : "))
break
except ValueError:
pass
Do this in place of your current line containing the input call, and get rid of the r == (str) test, which does not actually do anything close to what you are intending.
Also note if you are using Python2 you will need the raw_input function rather than input.

Python function returning a weird string

I've been working through a book called Exercises for Programmers as I am trying to learn Python.
https://pragprog.com/book/bhwb/exercises-for-programmers
At exercise 8 I ran into some trouble; I am meant to write code that prompts for how many people wanna order pizza, how many slices each and then it must calculate how many pizzas must be ordered (1 pizza = 8 slices) according to the total number of slices (persons * slices each) and the number of leftover slices (if there are any).
I think I've managed to suss it out except that once executed the method that calculates the number of leftover slices prints a weird string (it also contains a hex value?).
I've modulated everything into two files (trying to build good habits);
file 01:
main.py
import pizza as p
while True:
number_of_people = input("How many people are hungry for pizza? ")
number_of_slices_per_person = input("And how many slices per person? ")
try:
val = int(number_of_people) or int(number_of_slices_per_person)
print("\n" + number_of_people + " people have ordered " +
str(p.number_of_pizzas(number_of_people, number_of_slices_per_person)) + " pizzas.")
if int(number_of_slices_per_person) == 1:
print("Each person would like just a " + number_of_slices_per_person + " slice of pizza.")
else:
print("Each person would like " + number_of_slices_per_person + " slices of pizza.")
print("There are " + str(p.number_of_leftover_slices) + " pizza slices left over.")
break
except ValueError:
print("Please enter a valid number")
file 02:
pizza.py
def number_of_pizzas(p1, s1):
"""Calculates the number of pizzas according to the specified
requirements"""
total_pizzas = 0
total_slices = int(p1) * int(s1)
for s2 in range(0, total_slices):
if s2 % 8 == 0:
total_pizzas = total_pizzas + 1
return total_pizzas
def number_of_leftover_slices(total_pizzas):
"""Calculate the number of leftover slices of pizza"""
import main as m
total_pizzas = total_pizzas
leftover_slices = (int(total_pizzas) * 8) %
int(m.number_of_slices_per_person)
return leftover_slices
And this is the output I get;
'4 people have ordered 2 pizzas.'
'Each person would like 3 slices of pizza.'
'There are < function number_of_leftover_slices at 0x7f0a95e2c7b8 > pizza slices left over.'
My issue is the string that gets printed instead of the number I am expected to have calculated. Any thoughts on what I might have done wrong?
Thanks.
You have two problems. Firstly, you need to indent the return line at the end of number_of_leftover_slices
Next, when you call print on an object, Python will try to use either the _repr_ or _str_ method of that object to get a string representation of that object. What you're seeing is the string representation of your number_of_leftover_slices function. What you want to print is actually the output of that function.
n = p.number_of_pizzas(number_of_people, number_of_slices_per_person)
remain = p.number_of_leftover_slices(n)
print(remain)

How do I print a specific number of input statements in a loop?

I'm writing a code for my class but I'm having a little trouble at one part. I'm having the user input a number and then I need a loop to print specific statements based off the number the user inputted. So for example:
def main():
totalnumber = input("Enter the number of circles: ")
i = 0
for i in totalnumber:
i = 0 + 1
value = input("Enter the radius of circle",str(i)+":")
So I basically need the output to look like:
Enter the number of circles: 3
Enter the radius of circle 1:
Enter the radius of circle 2:
Enter the radius of circle 3:
I'm getting the error
TypeError: input expected at most 1 arguments, got 2
Is what I'm doing above okay to do or should I use a different approach?
If its okay what is wrong within my code that would be giving me that sort of error?
Try:
def main():
total_number = input("Enter the number of circles: ")
for number in range(1, int(total_number) + 1):
value = input("Enter the radius of circle {}: ".format(number))
main()
First: you need to convert the input to int, then iterate it by the number.
Notes:
use python pep-8 when naming your parameters user _ between the names
string formating is best with format try to use it.
Your for loop doesn't look correct.
Try
for number in range(int(totalnumber)):
i = number+1
value = input("Enter the radius of circle"+str(i)+":")

How to add variables in Python? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Python noob here. I'm trying to add a set of input variables defined in an 'if' statement and whenever I try to find the sum it will just display the values inline. For example, when a, b, c, and d equal 5, perimeter = 555...
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
d = raw_input("What is the length in feet of side 'd'?")
elif shape.lower() == "t":
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
else:
print "Please enter 'q' for quadrilateral or 't' for triangle."
if shape.lower() == "q":
perimeter = a + b + c + d
elif shape.lower() == "t":
perimeter = a + b + c
else:
print "Please make sure you enter numbers only."
print perimeter
str values can be added to each other much like numbers. The + operator you use works fine, but concatenates values for strings. The result of raw_input is a string (str), so that's why you'd see '555' in stead of 15. To sum numbers, use int() to coerce the values to numbers before adding them up:
try:
a = int(raw_input('gimme a number'))
except ValueError as e
print 'that was not a number, son'
Make sure that your raw_input actually Is an int():
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?")
if shape.lower() == "q":
try:
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side 'c'?")
d = raw_input("What is the length in feet of side 'd'?")
perimeter = int(a) + int(b) + int(c) + int(d)
except ErrorValue as e
print "Please make sure you enter numbers only."
elif shape.lower() == "t":
try:
a = raw_input("What is the length in feet of side 'a'?")
b = raw_input("What is the length in feet of side 'b'?")
c = raw_input("What is the length in feet of side '
perimeter = int(a) + int(b) + int(c)
except ErrorValue as e
print "Please make sure you enter numbers only."
else:
print "Please enter 'q' for quadrilateral or 't' for triangle."
for variables a, b, c, and d, use input(prompt) instead of raw_input(prompt).
raw_input returns a string,
but input returns the console input evaluated as a python literal. (As of right now, you're
concatenating strings, not adding integers).
Your code is not a good design. What if you want to add more shapes, hexagon, octagon and so on. You can actually use a dict to store shape mapping to number of sides. You don't have to write multiple if statements for each shape. You will have to do less type checking and you could use python builtin function sum to return the parameter. Go on now and try the following:
d = {'q': 4, 't': 3}
shape = raw_input("Is the plot a (q) quadrilateral or (t) triangle?\n")
if shape.lower() not in d:
print "Please enter 'q' for quadrilateral or 't' for triangle."
else:
sides = []
for i in range(0,d.get(shape.lower())):
side = raw_input("What is the length in feet of side " + str(i+1))
try:
sides.append(int(side))
except ValueError:
print "Integer value only"
print sum(sides)
I did this using a dictionary.
sides = {'a':0,'b': 0,'c': 0,'d': 0}
perimeter = 0
shape = raw_input("Is the plot a (q) quadrilatral or (t) triangle?: ")
if shape.lower() == "q":
for side, length in sides.iteritems():
sides[side] = input("What is the length (in feet) of side %s?: " % side)
perimeter+=int(sides[side])
elif shape.lower() == "t":
sides.pop("d",None)
for side, length in sides.iteritems():
sides[side] = input("What is the length (in feet) of side %s?: " % side)
perimeter+=int(sides[side])
else:
print "Please enter 'q' or 't'."
print "Perimeter is: %d" % perimeter
I figured a dictionary would be easier to use. Might be much cleaner, rather than repeat yourself.

Categories

Resources