Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 4    ❮    Lesson List    ❮    Top Page

❯  4.1  Functions    

4.2 Lambda Functions    

4.3 Handling Exceptions    

4.4 Intro to RegEx    

4.5 RegEx for Data Cleaning

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   9m 2s
☷  Interactive readings   5m
✑  Practice 4.1 (G Colab)   20m

Making a Function

A function is a block of code that only runs when it is called. 

In Python, a function is defined using the def keyword. Similar to for and if, the indented lines after that will be part of that function.

To call that function, use the function name followed by parenthesis ().

Adding an Argument to a Function

Information can be passed into functions as arguments.

Arguments are added after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Adding Multiple Arguments to a Function

In a function, you can add as many arguments as you want, just separate them with a comma.

Using Default Parameter Value

Some data or parameters might be incomplete. Adding a default value to a function can help with this. If we call the function without argument, it will use the default value:

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary, etc.), and it will be treated as the same data type inside the function.

WRITE BETTER CODE
Writing Functions Neatly

  • Don't use spaces around the = sign when used to indicate a keyword argument.

  • When a function has many arguments, add an extra indentation to distinguish arguments from the rest.

  • Functions should be in lower case (same format as variables).

LEARN FROM ERRORS
SyntaxError when Non-default Argument follows Default Argument

The argument with default value has to be written last. In addition to that, when calling a function, the number of argument has to be at least the same as the non-default values. 

You can fix the errors by moving mark before grade="?" and add an extra argument in print_stats("Andy"). You can also just add a default value to mark.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse