I'm trying to make a repeating pattern program in Python that asks you for how many sides you want the repeated shape to be, how many times it should be repeated and the color of the background and shape fill. It should draw the shape before turning by 360 divided by the amount of sides. However, it keeps repeating on the spot continually. My code is below.
from turtle import*
bgColor = input("What colour background do you want?: ")
fillColor = input("What colour shape fill do you want?: ")
numberOfSides = int(input("How many sides?: "))
rotationsWanted = int(input("How many rotations?: "))
rotationsCompleted = 0
def drawshape():
fillcolor(fillColor)
bgcolor(bgColor)
begin_fill()
while (rotationsCompleted < rotationsWanted):
for x in range(numberOfSides):
forward (100)
right(360/numberOfSides)
end_fill()
drawshape()
right(360/rotationsWanted)
rotationsCompleted = rotationsCompleted + 1
Try to modify the while-loop
rotationsCompleted = 0
while (rotationsCompleted < rotationsWanted):
rotationsCompleted = rotationsCompleted + 1
and after end_fill() you should go to an other position maybe using goto(100, 100) to draw the next shape at a different position.
Related
This is for a school task I have completed all the tasks except this one "Determine the colour of the minimum and maximum sized dots and output the result e.g. The maximum sized dot was orange with a size of 100". I have already found the minimum and maximum sized circles I just can't figure out how to also find the colour of the maximum and minimum sized circles so that I can print ('The maximum size circle is',size,'and it is',colour)
from turtle import *
import random
randomSize=[]
randomColour=[]
countr=0
countg=0
question=input('Do you want to run the program?')
while question=='yes':
#this function will calculate the minimum and maximum circle size form the list randomSize
def minMax(sizes):
minimum=maximum=sizes[0]
for i in sizes[1:]:
if i<minimum:
minimum=i
#im having trouble coordinating the circles size to its colour
elif i> maximum:
maximum=i
print('The maximum size of circles was',maximum)
print('The minimum size of circles was',minimum)
#this function is used to find out whether the there are an even or odd number of red or green
dots
def oddoreven(count,colour1):
result=count%2
if result==0:
print('There were an EVEN number of',colour1, 'dots',count)
else:
print('There were an ODD number of',colour1, 'dots',count)
number=int(input('How many dots do you want?'))
for i in range (number):
x=random.randint(-100,100)
y=random.randint(-100,100)
hideturtle()
penup()
colours=['pink','purple','black','red','green','blue']
colour=random.choice(colours)
if colour=='red':
countr+=1
elif colour=='green':
countg+=1
size=random.randint(0,100)
randomSize.append(size)
randomColour.append(colour)
totalarea=0
goto(x,y)
dot(size,colour)
print("There were",countr,"red dots and", countg,"green dots")
oddoreven(count=countr, colour1='red')
oddoreven(count=countg,colour1='green')
minMax(randomSize)
#this works out the cumulative area for all the values in the list of sizes
for i in randomSize[1:]:
area=3.14*(i**2)
totalarea=totalarea+area
print('The cumulative area for all of the circles is',totalarea)
question= input('Do you want to run the program again?')
Since these are parallel arrays:
randomSize.append(size)
randomColour.append(colour)
A simple fix might be to pass randomColour into minMax() as well and track the index as you loop:
def minMax(sizes, colours):
minimum = maximum = sizes[0]
minColour = maxColour = colours[0]
for index, i in enumerate(sizes[1:], start=1):
if i < minimum:
minimum = i
minColour = colours[index]
elif i > maximum:
maximum = i
maxColour = colours[index]
print('The maximum size of circles was', maximum, "in", maxColour)
print('The minimum size of circles was', minimum, "in", minColour)
Of course, when we see parallel arrays, it usually implies a missing data structure of some sort. Beyond this there are bugs in your code, the most glaring of which is:
randomSize.append(size)
# ...
dot(size,colour)
# ...
for i in randomSize[1:]:
area = 3.14 * (i**2)
The dot() method treats its size argument as a diameter but in your calculation of area, you're treating it as a radius. (The turtle circle() method takes a radius as its argument.) Below is my rework of your code to address the above and other issues:
import math
import turtle
import random
COLOURS = ['pink', 'purple', 'black', 'red', 'green', 'blue']
def minMax(diameters, colours):
''' calculate the minimum and maximum circle diameters and their colours '''
minimumDiameter = maximumDiameter = diameters[0]
minimumColour = maximumColour = colours[0]
for index, diameter in enumerate(diameters[1:], start=1):
if diameter < minimumDiameter:
minimumDiameter = diameter
minimumColour = colours[index]
elif diameter > maximumDiameter:
maximumDiameter = diameter
maximumColour = colours[index]
print("The maximum diameter of circles was", maximumDiameter, "in", maximumColour)
print("The minimum diameter of circles was", minimumDiameter, "in", minimumColour)
def oddOrEven(count, colour):
''' find out whether the there are an even or odd number of red or green dots '''
result = count % 2
if result == 0:
print("There were an EVEN number of", colour, "dots", count)
else:
print("There were an ODD number of", colour, "dots", count)
randomDiameters = []
randomColours = []
countRed = 0
countGreen = 0
answer = 'yes'
while answer.lower().startswith('y'):
number = int(input("How many dots do you want? "))
for _ in range(number):
x = random.randint(-100, 100)
y = random.randint(-100, 100)
turtle.hideturtle()
turtle.penup()
colour = random.choice(COLOURS)
diameter = random.randint(0, 100)
# parallel arrays
randomDiameters.append(diameter)
randomColours.append(colour)
turtle.goto(x, y)
turtle.dot(diameter, colour)
if colour == 'red':
countRed += 1
elif colour == 'green':
countGreen += 1
print("There were", countRed, "red dots and", countGreen, "green dots.")
oddOrEven(count=countRed, colour='red')
oddOrEven(count=countGreen, colour='green')
minMax(randomDiameters, randomColours)
# work out the cumulative area for all the values in the list of diameters
totalArea = 0
for diameter in randomDiameters:
area = math.pi * (diameter / 2) ** 2
totalArea += area
print("The cumulative area for all of the circles is", totalArea)
answer = input("Do you want to run the program again? ")
Since you appended the values in the list, I can only assume that randomSize[0] is the size of randomColour[0], so on and so forth.
randomSize.append(size)
randomColour.append(colour)
I started a project in Codeacademy to create an area calculator. However the code elif option == "T": keeps producing syntax error. I looked at the solution but it looks exactly the same. Can anyone please help?
Thanks in advance.
I've tried changing indentation and spacing and changing it from double quotes to single quotes. I even copied and pasted the solution but it still doesn't work.
# it calculates area of circle and triangle
print"Calculator, Ready!"
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
print area
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
You need to indent the area calculations since they're part of the if and elif blocks. You're getting a syntax error because an elif statement must follow an if block.
Also since you're doing print area in both cases, you only need to write it once.
The important bits fixed:
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
In Pythhon, a elif statement can only follow a elif or if statement, but in your code, it follows a print.
You may indent or remove the two following lines:
area = 3.14159 * radius ** 2
print area
My understanding of your code makes me propose you this solution:
# ==========================================
# It calculates area of circle and triangle
# A good practice is to initialise all your variable at the begining
option = None
radius = None
area = None
base = None
height = None
print("Calculator, Ready!")
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print ("The calculated area is: {}".format(area))
I am trying to create a loop that takes an input by a user and draws however many squares but it increases the size of the squares with each loop, however 2 sides are stay connected. I'll include the graphic to better explain.
import turtle
squares = 1
while squares >= 1:
squares = int(input('How many squares would you like drawn?:'))
if squares == 0:
print("You must have at-least 1 square.")
squares = int(input('How many squares would you like drawn?:'))
else:
for count in range(squares):
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.done()
The input request and the drawing logic ought to be separated.
Here is one approach that returns the turtle at the start at each turn, after increasing the side length.
import turtle
num_squares = 3
t = turtle.Turtle()
t.pendown()
side = side_unit = 30
while True:
try:
num_squares = int(input('input the number of squares'))
except ValueError:
print("please enter an integer")
if num_squares > 3:
break
for sq in range(1, num_squares + 1):
t.left(90)
t.forward(side)
t.left(90)
t.forward(side)
t.left(90)
t.forward(side)
t.left(90)
side = side_unit + 3 * sq # increase the size of the side
t.goto(0,0) # return to base
turtle.done()
While waiting for #ReblochonMasque's solution to finish drawing 100 squares, there's plenty of time to implement an alternate, faster solution based on stamping.
The first thing to note is in the provided instructions it says to draw 100 squares to create the design in the figure, but that figure consists of just under 50 squares. It's also been scaled in some non integral fashion which makes it appear to have different line thicknesses.
Let's focus on the spirt of the problem rather than the example. The OP had a 1 square minimum so I've preserved that. This solution also naturally tends to center the square on the window:
from turtle import Turtle, Screen
DELTA = 3
MINIMUM = DELTA * 2
CURSOR_SIZE = 20
num_squares = -1
while num_squares < 1:
try:
num_squares = int(input('Input the number of squares: '))
except ValueError:
print("please enter an integer.")
if num_squares < 1:
print("You must have at least 1 square.")
screen = Screen()
turtle = Turtle("square", visible=False)
turtle.fillcolor("white")
for size in range(((num_squares - 1) * DELTA) + MINIMUM, MINIMUM - 1, -DELTA):
turtle.goto(turtle.xcor() + DELTA/2, turtle.ycor() - DELTA/2)
turtle.shapesize(size / CURSOR_SIZE)
turtle.stamp()
screen.exitonclick()
This is clearly not the kind of solution the OP was looking for, but maybe next time a problem like this comes up, it might be one the OP will at least consider.
Ive based the e1 and e2 sections of code as two halves of the google equation found when asking calculate width of a rectangle given perimeter and area.
This section of code is set to be part of a larger piece that displays the calculated rectangle in a visual form instead of using integers, however when i test it, the answer it gives is incorrect.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = int(perim**2 - (16 * area))
e3 = int(math.sqrt(e2))
width = int(e1 * e3)
print(width)
It's recommended you name your variables better so we know what you're trying to calculate.
From the Google formula, you should just translate it directly.
import math
def get_width(P, A):
_sqrt = math.sqrt(P**2 - 16*A)
width_plus = 0.25*(P + _sqrt)
width_minus = 0.25*(P - _sqrt)
return width_minus, width_plus
print(get_width(16, 12)) # (2.0, 6.0)
print(get_width(100, 40)) # (0.8132267551043526, 49.18677324489565)
You get zero because int(0.8132267551043526) == 0
Important note: Your calcuation doesn't check
area <= (perim**2)/16
Here is the fixed code :
import math
print("Welcome to Rectangles! Please dont use decimals!")
S = int(input("Area "))
P = int(input("Perim "))
b = (math.sqrt (P**2-16*S)+P) /4
a = P/2-b
print (a,b)
If you don't need to use this equation specifically, it'd be easier to just brute force it.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
lengths = range(math.ceil(perim/4), perim/2)
for l in lengths:
if l*(perim/2 - l) == area:
print(l)
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = abs(perim**2 - (16 * area))
e3 = math.sqrt(e2)
width = e1 * e3
print(width)
print "Enter the amount of points you would like to generate to estimate Pi"
n = raw_input()
plt.xlim((0,1))
plt.ylim((0,1))
x = numpy.linspace(0,1,500)
y = numpy.sqrt(1-x**2)
for i in range(int(n)):
xcoordinate = random.random()
ycoordinate = random.random()
plt.scatter(xcoordinate, ycoordinate)
plt.plot(x,y,'g')
plt.show()
I'm trying to get n random points scattered across this graph. Instead I only get a single random point.
How can I fix this?
You can turn xcoordinate and xcoordinate into a list instead, and append random points in it.
xcoordinate=[]
ycoordinate=[]
for i in range(int(n)):
xcoordinate.append(random.random())
ycoordinate.append(random.random())
The rest of your code remains unchanged.