What am I doing wrong in this Python program using functions? - python

Let me preface this by saying I am a total newbie to Python programming. Sorry to bother anyone with a possibly trivial question. But I am creating a program that calculates the user's BMI and displays their info along with their calculated BMI. I must create a function for the following:
1. BMI calculation
2. Retrieve user's weight
3. Retrieve user's height
4. Display user's weight, height, and calculated BMI
Here is my code:
BMI Calculator Code
These are my results:
Code Results
I'm supposed to show the calculated results too, but I'm doing one step at a time, making sure I can at least print the inputs first which is not happening. I'm so confused and don't know what to do to fix it. Any feedback is appreciated. Thanks.

use return
your input in function do not return any value to w, h, name in main code.
so, function need to be
def get_weight():
return int(input('message'))
return pass value to caller, now w can get value returned by get_weight function
w = get_weight()

Problem & Solution
You are getting the user input correctly, but you need to actually return the user input from the function for the value to accessible outside of the function. Currently in your code you are simply getting your user input, converting it to an integer, and immediately throwing away the values by letting them be garbage collected.
To return the value from the functions, use the return keyword:
def get_weight():
return int(input(...))
def get_height():
return int(input(...))
Improvements
Along with the solution above, there are some general improvements you can make to your code:
Follow PEP8. Put spaces between parameter, a newline at the end of the source file.
Use newline characters, rather than extra calls to print, for whitespace around displayed text. For example, use:
print('\nBMI calculator\n')
Rather than:
print()
print('BMI calculator')
print()

Related

Function provided by professor does not output anything

My professor for my python class had this defined function in the lecture as an example of how to print out a string that would tell us if the first pixel of an image is more red, blue or green. My issue is that it does not output any value. This is word for word the code she put in the lecture slide but it does not do anything for me in Mu. What am I missing?
Below is the code:
def func3(img,x,y):
pixel=img[x][y]
r=pixel[0]
g=pixel[1]
b=pixel[2]
if r<30 and g>230 and b<30:
colourname='green'
elif r>200 and g<30 and b<30:
colourname='red'
else:
colourname='blue'
return colourname
Seems you have not understood functions properly.
Functions are a block of code which can be used multiple times.
functions run some code and return a result, like in your function, it is returning colorname
Now to get the output from a function, the first thing we have to do is call it.
So after defining the function;
def func3(img,x,y):
pixel=img[x][y]
r=pixel[0]
g=pixel[1]
b=pixel[2]
if r<30 and g>230 and b<30:
colourname='green'
elif r>200 and g<30 and b<30:
colourname='red'
else:
colourname='blue'
return colourname
# now i will call the function by simply writing its name with parenthesis in which we have to provide the parameters required by the function
func3(some_img, x, y) # some_img, x, y are the values of the parameters on which the code will act.
Now if you want to print the result on the console, use the print function;
print(func3(some_img, x, y))
Extra points to be noted as a beginner
return statement doesnot print anything on the console but is used to return a value from a function. What that means is, after the functions runs its code, at the end, it should be giving some value . Like in your example, you should be able to know at the end, which color it is. For that you return the colorname. print function is for printing the things to the console.

using boolean in python from inputs

PhoneValue=0
if (condition== "new"):
PhoneValue=int(PhoneValue+10)
else:
PhoneValue=int(PhoneValue+9)
if GPS==bool(input("true")):
PhoneValue=int(PhoneValue+1)
else:
PhoneValue=int(PhoneValue)
if WiFi==eval(bool(input("true"))):
PhoneValue=int(PhoneValue+1)
else:
PhoneValue=int(PhoneValue)
if camera==eval(bool(input("true"))):
PhoneValue=int(PhoneValue+1)
else:
PhoneValue=int(PhoneValue)
global PhoneValue
This is my code. I am supposed to be able to input the condition, GPS, camera, and WiFi and the code evaluates the input and gives points for each condition. If the phone is new it gets ten points and if used it gets nine. For GPS, Camera, and WiFi it wants me to use boolean to either give it a point for true or no points for false. I am wondering how do I convert the input string into boolean in order to add it to phone value?
There's a lot wrong in this code. Firstly, the input() command is defined
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline.
which means your call to input("true") prints "true" on the console and waits for a line of input. That's not what you were hoping for.
Your use of eval is bad. Almost every use of eval on user input is a problem. But you saved yourself here by accident: eval(bool(text)) is superfluous. The only thing that bool() can return True or False neither of which is dangerous to eval, but since you already had a boolean in hand, eval'ing it didn't do anything.
Converting the result of integer addition to an int() is useless, and your if / else clauses can be more clearly written as:
if input("Is there a GPS? "):
PhoneValue += 1
with no else clause needed. Unfortunately, this has almost no chance of getting correct input. If I type "True" the if block will trigger. It will also trigger if I write "no", "false", or "JosEduSol", those will be evaluated as True also. The declaration at the end
global PhoneValue
does absolutely nothing as the last line. In fact, you should probably just forget that global exists because most everybody uses it incorrectly.
There are more faults in the code, and you should really get assistance from a teacher or get a better learning resource.

Let a function return nothing, not even "None" in Python 2.7.10 - possible?

Is there any way to prevent a python function to return anything, even None? I would need an output like:
[...]
[...]
but I always get:
[...]
None
[...]
If requested, I can upload the source code as well, but it's a bit long.
Thanks in advance for any answer!
Nope. Just check with if output is None: and change the output accordingly.
Okay so looking at your code I assume you are printing the last line of code that generates the end results being "Goodbye! Total score: 9 points.".
What you need to do is instead of printing that line return it and print the function call like shown below.
Also functions always return something be it a string, a int or whatever type of data you set it to.
If you choose to not return anything it will always return None.
For if you are wondering what the \n is for it's to open up a new line because it seems like you want the space of a line between sessions of your game.
If not you can get rid of the \n it doesn't affect the outcome.
Anyway hope this helps!
def no_name():
# return the line of code that generates this outcome instead of printing it
#to get rid of the None.
return "Goodbye! Total score: 9 points.\n"
print no_name()
In Python an expression will always have to produce a result. Function calls are expressions, and are no exception here. As a result, any callable, including functions, produce a result, even if that result is None. From the documentation:
A call always returns some value, possibly None, unless it raises an exception.
You could just test for None:
result = functioncall()
if result is not None:
# ...

Python – Breaking out of a deeply nested loop with `while`, `try`, `if`, and `except` statements

Here is my code that solves a quadratic equation given user inputs a, b, c. However, I want to check for incorrect user inputs. If a user inputs anything but a float, the user is confronted with print "Not a valid input. Try again.\n" followed by a loop of the function quadratic2(). However, this program is part of a larger program, so I want the user to have the option of typing in "next" to terminate this function and move on. My issue is that I am calling for 3 user inputs, but I want the "next" input to be the first input, a. This works perfectly well until the user types in a random string, causing a ValueError. Once this happens, my code does not want to loop back to check for if the input is next. Please help me! I think something about the way this code is nested is messing me up.
def retest3():
print "Type in another a, b, and c. Or type \"Next\" to move on."
def quadratic1():
print ("This program calculates the zeroes of a quadratic equation."
"\nPlease enter a, b, and c, hitting \"Enter\" after each one: ")
def quadratic2():
while 1 == 1:
a = (raw_input())
if "next" == a.lower():
ontonextthing()
return 1 == 0
else:
try:
a = float(a)
except ValueError:
print "Not a valid input. Try again.\n"
quadratic2()
try:
b = float(raw_input())
except ValueError:
print "Not a valid input. Try again.\n"
quadratic2()
try:
c = float(raw_input())
except ValueError:
print "Not a valid input. Try again.\n"
quadratic2()
if b**2-4*a*c>0:
root1=(-b+math.sqrt(b**2-4*a*c))/(2*a)
root2=(-b-math.sqrt(b**2-4*a*c))/(2*a)
print ("First Root: {0}\nSecond Root: {1}".format(root1,root2))
else:
print ("The discriminant is negative, so your"
" roots will contain \"i\".")
disc1=(b**2-4*a*c)
disc2=-disc1
sqrtdisc2=(math.sqrt(disc2))/(2*a)
b2=(-b)/(2*a)
print ("{0} + {1}i".format(b2, sqrtdisc2))
print ("{0} - {1}i\n".format(b2, sqrtdisc2))
retest3()
quadratic1()
quadratic2()
This works perfectly well until the user types in a random string, causing a ValueError. Once this happens, my code does not want to loop back to check for if the input is next.
Seems like you want the continue statement:
try:
b = float(raw_input())
except ValueError:
print "Not a valid input. Try again.\n"
continue
The continue statement takes you back to the beginning of your while loop (the next iteration). Currently you are calling quadratic2() which makes your function recursive, and not what you want.
Because it's recursive, when you receive your Exception it exits the current function, but because you were using recursion, you simply return back to the previous function you were in the middle of (which is the same function). Therefore the next input you type could be parsed by
b = float(raw_input())
instead of
a = (raw_input())
The "real" solution for your problem is not to use deeply nested constructs in the first place. Deeply nested statements make your code hard to read, hard to test, hard to maintain and hard to reuse. Also, you will tend to duplicate code, which is bad. Especially in Python, deep nesting will cause you to count spaces to get the indentation right, which is really a pain in the neck.
Break your code into functions, and follow the "single responsibility principle" by letting one function do exactly one thing. This has several advantages:
You don't have to keep too many things in your mind. Focus on one small problem, and be done with it.
You can always return early in a function, so you can avoid nesting in many cases.
You can reuse the code in your function.
You don't have duplicate code: If you want to change a particular behavior, change one function instead of several places in one function.
You can test your functions in isolation, making sure that they do the right thing.
In your case, the quadratic2 function does a lot of things:
It runs a "main loop"
It reads user input for commands
It dispatches the command
It reads user input for values
It handles invalid user input
It does computations
It displays the result back to the user
Now I don't say that you need one function for every detail listed above, but it is rather obvious that this function does too much.
Examples on how you could break it up:
Make one function for the main loop and for dispatching commands. Let the commands (such as "next") be handled in separate functions.
Write one function to read in a float from the user, and call this three times instead of repeating the try...except code three times. This has the added benefit that you can enhance this function to run in a loop, so that the user is asked to repeat the input for one value, instead of having to start all over again as your current solution does.
Other tips:
Don't use else after return, raise, break, or continue. It is not necessary, since the next statement will not be reached anyway, and you can save one nesting level.
Don't use confusing expressions like 1==1 or 1==0. This is just a complicated way of writing True and False. In your example, it should read while True and return False instead.

Placing a Python variable inline

Forgive this rather basic Python question, but I literally have very little Python experience. I'm create a basic Python script for use with Kodi:
http://kodi.wiki/view/List_of_built-in_functions
Example code:
import kodi
variable = "The value to use in PlayMedia"
kodi.executebuiltin("PlayMedia(variable)")
kodi.executebuiltin("PlayerControl(RepeatAll)")
Rather than directly providing a string value for the function PlayMedia, I want to pass a variable as the value instead. The idea is another process may modify the variable value with sed so it can't be static.
Really simple, but can someone point me in the right direction?
It's simple case of string formatting.
template = "{}({})"
functionName = "function" # e.g. input from user
arg = "arg" # e.g. input from user
formatted = template.format(functionName, arg)
assert formatted == "function(arg)"
kodi.executebuiltin(formatted)
OK as far as I get your problem you need to define a variable whose value could be changed later, so the first part is easier, defining a variable in python is as simple as new_song = "tiffny_avlord_I_love_u", similarly you can define another string as new_video = "Bohemia_on_my_feet", the thing to keep in mind is that while defining variables as strings, you need to encapsulate all the string inside the double quotes "..." (However, single quotes also work fine)
Now the issue is how to update it's value , the easiest way is to take input from the user itself which can be done using raw_input() as :
new_song = raw_input("Please enter name of a valid song: ")
print "The new song is : "+new_song
Now whatever the user enters on the console would be stored in the variable new_song and you could use this variable and pass it to any function as
some_function(new_song)
Try executing this line and you will understand how it works.

Categories

Resources