LearnWave
Learn it. Master it.

Brief Overview of Python

Functions

Name a function's arguments and return value.

A function is a set of statements grouped under a name to do a particular task. It is defined once and called (by its name) wherever needed. For example, a program that computes compound interest in many places could use one function, CalcCompInt, that takes the rate, time and principal, works out the interest and shows it.

Built-in functions come with Python; we have used print() and input(). They make programming faster. To use one, know:

  • its name;
  • its arguments: the values passed to it inside the brackets (a function may take none, one or several);
  • its return value: the result it passes back to where it was called. Some functions return nothing.

Reading a line of code: in num = int(input("Enter the first number")), two functions work together. input() takes the prompt as its argument and returns the typed text as a string; int() takes that string as its argument and returns an integer. In print("the square of", num, "is", square), print() takes four arguments.

Common built-in functions (Table 3.8):

  • Input/Output: input(), print().
  • Data type conversion: bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple().
  • Mathematical: abs(), divmod(), max(), min(), pow(), sum().
  • Other: __import__(), len(), range(), type().

A module is a Python file in which several functions are grouped. Its functions are used after importing the module with the import command.

Example (new): in print(len('Mumbai')), len() is called first with the argument 'Mumbai' and returns 6; that 6 becomes print()'s argument, so 6 is displayed. Similarly, abs(-8) returns 8 and pow(2, 5) returns 32.

Name, arguments, return value.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.