Python range(%d) % sides - python

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

Related

Python Turtle issue drawing based on user input

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

Python If/else statements with math

I've been trying to make a circle area calculator, and I've got the basics. But if the user enters something like 5m, then I see an error. Instead of exiting with an error, I want to return "Enter a Number". Here is my code.
from math import pi
r = float(input("Input the radius of the circle : "))
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
if r==(str):
print("Enter a Number")
This here
if r==(str):
doesn't do what you are expecting.
You want to use string module for this check (Note that this should be done before attempting to convert input to a float):
import string
if set(r).issubset(string.digits)
Or there is a method on string object for this check:
r.isdigit()
But there is a better way:
from math import pi
try:
radius = float(input("Input the radius of the circle : "))
except ValueError:
print("Invalid input, enter a Number!")
else:
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
This shows how to handle invalid inputs. You may want to put this in a loop until you get a valid input.
You can repeatedly ask until a string that can be converted to a float is entered. You can detect failure to convert the string to a float by catching ValueError, which is the exception thrown when a type conversion fails.
while True:
try:
r = float(input("Input the radius of the circle : "))
break
except ValueError:
pass
Do this in place of your current line containing the input call, and get rid of the r == (str) test, which does not actually do anything close to what you are intending.
Also note if you are using Python2 you will need the raw_input function rather than input.

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.

Need some help trying to build a triangle in Python, but I keep getting it wrong

I'm trying to do this triangle in Python as an assignment for my computer science class, but I quite can't figure it out.
The output is supposed to be like this:
Select your height. > 5
*
**
***
****
*****
But it comes out like this:
Select your height. > 5
*
**
***
*****
******
Here's the source code.
I apologize for the lengthiness and slight unruliness, I'm currently using vim as my text editor, and I'm fairly new at it.
I'm so sorry if this question is bad... I searched for Python's documentation page, and I tried .ljust() and .rjust(), and it doesn't seem to be working for me well. Thanks so much for your help in advance!
# The tools we will use:
# We're just using this to make the program have a more clean, organized feel when executing it.
import time
# This will help build the triangle, along with other variables that will be described later. Spacing is necessary to help build a presentable triangle.
asterisk = "* "
# added will be used in the loop to control how long it will keep repeating the task.
added = 0
# This will multiply the amount of asterisks so that every time a line passes during the loop, it will steadily increase by one.
multiplier = 2
tab = ("""\t\t""")
nextline = ("""\n\n""")
# the finished product!
triangle = ("""""")
# THE PROCESS
print("I will ask you for a height -- any height. Once you tell me, I'll make an isosceles triangle for you.")
#time.sleep(2)
height = input("Please enter a height. > ")
heightNum = int(height)
while heightNum <= 0:
print ("Oops, you can't insert negative numbers and zeroes. Please try another one!")
height = input("Please enter a height. > ")
heightNum = int(height)
while heightNum > added:
if added == 0:
triangle = (tab + triangle + asterisk + nextline)
added += 1
else:
starsline =(tab + asterisk * multiplier + nextline)
triangle = (triangle + starsline)
added += 1
multiplier += 1
print("Here it is! \n\n\n")
print(triangle)
print ("\n\nThis triangle is %d asterisks tall.") % heightNum
def print_triangle(length):
for i in range(1, length+1):
print('{0:>{length}}'.format('*'*i, length=length))
And usage:
>>> print_triangle(5)
*
**
***
****
*****
To break it down, this is using the string formatting mini-language:
'{0:>{length}}'
The first opening bracket is indexed to the first argument, and the : means that formatting specifications will follow it. The > means to right justify it by a width, which is provided by another keyword variable, the length of the triangle.
That should be enough to get you finished, without rewriting your entire script.
def triangle(n):
return '\n'.join(
'%s%s' % (' ' * (n - i), '*' * i)
for i in xrange(1, n + 1))
print triangle(5)
This works because
'x' * n is a string with n 'x''s concatenated together which the '%s%s' % ... line uses to produce one row of n characters with spaces at the left and asterisks at the right.
'\n'.join(...) joins a generator expression on a newline to combine the rows into a triangle.
for i in xrange(1, n + 1) uses another generator to iterate a row counter, i, from 1 to n. The n + 1 is there since ranges are half-open in python.

Python-Need to turn this into a loop so it look like my picture?

I need to write this program using a loop
http://imgur.com/CGRMn
this is what i have so far but my program has to look exactly and the picture???
def main():
sum=0.0
for i in range(1,6):
x,y=eval(input("Please enter length and width of room:"))
sf=(x*y)
sum=sum+sf
print("The total square footage is",sum)
main()
Thank you for your help...
Just drop the indent on the print statement.
sum=0.0
for i in range(1,6):
x,y=eval(input("Please enter length and width of room:"))
sf=(x*y)
sum=sum+sf
print("The total square footage is",sum)
edited:
This is a common technique in python you could use to achieve what you want:
sum=0.0
for i in range(1,6):
x,y=eval(input("Please enter length and width of room %i:" % i ))
sf=(x*y)
sum=sum+sf
print("The total square footage is %i" % sum )
What i'm doing here is placing a wildcard in the middle of the string and then pass the parameters. '%i' tells the % operator that you are going to insert an integer. You can also put '%s' if you were going to add a string. There are a couple more you can check out. This is another example for the console:
>>> user_name = 'mauricio'
>>> sum = 42
>>> line_to_print = 'Hello user %s, your sum is %i' % (user_name, sum)
>>> print(line_to_print)
Hello mauricio, your sum is 42

Categories

Resources