Programming and Computational Thinking

How do you use functions and methods in Python

How do you use functions and methods in Python

This post tells about functions and methods in Python.

First of all, we must notice that Python allows us to convert different types of data.

The int() function converts any value into an integer. When this function converts into the integer, it does not round off. Fraction part is usually chopped off.

The float() function converts integer numbers and strings into floating-point numbers.

The str() function converts integer and floating-point numbers into a string.

Python can perform variety of mathematical  operations. Some of operations can be used as they are, like sum (+), extraction (-), division (/), multiplication (*), exponentiation (**). Other mathematical functions can be used importing them from a math module available in Python. This module contains built-in functions and variables. You can see examples of math library in action executing the code in our Github library.

Another interesting module is random module that has several functions within it, returning numbers. For example, we can use is random() function. It returns a float number in a range between 0.0 and 1.0. The function randint(low, high) returns integer between low and high values (including them). The example of these functions are also can be accessed via our Github library.

We can only set our custom functions using Python. In order to define a function we must use a keyword def with the desired name of function (using the same rules as for variables). Function can none or more arguments or parameters at the input, mentioned in the parentheses. First line of a function is called header (ends with a colon), the rest part of a function is body (has any number of statements).  One function can be used inside of the other function. Function has to be defined before it can be executed.

Examples of  how to set the functions and how to use them can be accessed via our Github library through the link there.

In order to make loops we can use already considered condition structures for and while.

Let’s consider what operations we can do with strings.

  1. count amount of characters in a string
  2. return a string length
  3. slice and return pieces of a string
  4. identify certain characters in string (using boolean operator in)
  5. compare strings
  6. we can also apply certain methods to strings (like to other objects – integers, floating point numbers and others). In order to find out what methods are available to use with strings, you can use the code from our Github library. In order to call the method, we must use method syntax, also available in our examples.
  7. parsing strings. In order to do so we must use the find method and slice the string into pieces. Full documentation for strings can be found at the official Python website in the documentation directory.
  8. formatting string