Here is my program:
from turtle import *
xpos=0
ypos=0
radius = 35
while radius > .1:
pu()
goto (xpos, ypos)
pd()
circle(radius)
ypos = ypos + (radius*2)
radius = radius - 5
I would like to somehow ASK the user to input x and y positions, and also request radius and shrink value. The program should then carry out the process that was keyed in by the user (depending on the integers they used) Is this possible?
I'm guessing it's something along the lines of int(input
You can use raw_input:
# use input if using python3
x_pos = int(raw_input("Insert x pos: "))
y_pos = int(raw_input("Insert y pos: "))
radius = int(raw_input("Insert radius: "))
shrink = int(raw_input("Insert shrink value: "))
print "x: {} y: {} radius: {} shrink: {}".format(x_pos, y_pos, radius, shrink)
Example on the command line:
% python request_input.py
Insert x pos: 4
Insert y pos: 5
Insert radius: 1
Insert shrink value: 2
x: 4 y: 5 radius: 1 shrink: 2
You can use input to do this. I didn't handle converting to ints and / or checking that they are indeed integer inputs. I leave this to you. Hint: isdigit() if you want to check for integer input.
input is python3 raw_input for python2
from turtle import *
....
xpos = input("Enter the x position:")
ypos = input("Enter the y position:")
radius = input("Enter the radius:")
shrink = input("Enter the shrink value")
#convert above to int's, or turn into a function.
....
Related
So I'm currently doing an assignment for my python coding class and I have to get the area of a cylinder and I'm supposed to be using functions so it looks cleaner, but I'm not so sure how to exactly do my assignment from scratch, I've watched a lot of videos but can't really seem to understand functions, my code looks like this currently, but whenever I run my code I can't get the "def calc():" part to run, could I get some pointers please?
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
print("The cylinders area is", area)
def calc():
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return pi, area
info()
Don't need so many funcatin .
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
calc(r,h)
def calc(r,h):
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
print("The cylinders area is", area)
info()
in this case I put the radius as 3 and height as 6. You need to define you variables.
Then it should work. in this case I used numpy to import an exact pi variable.
You have to put the calc() function above the info() function. You have to actually call the calc() function which will return the area of cylinder. I have provided the code below which should solve your problem. Hope you understand the code!
def calc(r, h): # Calculates the area of cylinder
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return area
def info(): # Takes the radius and height from user.
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
return f"The area is {calc(r, h)}"
# r = 5
# h = 10
print(info())
# using parameters in functions instead of inputs:
def info2(r, h):
return f"The area is {calc(r, h)}"
r = 5
h = 10
print(info2(r, h))
# Comparing areas of cylinders
area1 = calc(5, 10)
area2 = calc(10, 15)
if area1>area2: #Area1 is greater than Area2
print("Area1 is greater than Area2")
elif area2>area1: #Area2 is greater than Area1
print("Area2 is greater than Area1")
else: #Both are equal
print("Both are equal")
You mentioned in a comment that you wanted to input multiple cylinders and determine which was the larger one -- I think for that you want to have your function that inputs a cylinder return the cylinder itself so that it can be compared using the volume function.
from dataclasses import dataclass
from math import pi
#dataclass
class Cylinder:
radius: float
height: float
name: str
def volume(c: Cylinder) -> float:
return (2*pi*c.radius) * c.height + (pi*c.radius**2)*2
def input_cylinder(name: str) -> Cylinder:
r = float(input(f"What is the radius of the {name} cylinder? "))
h = float(input(f"What is the height of the {name} cylinder? "))
return Cylinder(r, h, name)
if __name__ == '__main__':
cylinders = [input_cylinder(name) for name in ('first', 'second')]
for c in cylinders:
print(f"The {c.name} cylinder's volume is {volume(c)}")
print(f"The bigger cylinder is the {max(cylinders, key=volume).name} one.")
Hello dear SO members and staffs. I have been working on a project where I took the coordinates of the already drawn rectangle with the center of (0,0) coordinates. What I want to do is ask the user to put his x and y coordinates, after which it will tell you that whether if your coordinates is within the area of that or not. I have reached some of my goals, except the one that I need to ask the if statement for both of the x and y at the same time as if I will write only X statement it will display for only checking the X and not Y.
So, I need your help in how to check both of them before displaying?
(The center of the rectangle is at the (0,0) with the total length of 5 and the width of 10.)
y1 = -2.5
y2 = 2.5
x1 = -5
x2 = 5
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if x1<inputX<x2, y1<inputY<y2:
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
Use and to combine them:
if (x1 < inputX < x2) and (y1 < inputY < y2):
i think that will work
if (x1<inputX and inputX<x2 and y1<inputY and inpputY<y2):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
The following code will work for only integer inputs - as it uses range function - range()
`
x1 = -5
x2 = 5
y1 = -2
y2 = 2
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if (inputX in range(x1,x2+1)) and (inputY in range(y1,y2+1)):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
`
The answer before given using if condition has no problem, I am writing this to give an idea for an approach of using it using a function
I am trying to code a game that has a red circle in which the user is supposed to click up to 7 times in the window. If the user clicks outside the circle, the circle will change its position to where the user clicked. And the game should end when the user has clicked 3 times inside the circle (does not have to be in a row) or when the user has clicked 7 times in total.
I have coded and done quite most of it I think, its just I cant seem to make it work as I want to.
from graphics import *
def draw_circle(win, c=None):
x = random.randint(0,500)
y = random.randint(0,500)
if var is None:
centa = Point(x,y)
var = Circle(centa,50)
var.setFill(color_rgb(200,0,0))
var.draw(win)
else:
p1 = c.p1
x_dif = (p1.x - x) * -1
y_dif = (p1.y - y) * -1
var.move(x_dif, y_dif)
return (var, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
var,x,y = draw_circle(win)
while score <= 7:
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and
mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
var,x,y = draw_circle(win, c)
print ("Success!")
print (("the score is, {0}").format(score))
thanks for the help in advance!
I see a couple problems.
your if mouseClick2.y >= y-50... conditional is spread out on two lines, but you don't have a line continuation character.
You never call main().
You don't import random.
You call draw_circle in the while loop with an argument of c, but there is no variable by that name in the global scope. You probably meant to pass in var.
c in draw_circle ostensibly refers to the circle object you want to manipulate, but half the time you manipulate var instead of c.
you assign a value to cvar in the loop, but never use it.
Your else block in draw_circle calculates the movement delta by subtracting the cursor coordinates from c.p1. But c.p1 is the upper-left corner of the circle, not the center of the circle. So your hit detection is off by fifty pixels.
import random
from graphics import *
def draw_circle(win, c=None):
x = random.randint(0,500)
y = random.randint(0,500)
if c is None:
centa = Point(x,y)
c = Circle(centa,50)
c.setFill(color_rgb(200,0,0))
c.draw(win)
else:
center_x = c.p1.x + 50
center_y = c.p1.y + 50
x_dif = (center_x - x) * -1
y_dif = (center_y - y) * -1
c.move(x_dif, y_dif)
return (c, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
var,x,y = draw_circle(win)
while score <= 7:
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and \
mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
var,x,y = draw_circle(win, var)
print ("Success!")
print (("the score is, {0}").format(score))
main()
Additional possible improvements:
Your hit detection checks whether the cursor is in a 50x50 rectangle centered on the circle. You could instead check whether the cursor is inside the circle if you measured the distance between the cursor and the center, and checked whether it was less than the radius.
var and c could stand to have more descriptive names.
mouseClick2 doesn't make much sense as a name, considering there's no mouseClick1.
The movement delta arithmetic could be simplified: (a-b) * -1 is the same as (b-a).
If you only use a variable's value once, you can sometimes avoid creating the variable at all if you nest expressions.
it might be nice to define constants, such as for the circle's radius, instead of having magic numbers in your code.
You can save five characters by using += to increment the score.
import math
import random
from graphics import *
RADIUS = 50
def draw_circle(win, circle=None):
x = random.randint(0,500)
y = random.randint(0,500)
if circle is None:
circle = Circle(Point(x,y),RADIUS)
circle.setFill(color_rgb(200,0,0))
circle.draw(win)
else:
circle.move(
x - circle.p1.x - RADIUS,
y - circle.p1.y - RADIUS
)
return (circle, x, y)
def main():
win= GraphWin("game",800,800)
score = 0
circle,x,y = draw_circle(win)
while score <= 7:
cursor = win.getMouse()
if math.hypot(cursor.x - x, cursor.y - y) <= RADIUS:
score += random.randint(0,5)
circle,x,y = draw_circle(win, circle)
print ("Success!")
print (("the score is, {0}").format(score))
main()
I'm not really a python guy, but I see that your hitbox is wrong. If there are any other issues then comment it/them to me.
Solving hitbox to be circle:
What you have already written is good to have thing but you should check if click was in circle not square. Pythagoras triangle is solution for this.
Check:
if (math.sqrt(delta_x **2 + delta_y **2) <= circle_radius)
where delta_x and delta_y is center coordinate minus mouse position
For my assignment, I'm trying to make a 5 x 5 checkerboard with the user choice in color and square size. I got how to make square sizes and colors based on the user input and am having some trouble with how to start a loop or how to create a 5 x 5 checkerboard. I'm just not sure what I could do to move the turtle to make a 5x5 board. I have this much done so far, if anyone could help me get started, i would really appreciate it!
import turtle
def main():
length = int(input("Enter a desired length (from 1-150.)"))
keepGoing = 'y'
while keepGoing == 'y':
print("What color would you like to draw?")
print(" Enter 1 for Black")
print(" 2 for Blue")
print(" 3 for Red")
print(" 4 for Green")
choice = int(input(" Your choice?"))
if choice == 1:
square(0,0,length,'black')
elif choice == 2:
square(0,0,length,'blue')
elif choice == 3:
square(0,0,length,'red')
elif choice == 4:
square(0,0,length,'green')
else:
print("ERROR: only enter 1-4.")
def square(x, y, width, color):
turtle.clear()
turtle.penup() # Raise the pen
turtle.goto(x, y) # Move to (X,Y)
turtle.fillcolor(color) # Set the fill color
turtle.pendown() # Lower the pen
turtle.begin_fill() # Start filling
for count in range(4): # Draw a square
turtle.forward(width)
turtle.left(90)
turtle.end_fill()
#calling main function
main()
First, you developed your user interface without having anything to interface to -- you might start the other way around next time. Second, don't reinvent booleans (e.g. while keepGoing == 'y'). Third, for the amount of code it took you to draw one square, we can stamp the entire grid:
from turtle import Turtle, Screen
COLORS = ["Black", "Blue", "Red", "Green"]
GRID = 5
STAMP_UNIT = 20
def main():
length = int(input("Enter a desired length (from 1-150): "))
keepGoing = True
while keepGoing:
print("What color would you like to draw?")
for i, color in enumerate(COLORS, start=1):
print(" Enter {} for {}".format(i, color))
choice = int(input(" Your choice? "))
if 1 <= choice <= len(COLORS):
grid(-length * GRID // 2, -length * GRID // 2, length, COLORS[choice - 1])
keepGoing = False
else:
print("ERROR: only enter 1-{}.".format(len(COLORS)))
def grid(x, y, width, color):
tortoise = Turtle('square', visible=False)
tortoise.shapesize(width / STAMP_UNIT)
tortoise.color(color)
tortoise.penup()
for dy in range(0, GRID):
tortoise.goto(x, y + width * dy)
for dx in range(dy % 2, GRID, 2):
tortoise.setx(x + width * dx)
tortoise.stamp()
screen = Screen()
main()
screen.exitonclick()
USAGE
> python3 test.py
Enter a desired length (from 1-150): 30
What color would you like to draw?
Enter 1 for Black
Enter 2 for Blue
Enter 3 for Red
Enter 4 for Green
Your choice? 2
OUTPUT
This is a perfect example of where stamping can make things simpler and faster than drawing.
I have been trying to organise this program into loads of functions to make it more modular, but I have run into this error
Traceback (most recent call last):
File "N:\Starry\Planetary Orbits Ver 6.py", line 100
Forces(pos, Radii, Masses)# Computes all the forces between masses
File "N:\Starry\Planetary Orbits Ver 6.py", line 74, in Forces
r = pos-pos[:,newaxis] # all pairs of star-to-star vectors (Where r is the Relative Position Vector
TypeError: tuple indices must be integers, not tuple
I'm not sure I have set up the functions correctly, which is why im getting the error in the function.
Or is it because i've used a numpy function inside the Forces function?
from visual import *
from time import clock
from random import random
# Stars interacting gravitationally
# Program uses numpy arrays for high speed computations
Nstars = int(input("Number of stars: ")) # change this to have more or fewer stars
G = 6.7e-11 # Universal gravitational constant
# Typical values
Msun = 2E30
Rsun = 2E9
vsun = 0.8*sqrt(G*Msun/Rsun)
dt = 10.0 #Reprensents the change in time
Nsteps = 0
time = clock()
Nhits = 0
Stars = []
colors = [color.red, color.green, color.blue,
color.yellow, color.cyan, color.magenta]
PositionList = []
MomentumList = []
MassList = []
RadiusList = []
pos = ()
Radii = ()
Masses = ()
def Calculations(SpeedX, SpeedY, SpeedZ, x, y, z, Mass, Radius):
px = Mass*(SpeedX)
py = Mass*(SpeedY)
pz = Mass*(SpeedZ)
PositionList.append((x,y,z))
MomentumList.append((px,py,pz))
MassList.append(Mass)
RadiusList.append(Radius)
def StarCreation(Stars,x,y,z,Radius):
Stars = Stars+[sphere(pos=(x,y,z), radius=Radius, color=colors[i % 6],
make_trail=True, interval=10)]
def DataCollection():
x = input("Please enter The x position of the Star: ")
y = input("Please enter The y position of the Star: ")
z = input("Please enter The z position of the Star: ")
Radius = input("Please enter the Radius of the Star: ")
StarCreation(Stars,x,y,z,Radius)
Mass = input("Please enter the Mass of the Star: ")
SpeedX = input("Please enter the X speed of Star: ")
SpeedY = input("Please enter the Y speed of Star: ")
SpeedZ = input("Please enter the Z speed of Star: ")
Calculations(SpeedX, SpeedY, SpeedZ, x, y, z, Mass, Radius)
def Momenta(Momentum, Masses):
vcm = sum(Momentum)/sum(Masses) # velocity of center of mass
Momentum = Momentum-Masses*vcm # make total initial momentum equal zero
def ListToArray(PositionList, MomentumList, MassList, RadiusList):
pos = array(PositionList)
Momentum = array(MomentumList)
Masses = array(MassList)
Masses.shape = (Nstars,1) # Numeric Python: (1 by Nstars) vs. (Nstars by 1)
Radii = array(RadiusList)
Momenta(Momentum, Masses)
def Forces(pos, Radii, Masses):
# Compute all forces on all stars
r = pos-pos[:,newaxis] # all pairs of star-to-star vectors (Where r is the Relative Position Vector
for n in range(Nstars):
r[n,n] = 1e6 # otherwise the self-forces are infinite
rmag = sqrt(sum(square(r),-1)) # star-to-star scalar distances
hit = less_equal(rmag,Radii+Radii[:,newaxis])-identity(Nstars)
hitlist = sort(nonzero(hit.flat)[0]).tolist() # 1,2 encoded as 1*Nstars+2
F = G*Masses*Masses[:,newaxis]*r/rmag[:,:,newaxis]**3 # all force pairs
def UpdateMomentaPositions(Momentum, pos, Masses):
Momentum = Momentum+sum(F,1)*dt
pos = pos+(Momentum/Masses)*dt
def UpdateDisplay(pos):
Stars[i].pos = pos[i]
#~~~~~~~~~~~~~~~~~~~~~~~~~ Actual Proagram ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
for i in range(Nstars):
DataCollection()
ListToArray(PositionList, MomentumList, MassList, RadiusList)
while True:
rate(100) # No more than 100 loops per second on fast computers
Forces(pos, Radii, Masses)# Computes all the forces between masses
for n in range(NStars):
F[n,n] = 0 # No self forces
UpdateMomentaPositions(Momentum,pos,Mass) # Updates the Momentum and Positions of Stars
for i in range(Nstars):
UpdateDisplay(pos) # Updates the 3D displays position of Masses