Is passing variables as arguments poor python? - 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.

Related

when to use functions in python and when not to?

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.

How can I pass user input in the form of a variable to a lambda function in python?

so I'm kind of new to programming and I was looking for some help. I'm making a graphing calculator and would like to have the user enter an equation using x such as (x + 3) or (x^2 + 3x + 4). I recently found out about the lambda function and was wondering if there was a way to pass a variable to it in order to get plot points with the user's equation. I plan on using a for loop to keep passing new values into the equation. If you have any other suggestions on how to go about completing my graphing calculator please do not hesitate to inform me. My code so far is only a way for the user to navigate through my program. Here is my code:
def main():
while True:
response = menu()
if response == "1":
print("enter an equation in the form of mx + b")
equation = (input())
print(coordinates(equation))
elif response == "2":
print("enter a value for x")
x = input()
print("enter a value for y")
y = input()
elif response == "0":
print("Goodbye")
break
else:
print("please enter '1' '2' or '0'")
def menu():
print("Graphing Calculator")
print("0) Quit")
print("1) Enter an equation")
print("2) Plot points")
print("Please select an option")
response = input()
return response
"""def coordinates(equation):
f = lambda x: equation
"""
if __name__ == "__main__":
main()
I get that I'm answering your question twice. But this time, I'm gonna show you something pretty freaking cool instead of just fixing your code.
Enter: Sympy. Sympy is a module of the Numpy package that does symbolic manipulation. You can find some documentation here.
Great, another module. But what does it do?
Sympy keeps equations and expressions as symbols instead of variables. Go ahead and import sympy or pip install it if you don't have it. Now, let's build an evaluation unit for that monovariate equation coordinate finder. First, let's make sure python knows that x is a sympy symbol. This is important because otherwise, python treats it like a normal variable and doesn't hand control over to sympy. Sympy makes it easy to do this, and even supports making multiple symbols at once. So go ahead and do x, y, z = sympy.symbols("x y z"). Now, let's ask for the function.
def make_an_equation(raw_equation = ""):
if raw_equation == "": #This allows for make_an_equation to be used from the console AND as an interface. Spiffy, no?
raw_equation = raw_input("Y=")
#filter and rewrite the equation for python compatibility. Ex. if your raw_equation uses ^ for exponentiation and XOR for exclusive or, you'd turn them into ** and ^, respectively.
expr = eval(filtered_equation)
return expr
Ok, you've got a thing that can make an equation. But... You can't quite use it, yet. It's entirely symbolic. You'll have to use expr.subs to substitute numbers for x.
>>> my_expression = make_an_equation("x**2") #I'm assuming that the filter thing was never written.
>>> my_expression
x**2
>>> my_expression.subs(x,5)
25
See how easy that is? And you can get even more complex with it, too. Let's substitute another symbol instead of a number.
>>> my_expression.subs(x,z)
z**2
Sympy includes a bunch of really cool tools, like trig functions and calculus stuff. Anyways, there you go, intro to Sympy! Have fun!
So... I went ahead and reviewed your whole code. I'll walk you through what I did in comments.
def main():
while True:
response = raw_input("Graphing Calculator\n0) Quit\n1) Enter an equation\n2) Plot points\nPlease select an option\n>>>")
#I removed menu() and condensed the menu into a single string.
#Remember to use raw_input if you just want a string of what was input; using input() is a major security risk because it immediately evaluates what was done.
if response == "1":
print("Enter an equation")
equation = raw_input("Y=") #Same deal with raw_input. See how you can put a prompt in there? Cool, right?
finished_equation = translate_the_equation(equation)
#This is to fix abnormalities between Python and math. Writing this will be left as an exercise for the reader.
f = coordinates(finished_equation)
for i in xrange(min_value,max_value):
print((i,f(i))) #Prints it in (x,y) coordinate pairs.
elif response == "2":
x = raw_input("X=? ")
y = raw_input("Y=? ")
do_something(x,y)
elif response == "0":
print("Goodbye")
break
else:
print("please enter '0', '1', or '2'") #I ordered those because it's good UX design.
coordinates = lambda equation: eval("lambda x:"+ equation)
#So here's what you really want. I made a lambda function that makes a lambda function. eval() takes a string and evaluates it as python code. I'm concatenating the lambda header (lambda x:) with the equation and eval'ing it into a true lambda function.

Python (Alternate two messages)

I have some code, and my goal is to make it so that when left button is clicked it will post text saying "Programming is fun!" and when it is pressed again, it will change that text to "It is fun to program", my idea was to make x = 0 if I wanted the first statement, and x = 1 if I wanted the second statement, but it keeps saying x is not defined, I've tried returning x but it simply won't... I've tried a variety of different methods but I can't figure it out. Thoughts? I'd like an alternative method to this, because I'm not sure that mine will work.
def text():
pf = Label(window2,text="Programming is fun")
pf.pack()
x = 0
def text2():
fp = Label(window2,text="It is fun to program")
fp.pack()
x = 1
def bt(event):
if x == 0:
text()
elif x == 1:
text2()
window2 = Tk()
window2.geometry("500x500")
The problem is that, in the scope of your functions, the variable x is indeed undefined.
An example:
height = 5
def some_function():
# code here can not access height just like that
When you want to access variables in functions, you generally have three options:
1) Put your code in a class instead. This requires some understanding of object oriented programming, and if you're a beginner this might not be the best choice for you
2) Pass the variable as an argument to the function and add it to the function's parameter list, for example like this:
def my_function(height):
# here height can be used
And when calling the function:
height_of_bob = 2
my_function(height_of_bob)
3) Use a global variable. This is usually not necessary, and is considered bad practice in general, but it will solve your problem just fine.
I found a way to do this below, the down low is that it's creating the text through that function, and then it's rebinding the key to do other function and then that function deletes previous text, creates the new text and then rebinds to the previous function, and the cycle continues. Here's the code.
def text(event):
global pf
fp.pack_forget()
pf = Label(window2,text="Programming is fun")
pf.pack()
window2.bind("<Button-1>", text2)
def text2(event):
global fp
pf.pack_forget()
fp = Label(window2,text="It is fun to program")
fp.pack()
window2.bind("<Button-1>", text)
window2 = Tk()
window2.geometry("500x500")
pf = Label(window2,text="Programming is fun")
fp = Label(window2,text="It is fun to program")
window2.bind("<Button-1>", text)

I'm trying to put these inputs into a text file, [duplicate]

This question already has answers here:
Print string to text file
(8 answers)
Closed 6 years ago.
In class we are working on functions that calculate the area of a square or rectangle. The program asks for a person's name, what shape they want and what the length and width are. It then prints the area of that shape, and the program loops back around again. What I'm looking to do is take each individual name input and area and output them into a text file. Our teacher didn't make it too clear on how to do this. Any help would be appreciated. Here's the code:
import time
def area(l, w):
area = l * w
return area
def square():
width = int(input("please enter the width of the square"))
squareArea = area(width, width)
return squareArea
def rectangle():
width = int(input("please enter the width of the rectangle"))
length = int(input("please enter the length of the rectangle"))
rectangleArea = area(length, width)
return rectangleArea
def main():
name = input("please enter your name")
shape = input("please enter s(square) or r(rectangle)")
if shape == "r" or shape =="R":
print ("area =", rectangle())
main()
elif shape == "s" or shape == "S":
print ("area =", square())
main()
else:
print ("please try again")
main()
main()
Edit: I don't think I asked the question clear enough, sorry. I want to be able to input something, e.g. the name and be able to put it into a text file.
Easy way:
file_to_write = open('myfile', 'w') # open file with 'w' - write permissions
file_to_write.write('hi there\n') # write text into the file
file_to_write.close() # close file after you have put content in it
If you want to ensure that a file is closed after you finished all operations with it use next example:
with open('myfile.txt', 'w') as file_to_write:
file_to_write.write("text")
This is what you're looking for. The line file = open('file.txt', 'w') creates a variable file, in which the file object representing 'file.txt' is stored. The second argument, w, tells the function to open the file in "write mode", allowing you to edit its contents.. Once you have done this, you can simply use f.write('Bla\n') to write to the file. Of course, replace Bla with whatever you'd like to add, which can be your string variable. Note that this function doesn't make a newline afterwards by default, so you'll need to add a \n at the end if that's what you want.
IMPORTANT: As soon as you're done with a file, make sure to use file.close(). This will remove the file from memory. If you forget to do this, it won't be the end of the world, but it should always be done. Failure to do this is a common cause of high memory usage and memory leaks in beginner programs.
Hope this helps!
Edit: As MattDMo mentioned, it is best practice to open a file using a with statement.
with open("file.txt", 'w') as file:
# Work with data
This will make absolutely sure that access to the file is isolated to this with statement. Thanks to MattDMo to for reminding me of this.

Saving output of a function as a variable and using it in another function

I'm new to programming, so this question might be dumb.
I need to introduce the value of Tr1 into the Bzero1 function. When I run the module I get the result below:
.
The program is not running the Bzero1 function and I'm not sure why. Is it because I am not introducing the Tr1 value correctly or something else? I want Bzero1 to perform the operation 0.083-(0.422/Tr1**1.6), with Tr1 obtained from the result of T/Tc1.
I would appreciate your help a lot.
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
Tc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", Tc1)
def Tr1(T, Tc1):
print("Relative temperature 1: ", T/Tc1)
Tr1 = Tr1(T, Tc1)
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
Do not replace Tr1 function value, to avoid such replacement change:
Tr1_value = Tr1(T, Tc1)
Call Bzero1 function with code:
Bzero1(Tr1_value)
Modify Tr1 to return value:
def Tr1(T, Tc1):
result = T/Tc1
print("Relative temperature 1: ", result)
return result
Also, let me suggest you to take a look on python official tutorial - there you can learn a lot about python ...
Good Luck !
def is only defining a function, not calling it. E.g.
def foo(a):
print a * 2
means there is now a function foo that takes argument a. The a in foo(a) is the name of the variable inside the function.
So in your case
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
defines the function Bzero1 as taking argument Tr1, but doesn't call it. You need to call the function, just like you called Tr1:
Bzero1(Tr1)
You can see that this way it becomes confusing quite quickly on which is a variable outside of your function, and which are variables inside functions. Therefore it is better to use different names for variables in your outer program v.s. those inside functions.
Here are a few more best practices that you might find useful:
It is generally better to first define all functions and then execute the program's main code, as opposed to intermixing function definitions and the main program.
Another best practice is to make functions only calculate output from inputs, and handle output somewhere else. This way you get to reuse your functions in other parts of your program while always keeping control of when and what to output to the user.
Finally, you shouldn't generally reassign names, e.g. Tr1 = Tr1(...) means that Tr1 is now no longer the name of the function but the name of the result returned by Tr1. In short, use different names for different things.
Applying these tips, your code might look as follows:
# function definitions first
def Tr1(vt, vtc1):
return vt/vtc1
def Bzero1(vtr1):
return 0.083-(0.422 / vtr1 ** 1.6)
# get user input
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
vTc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", vTc1)
# run calculations
vTr1 = Tr1(T, vTc1)
vBz1 = Bzero1(vTr1)
# print output
print("Relative temperature 1: ", vTr1)
print("Bzero 1: ", vBz1)
Note
Since I don't know the semantic meaning of your variables I have just used small letter v as a prefix - in general it is better to use meaningful names like temperature or temp1 and temp2 etc. Programs are not math papers.

Categories