I want to use python turtle to create a program that asks the user how many sides they want on a polygon, then turtle draws it. Here is my code:
import turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
shape = turtle.Turtle()
shape.color("blue")
shape.pensize(3)
sides = int(input("How many sides do you want? Use digits: "))
def polygon(sides,length):
for x in range(sides):
shape.forward(length)
shape.left(360/sides)
For some reason this won't work. Any ideas?
Thanks in advance!
You don't actually call polygon, you only define it (that's what the def part of def polygon(sides,length): means.
Try adding something like
polygon(sides, length)
to the bottom of your script; or more specifically anywhere after the definition.
Original
If you're using Python 2 you should probably use raw_input instead of input.
Other than that, try and include the error message / output to receive a moore targeted answer.
The only reason i can see why it doesn't work is that you haven't put in the final line of code in. This is actually essential or python wont run the def. For your instance it would be: polygon(sides,100)
I only put the 100 in as an example and you can change it yourself to whatever you desire
You need to call the function you create like this:
polygon(sides,100)
Or any other length you want instead of 100
The other thing you can do is to ask user to enter the length from console
length = int(input("How tall do you want the lines? Use digits: "))
Your code should look like this
import turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
shape = turtle.Turtle()
shape.color("blue")
shape.pensize(3)
sides = int(input("How many sides do you want? Use digits: "))
def polygon(sides, length):
for x in range(sides):
shape.forward(length)
shape.left(360/sides)
polygon(10, 90) # replace these numbers with the values that you want
The first thing I saw was you didn't have a space between the two variables in the def() statement. The second thing is that when you create a def it is like creating a big variable where all the code inside is that variable(kinda) the variables inside the parenthesis in the def statement are variables that need to be defined later on when calling the function so that the function will run correctly!
Related
I am having an issue creating turtle.onkey commands using the numpad 1-9 keys as input.
I looked at the source and documentation, it appears the keys taken as arguments come from tkinker. I found a list of keys from the documentation there as well as this list and from what I can gather the argument should be "KP_4" for the number '4' on the numpad, but my code will not take it. I have tried more traditional keys like "Left" for the left arrow and these seem to work fine. I also looked into a document on here about pygame thinking maybe it was similar, but the one they list for the numpad 4 did not work either. (it was K_KP4)
def player_move_left():
x = player_char.xcor()
x -= player_max_move
player_char.setx(x)
turtle.onkey(player_move_left,"K_P4")
This should take the x coordinate, and subtract the movement amount then apply that number to the player variable's x-coordinate.
* Solution provided in the first answer*
My (OS X) system doesn't distinguish between "4" on the main keys and "4" on the keypad, both moved the turtle. However, it does distinguish between "Return" on the main keys and "KP_Enter" on the keypad so I'll use that in my example code:
from turtle import Screen, Turtle
player_max_move = 10
def player_move_left():
x = player_char.xcor() - player_max_move
player_char.setx(x)
screen = Screen()
player_char = Turtle()
screen.onkey(player_move_left, "KP_Enter") # vs "Return"
screen.listen()
screen.mainloop()
Experiment with the above to see if you can get insight into your problem (e.g. is there any step you left out?)
I have code to make a triacontagon (30 sided polygon) but when i let it run, it only provides an answer in the shell and not an actual program. It may be due to what I put beside int, but I'm not sure. Thanks!
the code
import turtle
numberOfSides = int(input('30'))
lengthOfSide = int(input('5'))
exteriorAngle = 360/numberOfSides
for i in range(numberOfSides):
turtle.forward(lengthOfSide)
turtle.right(exteriorAngle)
If I understand correctly what is happening, you are misunderstanding the use of input().
input() ask the user for input at runtime. Let say in the code you have x = int(input("Please type number of sides: ")), then the user is asked for input, typically to be typed in the terminal, and the input is saved in the variable x. The string argument of input() is shown in the terminal just before the user typing: it's intent is to provide information to the user on what he/she have to type.
In your case, if you want to draw a triacontagon you could just edit your code this way:
numberOfSides = 30
lengthOfSide = 5
You do not need input() to assign to a variable a known value.
But your code is more general, it can draw any regular polygon. To make it more clear, try to edit it this way:
numberOfSides = int(input("Please type number of sides: "))
lengthOfSide = int(input("Please type length of sides: "))
It will draw a regular polygon according to the numbers you give him each time you execute the code (if you type 4 and 10 for example, the code draws a square whose each side is of length 10).
Remember to add at the end of the script:
turtle.done()
otherwise the window is closed immediately.
You can do it manually, it will be long, but it will be SO much easier.
Here is the code you should type:
By the way, this tricantagon won't look exactly like a tricantagon, more like a circle, but if you see the code, it is a tricantagon. 30 sides!!
from turtle import *
speed(1)
penup()
setpos(-250, 0)
down()
for i in range(72):
fd(10)
left(5)
Code doesn't work like it should. It is just a small thing i would like to learn as a new coder:
import turtle
import random
me=turtle.Turtle()
def up_right():
me.right(90)
me.forward(100)
def down_right():
me.right(90)
me.forward(100)
choose = (up_right(), down_right)
random.choice(chose)
It should pick one and do it but it picks them both.
I've tried random.sample and random.choice but cant get them to work.
Besides the typo of choose... My suggestion is that after you create a tuple of functions and choose the function using random.choice(), you should make a call to the function chosen by the random.choice().
# Notice I removed the () after up_right so it doesn't make the function call on this line
choose = (up_right, down_right)
# random.choice will return one of the two, and then the () will call whatever function was chosen
random.choice(choose)()
I see three issues with your code. The first two folks have pointed out already, the choose vs chose typo and leaving the parens () on upright when refering to it as a function (up_right(), down_right).
The third is that up_right and down_right both implement the same motion, so even if the rest of your code worked, you wouldn't see any difference! Below's a rewrite that fixes this issue:
from turtle import Screen, Turtle
from random import choice
def up_right(turtle):
turtle.setheading(90)
turtle.forward(100)
def down_right(turtle):
turtle.setheading(270)
turtle.forward(100)
choices = [up_right, down_right]
screen = Screen()
me = Turtle('turtle')
choice(choices)(me)
screen.mainloop()
Run it several times and you'll see sometimes the turtle heads up the screen, sometimes it heads down.
Within a python program, I need to simulate a basic game. Within this game, I need to randomize a hiding spot using a number between 1-3 as part of a simulated game:
def coin_places():
return random.randrange(1,4)
I then take this random number and put it into the game, seeing if the simulated guess is correct:
hide_spot = coin_places()
print(hide_spot)
guess = random.randrange(1,4)
print(guess)
def game():
if guess == hide_spot:
return True
elif guess != hide_spot:
return False
else:
return game(guess)
However, where I'm stumped is, I've been tasked with creating a caveat where one wrong hiding spot is removed, and the program must swap the remaining two guess numbers.
For example, the ramdom output is guess = 2 and hide_spot = 2, so the number 3 or 1 needs to be removed, and guess will be swapped with what is left, let's say from 2 to 1. Each the caveat and original values are outputted as percent chances (just as background, I'm able to write that part)
I can't seem to be able to find any examples of this kind of problem elsewhere, and any help would be greatly appreciated!
To be a bit more clear essentially I need to:
Create a simulated number of games, from user input
Create the number of spots and designate one as the hiding spot.
Create the parameters of the normal game, simulating user guess
Add another technique, which will produce its own results, where one wrong hiding spot is removed, and the program must swap the remaining two guess numbers.
Output the chances of success of each technique as percentages
Thanks a bunch for any help or consideration!
import sys
import turtle
t=turtle.Pen
def what_to_draw():
print ("What to do you want to see a sketch of that may or may not be colored?")
what_to_draw=sys.stdin.readline()
if what_to_draw=="flower/n":
t.forward(90)
elif():
print ("What you typed isn't in the code. Try putting a letter or letters to lowercase or uppercase. If that doesn't work, what you typed has not been set to make something happen")
I typed in this code above. It says in the python shell "flower" isn't defined. Can someone figure this out for me?
Several lines of your code have errors of some sort:
t=turtle.Pen should be: t = turtle.Pen()
You should avoid functions and variables with the same name
def what_to_draw():
...
what_to_draw = sys.stdin.readline()
Use rstrip() to deal with "\n" and .lower() to deal with case:
if what_to_draw == "flower/n":
elif(): requires a condition of some sort otherwise use else:
Let's try a different approach. Instead of mixing console window input with turtle graphics, let's try to do everything from within turtle using the textinput() function that's new with Python 3 turtle:
from turtle import Turtle, Screen
def what_to_draw():
title = "Make a sketch."
while True:
to_draw = screen.textinput(title, "What do you want to see?")
if to_draw is None: # user hit Cancel so quit
break
to_draw = to_draw.strip().lower() # clean up input
if to_draw == "flower":
tortoise.forward(90) # draw a flower here
break
elif to_draw == "frog":
tortoise.backward(90) # draw a frog here
break
else:
title = to_draw.capitalize() + " isn't in the code."
tortoise = Turtle()
screen = Screen()
what_to_draw()
screen.mainloop()
Your indentations are wrong, so most of the statements are outside the function body of what_to_draw().
You don't actually call the function, so it won't do anything.
Also, don't use the what_to_draw as a function name and a variable name.
There shouldn't be () after elif:
Instead of print() and stdin, use input() . You don't get the \n that way as well.
Try this and let me know:
import sys
import turtle
t=turtle.Pen()
def what_to_draw():
draw_this = input("What to do you want to see a sketch of that may or may not be colored?")
if draw_this == "flower":
t.forward(90)
elif:
print ("What you typed isn't in the code. Try putting a letter or letters to lowercase or uppercase. If that doesn't work, what you typed has not been set to make something happen")
what_to_draw()