I have written this program which asks the user about how many rectangles they wants to print out. It also asks for the width and height of each, and prints the triangles. After asking the height and width of each, it moves onto the next rectangle and so on.
This all works fine using the program I've made but at the end I want to print out the total area of all the rectangles that the user has created. How can I update my code and achieve this? How is it possible to store the area of the first rectangle and add the area of the second to this first area and so on?
Here is the code:
size = input("How many rectangles?" ) #asks the number of rectangles
i=1
n = 1
while i <= size:
w = input("Width "+str(n)+"? ") #asks for width of each rectangle
h = input("Height "+str(n)+"? ") #asks for height of each rectangle
n=n+1
h1=1
w1=1
z = ""
while w1 <= w:
z=z+"*"
w1+=1
while h1<=h:
print z
h1+=1
i+=1
How about you just accumulate the total area?
Above your loop, do:
area = 0
Then, somewhere inside your loop, after you've got w and h from the user, just do
area += w * h
When you finish looping, area will contain the total area.
This code should really use a for loop instead of a while loop to keep track of counters, keep numbers in variables instead of just "*" strings, and use += instead of x=x+1 in a few places, among other things, but here's a minimal step to solve the total area problem you specifically asked about:
size = input("How many rectangles?" ) #asks the number of rectangles
i=1
n = 1
area = 0
while i <= int(size):
w = float(input("Width "+str(n)+"? ")) #asks for width of each rectangle
h = float(input("Height "+str(n)+"? ")) #asks for height of each rectangle
n+=1
h1=1
w1=1
z = ""
while w1 <= w:
z=z+"*"
w1+=1
while h1<=h:
print(z)
h1+=1
area += len(z)
i+=1
print('total area = ',area)
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
Trying to find the area of a triangle, the code is pretty simple but whenever I run the code nothing happens, not even the first line of print("width of the base").
print("width of the base")
width = input()
print("height")
height = input()
variable1 = width*height
area = variable1/2
print("area = {0}".format(area))
What you are doing will only work for a right angled triangle, regardless, i agree with #BuddyBoblll that you need to type a number.
Instead of using the (height*base/2) formula, you can use the Heron's formula, which will need only one or two additional lines of code. Furthermore, it will find area for all types of triangles, and is not restricted to right angled ones.
# Three sides of the triangle is a, b and c:
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
The output that i am getting for this code is:
Enter first side: 5
Enter second side: 12
Enter third side: 13
The area of the triangle is 30.00
Side note, i am working on mac osx on a Python 3.8.0 version.
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")
My problem is that my height of the tower variable is not printing at all, and I feel if it did it would not work. I cannot understand why this isn't working please help.
My Code:
import turtle
bob = turtle.Turtle()
turtle.setup(width = 400, height = 300)
turtle.bgcolor("orange")
n = int(input("Please enter number of towers: "))
h = (input("Please enter height of towers : "))
x = str(h.split(","))
def ocean():
bob.setpos(-200, 0)
bob.color("midnightblue", "midnightblue")
bob.begin_fill()
for x in range(1, 3):
bob.forward(400)
bob.right(90)
bob.forward(150)
bob.right(90)
bob.end_fill()
def tower():
bob.right(90)
for x in range (0,n):
bob.forward(x)
ocean()
tower()
I find that beginning programmers either write too much code or too little code. In the case of your tower() function, it's too little code. You also use the x variable for two different purposes -- get out of the habit of using single letter variable names. Your "Please enter number of towers: " question isn't needed as the number of tower heights entered gets you that same value. This is your first logic error:
x = str(h.split(","))
We do want to split that input string on comma, but we want to turn it into a list of number instead of strings. One way:
x = map(int, h.split(","))
The next issue surfaces in tower():
for x in range (0,n):
bob.forward(x)
This reuse of x masks our heights, what you really wanted was something like:
for idx in range(n):
bob.forward(x[idx])
...
But we don't need to use indexing, we can simply walk x itself. A rework of your code with the above fixes, some tower drawing, and some style changes:
from turtle import Turtle, Screen
WIDTH, HEIGHT = 400, 300
def ocean():
bob.setpos(-WIDTH/2, 0)
bob.color("midnightblue")
bob.begin_fill()
for _ in range(2):
bob.forward(WIDTH)
bob.right(90)
bob.forward(HEIGHT/2)
bob.right(90)
bob.end_fill()
def tower():
for height in heights:
bob.left(90)
bob.forward(height)
bob.right(90)
bob.forward(50)
bob.right(90)
bob.forward(height)
bob.left(90)
heights_string = input("Please enter height of towers: ")
heights = map(int, heights_string.split(","))
screen = Screen()
screen.setup(width=WIDTH, height=HEIGHT)
screen.bgcolor("orange")
bob = Turtle()
ocean()
tower()
bob.hideturtle()
screen.mainloop()
USAGE
> python3 test.py
Please enter height of towers: 100,30,140,60,90,20,45
OUTPUT
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)+":")
I'm very new to Python and I hope for some help or guides by asking here.
Here's the problem:
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn. Find the average number of drawings needed over the 1000 times the loop runs.
I tried to create something (below), but I just can't think of how to get those average number. Also it seems the loop is not good. Any help or solution? thank you in advance.
from random import randint
from random import choice #???
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
x = 0
randomlotterylist = []
while not x>1000:
lottery = []
for i in range (6):
lot.append(randint(1,10))
randomlotterylist.append(lottery)
x = x + 1
#Next.. ????
First, you want to know your theoretical average number of drawings, that's (1/10)^6 assuming no repetition allowed. Therefore on average every 1,000,000 tries you'd hit the correct number. That is only if the order matters but I assume in your case the order does not matter, so def your average is less than that...
from random import randint
def number_of_tries_before_hitting_jackpot(user_number):
n_tries = 0
while True:
random_number = set([randint(1,10) for i in range(1,7)])
if user_number == random_number:
return n_tries
else:
n_tries+=1
def ask_user_his_number():
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
return set(userlist)
n_tries_list = []
for x in range(1,1001):
user_number = ask_user_his_number()
print user_number
tmp = number_of_tries_before_hitting_jackpot(user_number)
print tmp
n_tries_list.append(tmp)
avg_number_drawings = reduce(lambda x, y: x + y, n_tries_list) / len(n_tries_list)
print avg_number_drawings
This code is not what I'd do in the sense that the user needs to input its 6 numbers 1,000 times (v annoying for the user). You could change the ask_user_his_number function to a function that just randomly selects a set of 6 numbers.
by using random module, for loop, list in short without defining fuction.
from random import *
user_num=[]
count=0
for i in range(6):
random_num=randint(1,10)
user_num+=[random_num]
user_num.sort()
for j in range(1000):
picked=[]
for k in range(6):
pick_num=randint(1,10)
picked+=[pick_num]
picked.sort()
if picked==user_num:
count+=1
print("the avg darwing is: ",count, count/1000)