def vel(y,umax,r,Rmax):
vel_p=umax*(1-(r/Rmax)**2)
if r<50:
r=50-y
else:
r=y-50
return 'the value of velocity in cell is %r,%r,%r,%r'%(umax,r,Rmax,vel_p)
def main ():
y=(input('enter y'))
a=(input('enter the umax'))
#b=(input('enter the r'))
b=(r)
c=(input('enter the Rmax'))
print(vel(a,c,b,y))
main()
i do not understand where i should put r it gives me an error global variable r not defined
As already mentioned in the comments, try to use "good" (=readable) variable names since this helps to reduce confusion.
The conversion from string to float should be made robust against non-numerical input with try...except, so I put that in a separate function.
Usually you don't want a function to return a string with all your calculated values inserted, but the "raw" values. The printing of those values should normally be done somewhere else.
In the comments you mention you "need to get the value of r from y, if i do not put that in comments it is taking my value of r and will not calculate from the if r statement", but your function vel() uses r to calculate vel_p in the very first line. The variable r is an argument to the function, so it has to come from somewhere. Either you let the user input it like all the other values, or you have to define it somewhere else. If you do that globally, have a look at Vipin Chaudharys answer.
My suggestion, if you want the user to input r:
def vel(y, u_max, r, r_max):
# You use the value of r here already!
vel_p=u_max*(1-(r/r_max)**2)
# Here you change r, if r is less than 50.
# You are using r again, before assigning a new value!
if r<50:
r=50-y
else:
r=y-50
# I use the preferred .format() function with explicit field names
# \ is used to do a line-break for readability
return 'The value of velocity in cell is umax: {value_u_max}, \
r: {value_r}, Rmax: {value_r_max}, vel_p: {value_vel_p}.'.format(
value_u_max=u_max, value_r=r,value_r_max=r_max, value_vel_p=vel_p)
# Helper function to sanitize user input
def numberinput(text='? '):
while True:
try:
number=float(input(text))
# return breaks the loop
return number
except ValueError:
print('Input error. Please enter a number!')
def main():
y=numberinput('Enter y: ')
u_max=numberinput('Enter the umax: ')
r=numberinput('Enter the r: ')
r_max=numberinput('Enter the Rmax: ')
print(vel(y, u_max, r, r_max))
main()
Notice, that the input value of r is used to do the calculation. Then it is changed depending on y, and the new value gets printed.
In your main method , you assigned b = (r) whereas you never specified what is r , so if you have variable r in your global scope then the first line in the main method should be
def main():
global r
# Now you can use your r
by doing so , you called your variable r in your method.
Hope it helps :)
Related
Below is my work. I did the printline function before, and this question required to call the function printline above for printing each line. I try to print 3 lines, each line has 4 symbols, but I only can get 2 lines, each line comes with 12 symbols. Can someone help me correct my code?
def printline(num,sym):
for i in range(num):
a = (num*sym)
return a
a = printline(5,'*')
print(a)
def printrectangle(num,height,sym):
for i in range(height):
a = printline(num,sym)*height
print(a)
return a
c = printrectangle(3,4,'*')
print(c)
A few things here:
Your printline function works, but overcomplicates the problem.
In other programming languages, in order to repeat the same string multiple times it is common to create a loop of the form:
String s = "";
for(int i = 0; i < num; i++)
s += sym;
return s;
Since this is equivalent to just concatenating the same string num times, in python there is a simpler way to do this:
s = sym*num
Your solution works because you are overwriting the value in the variable a for num times before returning it.
You misinterpreted your testcase.
You said printrectangle(3, 4, '*') should print 3 lines with 4 symbols. But as you wrote it, the first variable num=3, and the second variable height=4.
The output here is in fact:
***
***
***
***
Your code does not currently do that, but let's not get ahead of ourselves.
Indentation error
The return statement in the printrectangle function is inside the loop. This means that during the first iteration of the loop, the function will return a value.
Easy fix, just backspace until the indentation of the return lines up with that of the loop.
Actually solving the problem.
From part 1, I introduced here that in python to concatenate the same string multiple times you may simply multiply the string by the number of times you want it to show up.
Here we want the string printline(num, sym) to show up height times with an enter key after each time.
The enter key sends the command of \n. In other words, a string such as 'a\nb' is printed as:
a
b
For our purposes, we can concatenate the string printline(num, sym) with \n first, and then multiply the resulting string by height to get the result of printrectangle(num, height, sym)
def printrectangle(num, height, sym):
a = (printline(num, sym)+'\n')*height
return a
Though this code will give you what you are looking for, I still doubt by mistake you swapped num and height values in the call printrectangle(3,4,'*') itself
def printline(h,sym):
a = h*sym # removed unnessary loop
return a
def printrectangle(num,height,sym):
for i in range(num): # swap height with num in your code
a = printline(height,sym) #swap num with height in your code
yield a
for row in printrectangle(3,4,'*'):
print(row)
Thanks firstly for bearing with me as a relative newcomer to the world of Python. I'm working on a simple set of code and have been racking my brain to understand where I am going wrong. I suspect it is a relatively simple thing to correct but all searches so far have been fruitless. If this has been covered before then please be gentle, I have looked for a couple of days!
I'm working on the following and after catching and correcting a number of issues I suspect that I'm on the last hurdle:-
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(our_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(our_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(our_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
main()
else:
print("Goodbye")
break`
For some reason the appended (our_list) is not being recognised within the while true loop rendering the statistics calculation void. Any steer would be really appreciated as to where I am missing the obvious, thanks in advance.
Cheers
Bryan
I'm not sure exactly what you mean by "not being recognized", but our_list is a local variable inside main, so it can't be used anywhere but inside main.
So, if you try to use it elsewhere, you should get a NameError.
If your code actually has a global variable with the same name as the local variable that we aren't seeing here, things can be more confusing—you won't get a NameError, you'll get the value of the global variable, which isn't what you want.
The best solution here is to return the value from the function, and then have the caller use the returned value. For example:
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
return our_list
the_list = main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(the_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(the_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(the_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
the_list = main()
else:
print("Goodbye")
break
There are other options—you could pass in an empty list for main to fill, or use a global variable (or, better, a more restricted equivalent like an attribute on a class instance or a closure variable), or refactor your code so everyone who needs to access our_list is inside the same function… but I think this is the cleanest way to do what you're trying to do here.
By the way, this isn't quite the last hurdle—but you're very close:
After any mean, median, or mode, it's going to hit the "Goodbye" and exit instead of going back through the loop. Do you know about elif?
You mixed up '5' and '4' in the menu.
If the user enters 2 and 3 and asks for the mode, your code will dump a ValueError traceback to the screen; probably not what you want. Do you know try/except?
That's all I noticed, and they're all pretty simple things to add, so congrats in advance.
The issue is that our_list was defined in the main() function, and is not visible outside of the main() function scope.
Since you're doing everything in one chunk, you could remove line 1 and 6, taking the code from your main() function and putting it on the same indentation level as the code which follows.
This seems to be because you defined our_list within the main() function. You should probably define it as a global variable by creating it outside the main() function.
You could also put the while loop inside a function and pass in our_list as a parameter to the list.
I'm having issue with allowing a function to call on variables set by another function. I believe I know how to do this with single variables, but my code requires it be done with multiple variables, a challenge I've struggled with for hours. I've read much about ways others seem to have done this but I can't find success in implementing them.
#gathers the user's requests
def ask():
userw = int(input('How wide? '))
userh = int(input('How tall? '))
userc = input('What string to use? ')
userc_len = int(len(userc))
return (userw, userh, userc, userc_len)
#draws the rows of the box. First the top with the topbot function, then the body with body(), then the bottom with topbot again
def draw(w, h, c, c_len):
def topbot(w_, c_):
for x in range(w_):
print (c_, end ='')
print ('\n')
def body(w_, h_, c_, c_len_):
for x in range(h_-2):
print (c_, end = '')
for x in range(w_-2):
print(' ' * c_len_, end = '')
print (c_)
topbot(w, c)
body(w, h, c, c_len)
topbot(w, c)
#begins draw
draw(userw, userh, userc, userc_len)
The problem begins when the draw function tries to begin with the arguments of userw, userh, userc, userc_len, but can't find them:
NameError: name 'userw' is not defined
is returned when I try to run it.
Is it correct to define topbot and body within the draw function and manage the arguments how I did?
How do I return the four variables from ask in a manner such that draw can then use them as arguments?
ask() is a function which will return 4 values. So,
returnValues = ask()
draw = draw(*returnValues)
or simply, draw = draw(*ask())
Also, end = ' ' is not correct. Instead of that you can just use print(c_,'').
Include Validations wherever necessary. Like what if I type "hi" for "How wide?". In this case the program should tell me that this is wrong.
I was able to get draw() to accept the inputs from your ask() function (in Python IDLE) just by changing the last line of your code to this:
draw(*ask())
The * will unpack the variables from the ask() call and pass that along to draw(). The output looks kind of funny, and I'm not sure whether that's what you're looking for or not, but at least it got the variables in there correctly.
I'm quite new to Python, and I'm busy trying to figure out how these pesky functions work... The program I'm making is supposed to be working out the area of a triangle, but I can't actually get it to return the local variables to other functions. Any help would be greatly appreciated!
# Area of a triangle
base = 0
height = 0
area = 0
def inData():
base = float(raw_input("Base:"))
height = float(raw_input("Height:"))
return base
return height
def triangle(b,h):
area = b / 2 * h
return area
if __name__ == '__main__':
inData()
triangle(base, height)
print "The area of a triangle of base", base, "and height" , height, "will be", area
There are many problems and misconceptions I see in your code; Let me see if I can start from scratch and try to convey the proper way to do these functions for you. In the end, we will have a working version of your code. :)
note: You do not have to declare functions ahead of time in Python-- it does that itself! So no need for base, height, area at the top!
Functions
Functions are in short, sets of commands that get run in a bundle. You know this. What you miss though are the concepts of arguments and parameters and return vs print.
Arguments vs Parameters
When you define a function, you are setting up what you want it to do in the future and at your beck and call. Just like any function f(x) in math, you want one equation that will work with whatever input you give it. For f(x), x is your input.
In programming, this is referred to as a parameter. So when you write in Python:
def Function(x):
y = x*x
return y
You have defined x as your parameter. Now, Arguments are the values that you put into a function, where the parameters go. In Algebra, the applicable idea would be defining a variable. Knowing this, when you actually use that function:
Function(2)
You will get back 4, because you said run Function(x) where x = 2.
This is the concept of Arguments vs Parameters. It is very useful, because you don't always want to ask a user for input inside the function. The more direct your function is, the less it can do. Sometimes you want to use that same function to do math in the background, for example. You can't very well have raw_input() if you expect the process to work on its own in the background, can you?
This is the true value of Arguments vs Parameters.
Return vs Print
In the same vein as not using raw_input() because it is too direct, you want to avoid using print and use return instead. I know you didn't use print here, but you've misunderstood the workings of return and I figure the same lesson applies.
Here is an example: You have two functions.
def Function1(x,y):
z = x*y
print z
def Function2(x,y):
z = x*y
return z
Function 1 prints z, which means that no matter what you want it to do, it will always print z to the console, even if you want it to just do the math.
Meanwhile, Function 2 returns z, meaning it hands back the value of z to the program as it was called. It is also worth noting that as soon as a function hits the line return, it stops running the function further. There is no reason to code beyond this, because the function is no longer being run, unless you had a more advanced code that skipped over return (for example, an if statement).
Why is return so conceptually important?
Because in your original code, you run the function inData(), and after that, not only do you run return twice, but in your if statement, you don't even use what inData returns, you just tell the program to run inData().
When a function returns a value, you have to assign it to something. Take, for instance, simple math in any random programming language. The code:
x = sqrt(4)
print x
will output 2, because at the end of the function sqrt(), it returns its answer. Here, we assigned x to be variable that sqrt(4) gives a return to. While it's true that:
sqrt(4)
will also print 2 to the console, this is because of fool-proofing by language developers, where in fact the language assumes you want the code printed. You're not telling it to do that.
So, when you run the lines of code:
inData()
triangle(base, height)
You are basically saying:
run the function inData()
run the function triangle(base, height)
When, because of their returns, you need to be saying:
set <variable1> equal to the return of inData()
set <variable2> equal to the return of triangle(base,height)
(there is more simplification to be done here, but we'll approach it in a moment).
One last thing on return. In programming, it is useless to write:
x = 1+1
return x
When return 1+1 accomplishes the same thing. Thus, no need to define what the area of a triangle will be and then return the area. Just tell the function to return what it calculates the area to be in the same line of code!
Have I lost you? Still with me? Good!
Simplification of your code
Your code has a few structural problems that, while it may work, would baffle any more seasoned programmer that looked at it. While we're here, why don't we see if I can have you understand what a better practice for this would be.
In your code, you have written (in a summarized form)
variables defined that you don't need
def FunctionThatGathersData()
def FunctionThatDoesTheMath(x,y)
if (condition)
FunctionThatGathersData()
FunctionThatDoesTheMath(x,y)
print out the results
The structure of this would confuse a programmer who has more experience. He might ask the following questions:
What?
Why are you returning things this way?
Why are the variables defined?
Why don't you combine FunctionThatGathersData and FunctionThatDoesTheMath?
Some of these reasons are already exposited upon above, but let's get to the last two questions.
Why are the variables defined?: On one hand, Python handles variables during execution. So you never have to define them ahead of time, but you can, and the advantage of this is as follows:
x = 0
def Function()
x = 5
y = 10
Looking at this code, you might wonder why x is defined. The simple answer is that Python will see that you already have an x, and thus, when you run Function(), you want to overwrite it with the work inside the function. y on the other hand, has no previous definition, and thus a new variable will be created.
However, in your function we don't need any of that because your answer, in its best form, won't need to depend on x outside the function.
Why can't we just combine the two functions together, using what we learned about parameters, arguments, and returns? (hint: we can!)
Here is a new snippet of code that you should now be able to read and understand. Clear your head of what you've read for a moment and see if it makes sense. In it, you will:
Define your function DoTheMathAndThenGiveMeTheValueBack
Decide if __name__ == '__main__'
Provide your values (put them in variables)
Pass those variables as arguments into the function
tell the program to print the base and height and then area based on the function's return.
The Code
def CalculateTriangleArea(b,h):
return b / 2 * h
if __name__ == '__main__':
base = float(raw_input("Base:"))
height = float(raw_input("Height:"))
area = CalculateTriangleArea(base,height)
print "The area of a triangle of base", base, "and height", height, "will be", area
If you do not grok this, please, comment and ask me more because I remember struggling with this and know what misunderstandings you are having.
Oh! And I forgot to mention to you what to do about multiple returns.
In the event that you need to return more than one value in a function, you can do so through an array or a tuple. This is just a list of values you have stored. You can access any item in an array or tuple by including the index at the end in the form of [i], where the first item is at [0]. For example:
def Function():
string1 = "nobody"
string2 = "expects"
string3 = "the"
string4 = "spanish"
string5 = "inquisition"
return string1, string2, string3, string4, string5
print Function()[0]
print Function()[1]
print Function()[2]
print Function()[3]
print Function()[4]
print Function() #prints the whole tuple!
Will get you:
nobody
expects
the
spanish
inquisition
('nobody', 'expects', 'the', 'spanish', 'inquisition')
Understand? :)
For more hands-on work in python, try this amazing Python tutorial.
When you do return, the function immediately ends, returning the value. Therefore, your inData function will only return the base, not the height. In addition, you seem to be asking the user to input the base and the height twice -- that's unnecessary, since your inData function already does that
Rather, you want to return two values at the same time by doing something like this. (Note -- I renamed some of your functions for clarity)
# Area of a triangle
def get_user_input():
base = float(raw_input("Base:"))
height = float(raw_input("Height:"))
return base, height
def triangle_area(b, h):
area = b / 2 * h
return area
if __name__ == '__main__':
base, height = get_user_input()
area = triangle_area(base, height)
print "The area of a triangle of base", base, "and height" , height, "will be", area
The problems with your code:
# Area of a triangle
base = 0 # You don't need to initialize these values. Even if you want
height = 0 # to make these global you can simple assign inside the if
area = 0 # __name__ == '__main__' condition
def inData():
base = float(raw_input("Base:"))
height = float(raw_input("Height:"))
return base # return immediately stops the execution of the function
return height # and returns the value
def triangle(b,h):
area = b / 2 * h
return area
if __name__ == '__main__':
inData() # You are not assigning the returned value to any variable
triangle(base, height)
print "The area of a triangle of base", base, "and height" , height, "will be", area
Correct version of your program:
# Area of a triangle
def inData():
base = float(raw_input("Base:"))
height = float(raw_input("Height:"))
return base, height
def triangle(b,h):
area = b / 2 * h
return area
if __name__ == '__main__':
base, height = inData()
area = triangle(base, height)
print "The area of a triangle of base", base, "and height" , height, "will be", area
Question: write a program which first defines functions minFromList(list) and maxFromList(list). Program should initialize an empty list and then prompt user for an integer and keep prompting for integers, adding each integer to the list, until the user enters a single period character. Program should than call minFromList and maxFromList with the list of integers as an argument and print the results returned by the function calls.
I can't figure out how to get the min and max returned from each function separately. And now I've added extra code so I'm totally lost. Anything helps! Thanks!
What I have so far:
def minFromList(list)
texts = []
while (text != -1):
texts.append(text)
high = max(texts)
return texts
def maxFromList(list)
texts []
while (text != -1):
texts.append(text)
low = min(texts)
return texts
text = raw_input("Enter an integer (period to end): ")
list = []
while text != '.':
textInt = int(text)
list.append(textInt)
text = raw_input("Enter an integer (period to end): ")
print "The lowest number entered was: " , minFromList(list)
print "The highest number entered was: " , maxFromList(list)
I think the part of the assignment that might have confused you was about initializing an empty list and where to do it. Your main body that collects data is good and does what it should. But you ended up doing too much with your max and min functions. Again a misleading part was that assignment is that it suggested you write a custom routine for these functions even though max() and min() exist in python and return exactly what you need.
Its another story if you are required to write your own max and min, and are not permitted to use the built in functions. At that point you would need to loop over each value in the list and track the biggest or smallest. Then return the final value.
Without directly giving you too much of the specific answer, here are some individual examples of the parts you may need...
# looping over the items in a list
value = 1
for item in aList:
if item == value:
print "value is 1!"
# basic function with arguments and a return value
def aFunc(start):
end = start + 1
return end
print aFunc(1)
# result: 2
# some useful comparison operators
print 1 > 2 # False
print 2 > 1 # True
That should hopefully be enough general information for you to piece together your custom min and max functions. While there are some more advanced and efficient ways to do min and max, I think to start out, a simple for loop over the list would be easiest.