Making a Triacontagon in Python - python

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)

Related

What modules should I use to make my grid swap letters as intended?

I have a crossword puzzle project. I have a puzzle and a random letter generator for every time I press run. Here is the code,
import random
import string
for x in range(4):
for y in range(4):
print( '['+random.choice(string.ascii_letters)+']',end='' )
print()
This results in the following output
[O][E][R][i]
[g][c][C][J]
[D][M][Z][X]
[y][A][M][Q] (letters are randomly generated)
I want to take it to the next level by implementing code which will swap the places of two blocks in the grid which are either exactly above, below, to the left or to the right of each other. Furthermore, I want this to be done only through touch, not any commands
Through research I have learnt that some modules could be used such as the Kivy module or the touch module but I'm not entirely sure. Can anyone please suggest what should I check to get started on this?

How do I make the numbers do their operation? Is there any module that can do that?

def equalizer(entryblock):
x = entryblock.get()
entryblock.delete(0, tk.END)
entryblock.insert('end', int(x))
so here is a function for my tkinter calculator. I am trying to make a function where it takes the entry box and does the operations and gives the result. For example, if I punch in '1+2+3', I want this function to turn it into 6. Whenever I try this, it gives this error:
ValueError: invalid literal for int() with base 10: '1+2+3'
Could I use the math module to fix this problem?
There are 3 ways to solve this problem as far as I can think:
One is to use eval but then you cannot have the user input the values into the entry, as its not safe.
Next is to implement an AST parser suitably, that way you can use user input via Entry and still be safe from the exploits of eval.
The third way would be change your logic and make the app work like how the calculator in windows works, this way you do not need eval or anything. You will have to keep reference to the last item given and then add(or any operation) with the next entered item. Video reference: Build A Simple Calculator App - Python Tkinter GUI Tutorial #6, there is a previous part but only follow the logical part of the code, the other part is quite naïve.
For the first approach, this should give you a bare example:
from tkinter import * # Note: Better to use import tkinter as tk and make changes needingly
root = Tk()
def write(num):
lbl['text'] += num # Add the user inputted number to the end of current text from label
def calc():
out = eval(lbl['text']) # Get the text and do the operations
lbl['text'] = str(out) # Change the text with the output
texts = '123456789' # Digits to loop through
lbl = Label(root,font=(0,15),justify='left')
lbl.grid(row=0,column=0,columnspan=3)
# To create a 3x3 grid of widgets, starting from 1 because 0th row/column is already taken by the label
for i in range(1,4):
for j in range(1,4):
text = texts[3*(i-1)+(j-1)] # Indexing to get the respective texts
Button(root,text=text,command=lambda num=text: write(num),width=15).grid(row=i,column=j-1)
# Some buttons outside the normal gridding behavior and with different function
Button(root,text='+',command=lambda: write('+'),width=15).grid(row=i+1,column=0)
Button(root,text='0',command=lambda: write('0'),width=15).grid(row=i+1,column=1)
Button(root,text='=',command=calc,width=15).grid(row=i+1,column=2)
Button(root,text='C',command=lambda: lbl.config(text=''),width=15).grid(row=i+2,columnspan=3,sticky='news')
root.mainloop()
You can design/place the widgets the way you want, notice how the function handles the input and user cant input any number as they wish either.
For the second approach, you can refer here for a code from Kevin that implements ast and does calculation and you can take user input as well and integrate tkinter with that function by making a few tweaks.
So to answer your question:
Could I use the math module to fix this problem?
Nothing I can think of from math does what you are looking for.

Swapping and removing numbers within a randomized Python guessing game

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!

Python Turtle with user input

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!

Stop a Python program until a user performs an action

My original program used input, like this:
n = input("Enter your favorite number: ")
# do stuff with number
Now, I have switched to a GTK GUI, but still want the accomplish the same thing. Now look at this very similar piece of code:
n = myWindow.getNumber()
# do stuff with number
Would it be possible to write a getNumber() method that only returns after the user presses a submit button in the window? (like the how the input function works) or is this my only option:
def callback(widget, event):
n = myWindow.inputWidget.getValue()
# do stuff with number
n = myWindow.getNumber(callback)
Update: I'm looking to do this without a gtk.Dialog, as I don't want a dialog popping up every time user input is required.
What you need is a modal dialog. I don't know GTK (or PyGTK) at all, but there appears to be an example in the documentation.

Categories

Resources