Python Turtle issue drawing based on user input - python

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

Related

Storing updated variables in a loop?

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)

How do I loop through a list in Python to make sure there are no repeats?

In my code I am trying to generate coordinates for battleship without having any repeat coordinates. I only manage far more coordinates than I asked for or none at all. What am I doing wrong in my loop/how can I fix this?
from random import randint
board = [] #Create an empty array to act as the game board.
ships = [] #Create an empty array to hold the locations of the random ships.
board_size = int(input("Enter your desired board size: ")) #Ask the user for their preferred board size.
ship_number = int(input("Enter the number of ships you want to find: ")) #Ask the user for their preferred ship number.
ships_found = 0 #Set the counter of the number of user-found ships to start at 0.
def generate_board(board_size): #Define a function to generate the initial board.
for each_item in range(board_size): #For each item in the range of the board's size,
board.append(["O"] * board_size) #Append an O to the board as many time as the user's board size says.
generate_board(board_size)
def print_board(board): #Define a function to print the current board.
for row in board: #For each row in the board,
print(" ".join(row)) #Print each chacter, separated by a space.
def generate_ships(ship_number,board):
for each_ship in range(ship_number):
new_ship = [randint(0, len(board) - 1),randint(0, len(board) - 1)]
for each_item in ships:
if each_item == new_ship:
ships.pop()
ships.append(new_ship)
else:
ships.append(new_ship)
generate_ships(ship_number,board)
While using set() to remove duplicates would technically answer the question in your title, I'd recommend rethinking your approach (and rewriting generate_ships, the logic for which looks like it might not be doing what you want it to).
Rather than randomly generating a coordinate, you could select a random element from the set of available coordinates (your board coordinates after removing the coordinates where there are already ships). This way you only ever select the number of ships you ask for and you don't have to worry about checking for duplicates.

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)+":")

Can anyone help me make a Polygon Generator in Python?

It should ask for a number between 4 and 8 and then turtle will draw those sides.
The interior angle equation:
where N is the # of sides (N -2)180= x, then x divided by N = draw
sides
>>> import turtle
>>> t=turtle.Pen()
>>> usernum = int(input('Give me a number between 4 and 8: '))
Give me a number between 4 and 8: 5
>>> if usernum < 4 or usernum > 8:
print ("invalid number!")
else:
draw
myangle = (((numSides-2) * 180)/ numSides)
turtle.right(180 - myangle)
Since you showed what you actually tried I'll toss you a bone, but you almost certainly could have figured out how to do this from a couple of quick Google searches.
For whatever reason I have some issues running turtle graphic scripts from IDLE, I don't know if you have better luck.
import turtle
t = turtle.Pen()
num_sides= int(input("Give me a number between 4 and 8: "))
side_length = 30
while True:
if (num_sides < 4) or (num_sides > 8):
num_sides = int(input("Invalid Number! Please enter a new one from 4-8: "))
else:
myangle = 360 / side_length
break
for i in range(num_sides):
t.forward(side_length)
t.right(myangle)
If like me you have issues running that from IDLE try running it from the python interpreter in the command line. Using a slightly modified version of this I made all of the polygons where num_sides = range(3, 15). As a note, the reason that we don't get exactly back to the start each time is due to the use of integers instead of floating point numbers. Changing this to use floating point should resolve that issue.

Python range(%d) % sides

I am trying to make a program, that uses the turtle module using Python 2.7.5+.
The user can input a integer so I want to use that number as a argument for range()
Here is my code so far:
import turtle
import time
sides = int(raw_input("Enter the amount of sides you want!"))
angle = float(360 / sides)
length = int(raw_input("Enter the length of each side!"))
#Starts turtle drawer
turtle = turtle.Turtle()
def turtleDrawer():
for i in range (%d) : % (sides)
turtle.fd(%d) % (length)
turtle.rt(%d) % (angle)
ws = turtle.Screen()
turtleDrawer()
time.sleep(10)
When this code is executed, it gives me a syntax error, highlighting the % sign in the brackets.
for i in range (%d) : % (sides) is invalid. This type of formatting is used for strings, not for conditional statements.
You are looking for this statement:
for i in range(sides):

Categories

Resources