Changes

Jump to: navigation, search

OPS435 Python3 Lab 3

133 bytes added, 16:14, 19 September 2019
PART 2 - Function that does not take argument but return a value
</source><br><br>
== PART 2 - Function that does not take argument but return returns a value ==:#Let's create a function that '''returns''' some data to the caller after the function is called. This function does not print out any text: instead; it creates new variables objects and at the end returns the value of one of the variablesobject named '''greeting''', which is a string object containing 'Good Monring Terry'.<source lang="python">
def return_text_value():
name = 'Terry'
:# Call the function like this:<source lang="python">
return_text_value()
</source>One major difference between a function '''returning a value''' and simply '''printing a value''' is that '''returned''' values can be caught and stored in variables assigned to a object and can be used in the program (that called the function) for at a later usetime. Once the returned value has been storedassigned to an object, it can be printed, manipulated, compared in IF statements, etc. Below will cover how to store assign a returned valueto an object.<br><br>
:#Notice that this syntax looks just the call to the input() function which you've used in the last lab:<source lang="python">
text = return_text_value()
</source>
:#Now the returned text string from the function has been stored in the variable assigned to object named "'''text'''". It can be used like any string value object now.<source lang="python">
print(text)
</source>
'''Functions and Numbers (Integers)'''
: You will now learn how to define and run call functions that will return '''integer data''' when a function is called. In this section, you will define a function that will be returning an integer values instead of textstring. There is not a big difference, but when returning number values, care needs to be taken if you try combining it with a string!
:'''Perform the Following steps:'''
number = return_number_value()
print('my number is ' + number)
</source> What do you notice? You should notice a warning message. This occurs because the returning value is a '''numbernumeric''' object and NOT a '''string'''object! Combining numbers and strings in a statement (such as '''print()''') can cause errors. The error message should appear similar to the one displayed below: <source>
Traceback (most recent call last):
File "test.py", line 2, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
</source>
:#If a number needs to be combined with a string, use the '''str()''' predefined function that was discussed in a previous lab in order to convert the returned number object into a stringobject:<source lang="python">
number = return_number_value()
print('my number is ', number)
1,760
edits

Navigation menu