when to use functions in python and when not to? - python

I'm not understanding where I have to use a function and where I don't, for example, I tried to write this for the area of a rectangle and after hours of trying to figure out why I couldn't get it to execute properly I could just get rid of the very first line of code and it worked fine.
def area_rectangle(width,height):
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
Thought I had to start it out like I did but it just wasn't working until I deleted the first line.

Functions are a way of compartmentalizing code such that it makes it both easier to read and easier to manage. In this case, there are a few concepts you must understand before implementing functions to solve your problem.
Functions follow the format:
def functionName(): #this defines the function
print("This is inside the function.") #this is code inside the function
functionName() #this calls the function
A few things to note:
code that belongs to the function is indented
in order for the function to execute, it first has to be invoked (i.e. called)
So your function aims to calculate the area of a rectangle using width and height variables. In order for your function to work you would first need to invoke the function itself and then remove the unneeded parameters as you are asking for them as input anyway. This would give you:
def area_rectangle():
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print (area)
area_rectangle()
Another way to go about this would be to make use of parameters. Parameters are values passed to a function by the line of code that invokes them, and they are given within the parentheses:
def functionName (my_param):
print (my_param)
fucntionName (my_param)
Using parameters to solve your problem would look something like this:
def area_rectangle(width, height):
area=width*height
print (area)
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area_rectangle(width, height)
Another side note is on return values. Rather than printing the result of a function within the function itself, you can return it to the line that invoked it and then make use of it outside the function:
def area_rectangle(width, height):
area=width*height
return area
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area = area_rectangle(width, height)
print ("The area is {}".format(area))
Functions are an essential part of Python, and I suggest reading some tutorials on them, as there is many more things you can do with them. Some good ones...
learnpython.org - Functions
tutorialspoint.com - Python Functions

First,
You should indent your code
Second,
Now to get your code working you should call the function area_rectangle()
Corrected Code
def area_rectangle():
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
area_rectangle()
Indentation is the key for Python (there are no {} just indentation)
Refer python documentation

You cant executing your function because
You are not invoking (calling) it at the bottom.
def area_rectangle(width,height):
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
area_rectangle()
You are passing the required argument "width and height" to the function
"area_rectangle" which is meaningless because you are accepting them from the user
within the function. just call the function to work.
Functions are a group of statements which gives you the answer for your problem statement. In your case if you are writing it as a function then you can resuse this value "area_rectangle" anywhere you want. you don't need to write those lines again.

Related

unresolved reference during calling a function

I keep getting "Unresolved Reference" error when, I'm trying to call function
here is code for area of circle
#area of circle
def arc(a,r):
a=3.14 * (radius**2)
return arc
radius=int(input("Enter Radius: "))
area_of_circle=arc(a,r)
print("Area of circle: {}".format(arc))
There are a few errors in here, I'll step through each and explain what's happening.
The first two issues occur in your arc() function. I'll write comments above each offending line:
def arc(a,r):
# What is `radius`? That's not defined in this function!
a=3.14 * (radius**2)
# You're returning a reference to the arc() function from the arc() function?
return arc
The next two issues are in the main area of your program. Again, I'll write comments above the offending lines:
radius=int(input("Enter Radius: "))
# What is `a`? What is `r`? You haven't defined those names!
area_of_circle=arc(a,r)
# `arc` is a function, so what do you expect to happen here?
print("Area of circle: {}".format(arc))
To clean this up, you need to make sure every name references a valid variable, and that you're using functions and variables correctly. In your particular program, functions should be defined and called, not returned from functions or passed around like variables in .format() statements. Variables should be defined and given a valid value.
There are a few other errors that may arise once you clean those issues up, but I'm hoping you'll be able to solve those once you have most of the issues fixed!
Fixed up the variables/names/labels in your code:
# area of circle
def area_of_circle(radius):
area = 3.14 * (radius ** 2)
return area
radius = int(input("Enter Radius: "))
area_of_circle = area_of_circle(radius)
print("Area of circle: {}".format(area_of_circle))

when i run my code, why does the ellipse/circle not show up

from math import sin
from processing import *
X = 30
Y = 30
delay = 16
radius = 30
def setup():
strokeWeight(10)
frameRate(20)
size(500,500)
def sircle():
global X, Y, radius
background(100)
fill(0,121,184)
stroke(255)
fc = environment.frameCount
X += (mouse.x-X)/delay;
Y += (mouse.y-Y)/delay;
radius = radius + sin(fc / 4)
draw = sircle
run()
for some reason run() only creates the background.
does anybody know how to call the function for sircle()?
I think the OP is referring this code
where it does seem correct that draw is being assigned the function variable sircle. Besides, its not like sircle() is returning anything that can be assigned to draw
Looking at the example code in the link I shared above, you need a line like
ellipse(X,Y,radius,radius)
at the end of your sircle function
You need to run sircle() and setup() with parentheses.
These are functions not variables, they demand their parentheses. In your code draw variable stores the memory address of sircle() function.

Get Python turtle window to display graphics and remain open

In this code I can't see why it isn't printing a hexagon 24 times. I tell it to make a 6 sided shape with 60 degrees between lines ( a hexagon) and tell it do turn 15 degrees each time. This ends up being a even 24 for the picture I'm trying to draw.
import turtle
Hex_Count = 0
x = turtle.Turtle()
x.speed(.25)
def Hexagon():
for i in range(24):
for i in range(6):
x.forward(100)
x.left(60)
Hex_Count = Hex_Count + 1
x.left(15)
print(Hex_Count)
Hexagon
But, for some reason, when I run this code the turtle screen pops up for about a half second then closes. How do I get it to perform in the way I want it to?
You have several errors that I corrected for you; I added the explanation in the comments:
import turtle
hexagons_count = 0
my_turtle = turtle.Turtle() # x is not a good name for a Turtle object
# my_turtle.speed(.25) # see #cdlane comment reported in a note under.
def draw_hexagon(): # use explicit names respecting python conventions (no camel case)
global hexagons_count # need global to modify the variable in the function scope
for idx in range(24): # use different dummy variable names in your loops
for jdx in range(6): # use different dummy variable names in your loops
my_turtle.forward(100)
my_turtle.left(60)
hexagons_count += 1
my_turtle.left(15)
print(hexagons_count)
draw_hexagon() # need parenthesis to call the function
turtle.exitonclick() # this to exit cleanly
Note: I know you simply copied it from the OP but my_turtle.speed(.25)
doesn't make sense as the argument should be an int from 0 to 10 or a
string like 'slow', 'fastest', etc. I especially don't understand why
beginners with turtle code that isn't working call turtle.speed() at
all -- it seems to me a function to be tweaked after everything is
working. #cdlane
You have some reference issue, you just need to put the variable hex_count where it needs to be so you don't have error accessing it.
import turtle
x = turtle.Turtle()
x.speed(.25)
def Hexagon():
Hex_Count = 0
for i in range(24):
for i in range(6):
x.forward(100)
x.left(60)
Hex_Count += 1
x.left(15)
print(Hex_Count)
Hexagon()
prints 24
You have several problems with your program. One is that it will when after running through the program, closing the window it created. You can add turtle.exitonclick() to the end of your script which tells python to wait for a click in the graphics window, after which it will exit.
The second problem is that you don't call the Hexagon function because you're missing the parentheses. Even if a function takes no arguments, you still need to call it like:
Hexagon()
The final problem is that you need to define Hex_Count before you try to increment it. Hex_Count + 1 will thrown an error if Hex_Count wasn't already assigned to. You can fix this by putting
Hex_Count = 0
before your for loop in Hexagon.
An approach different in a lot of the details but primarily in its use of circle() to more rapidly draw the hexagons:
from turtle import Turtle, Screen # force object-oriented turtle
hex_count = 0 # global to count all hexagons drawn by all routines
def hexagons(turtle):
global hex_count # needed as this function *changes* hex_count
for _ in range(24): # don't need explicit iteration variable
turtle.circle(100, steps=6) # use circle() to draw hexagons
turtle.left(15) # 24 hexagons offset by 15 degrees = 360
hex_count += 1 # increment global hexagon count
print(hex_count)
screen = Screen()
yertle = Turtle(visible=False) # keep turtle out of the drawing
yertle.speed('fastest') # ask turtle to draw as fast as it can
hexagons(yertle)
screen.exitonclick() # allow dismiss of window by clicking on it

Python Turtle: I want to make a function that executes another function depending on what the previously executed function was

I'm drawing my name using turtles and I have a bunch of different functions for each of the letters
like so (for letter r)
def letter_r(t):
def letter_r_top(t):
turtle.lt(90)
turtle.fd(150)
turtle.rt(90)
turtle.circle(-37.5,180)
turtle.lt(130)
def letter_r_leg(t):
csquare = ((75**2) + (37.5**2))
sidec = math.sqrt(csquare)
turtle.fd(sidec)
letter_r_top(rob)
letter_r_leg(rob)
After each letter, i need to move the turtle into the right place to setup for the next letter. Because each of the letters are different sizes I need to make custom movements depending on what the previous letter is but I dont want to make separate functions for each of those movements.
At the end of my code I have the list of functions to be called in the correct order to spell my name
letter_t(rob)
letter_setup(rob)
letter_r(rob)
letter_setup(rob)
.....
Is there a way that I can do something like this so that I will only need 1 setup function.(Not real code, just a conceptualization of what I'm thinking
def letter_setup(t):
if previously executed function A
turtle.fd(75)
if previously executed function B
turtle.fd(75)
turtle.lt(90)
if previously executed function C
turtle.fd(75)
turtle.lt(90)
Why not the movement to the right place for the next letter at the end of the previous letter?
Perhaps there is a better way to do this but you could make a variable last_function_called and in each function you give it a different value then you'll know wich one was the last called :
last_function_called = NONE;
def function1():
last_function_called = FUNCTION1
blablabla
...
if (last_function_called == FUNCTION1):
call another one
and before of course something like :
NONE = 0
FUNCTION1 = 1
FUNCTION2 = 2
ect...

Is passing variables as arguments poor python?

I'm writing a printer calculator program. I want to take a "parent sheet" divide it into "run sheets" and then the runs into finish sheets. The size of parent, run and finish are input by the user.
There are other variables to be added later, like gutter and paper grain, but for now I just want to divide rectangles by rectangles. Here's my first crack:
import math
def run_number(p_width, p_height, r_width, r_height):
numb_across = p_width/r_width
numb_up = p_height/r_height
run_numb = numb_up * numb_across
print math.trunc(run_numb)
def print_number(f_width, f_height, r_width, r_height):
numb_across = r_width/f_width
numb_up = r_height/f_height
finish_numb = numb_up * numb_across
print math.trunc(finish_numb)
#Parent size
p_width = input("Parent Width: ")
p_height = input("Parent Height: ")
#Run size
r_width = input("Run Width: ")
r_height = input("Run Height: ")
#finish size
f_width = input("Finish Width: ")
f_height = input("Finish Height: ")
run_number(p_width, p_height, r_width, r_height)
print_number(f_width, f_height, r_width, r_height)
Am I using the arguments correctly? It seems wrong to create variables, pass those variables as arguments, then use those argument values. But, how I would I do this better?
The input call is outside the functions, but I'm using the same variable name (p_width, p_height, etc.), as I'm using inside the function. I don't think this is breaking this program, but I can't believe it's good practice.
It is perfectly fine to pass variable to a function as arguments! (I don't think there is another way)
If you don't want to save space, you could use input without making it an extra variable like this:
Instead of:
a = input("A: ")
b = input("B: ")
someFunction(a,b)
You can use:
someFunction(input("A: "),input("B: "))
I believe it is better than using global variables at all. Your method becomes much more general and independent of the context.

Categories