Learn Python: Step-by-Step by Ambli Shreeharsh

Learn Python: Step-by-Step by Ambli Shreeharsh

Author:Ambli, Shreeharsh [Ambli, Shreeharsh]
Language: eng
Format: epub, pdf
Published: 2020-05-26T16:00:00+00:00


def add ( user_input ):

return user_input[ 0 ] + user_input[ 1 ]

def display_result ( inputs , result ):

print ( ' {} + {} = {} ' .format(inputs[ 0 ], inputs[ 1 ], result))

display_app_header( 'Addition program' )

user_input = get_user_inputs()

result = add(user_input)

display_result(user_input, result)

Notice get_user_inputs(). We need to get the user inputs properly converted to numbers & both the nos. returned so that the next function can use the inputs. To do so, we have used a list. A list is a structure used to store multiple data items. In this case, we are storing 2 different nos.

We first let Python know that the variable result is a list by using this syntax:

result = []

We can now add data to this list by calling append(), like so:

result.append( float (firstNo))

Finally, we return the list so that other functions can use the same for further processing:

return result

add() uses this list to add the supplied nos. & returns the result:

return userInput[ 0 ] + userInput[ 1 ]

It does this by using an index. Index basically lets us point to a particular item in a list & it starts with 0. So to point to the first number we use:

userInput[ 0 ]

The resulting program is a little longer but is more readable. If there are any issues or bugs (wrong code), we can easily go to that particular function & fix without reading the entire program to search.

The e.g. problem of adding two numbers has got us thus far. To learn more we need to switch our problem to a more complex one so that we can leverage other language features. We will next build a program to display the multiplication table for a given no.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.