1. 程式人生 > >How To Make My Python Code Shorter With Function.

How To Make My Python Code Shorter With Function.

Python function is very important in structuring your code in a program.

When it comes to writing a simple program, you can do it without functions, but when your program becomes long and would need maintenance from time to time, I recommend you design your code into chunks (functions).

Here’s the deal:

When you learn about Python function, you’ll never repeat a code more than once in your program again.

Hence you make your code shorter and elegant to read.

Isn’t that cool?

But you may be wondering:

What Exactly is a Function in Python?

A function is a block of code that is organized in such a way that you can re-use it to perform a particular action in a program.

Python has 68 built-in functions and examples are: print(), len(), max(), min(), sum(), eval(), input(), next(), help() etc.

You now know what a function is in Python.

2 Top Reasons That Will Make You Change The Way You Code – Why You Should Use Function in Your Program Now

Many Python beginners will write long chunks of code to solve a simple problem.

That can make your code boring to read, but making your code shorter is one of the fun things to do with Python believe me.

I will just outline two major reasons that will make you use functions in your program, hence changing the way you code.

  1. Functions make your code shorter and easier to read and hence more than one programmer can work on the same project.
  2. With function, you can quickly debug your program.

Use these 8 Quick Steps to Define a Function in Python.

  1. Begin your block of code with the keyword def
  2. In the same line, type in your function name and include parentheses ()
  3. Any argument is added within the parentheses
  4. At the end of the parentheses include a colon (:)
  5. Press enter
  6. You can describe your function name in quotes (“ “)
  7. Press enter and write your program
  8. When you finish writing your program, include the return keyword
How to define a function in Python

8 quick steps to define a function

Below is a quick video guide on How to define a Function in Python.

I will quickly talk about step 6 as it’s a good habit to give a description of what your function does.

A Cool Way to Describe Your Function Without The Hash(#) Symbol

In Python to describe your code, you use the hash symbol(#). Python ignores comment as it is for the humans to read.

To describe your function in Python, you use a docstring which is the sixth step in defining a function.

To demonstrate this, I will write a function to calculate a quadratic mathematical equation.

I will also show you how to access a docstring of a function.

The program is saved as quadratic_Calculator.py( for those that will download the source code of this Python programming tutorial).

quadratic_Calculator.py Python
12345678 importmathdefquad_calculate(a,b,c):"Calculates a quadratic mathematical equation"x=(-b+math.sqrt(b**2-4*a*c))/(2*a*c)y=(-b-math.sqrt(b**2-4*a*c))/(2*a*c)print("The value of x can be",x,"or",y)quad_calculate(2,2,-1)print("Description of quad_calculate:",quad_calculate.__doc__)

In the last line of code in the code snippet above, the docstring of the function name (quad_calculate) is accessed by quad_calculate.__doc__

NOTE:

__doc__ is a function attribute and it has two leading and two trailing underscores.

This block of code to solve a quadratic equation is executed when the function(quad_calculate) is called. You will learn how to call a Python user defined function later.

But first:

Good Practices When Defining a Function in Python

When defining a function in Python, never do the following:

Starting your function name with something that is not a letter except an underscore

Your function name can begin with an underscore(_) or a letter(either upper case or lower case) first then after that you can include digits.

The only acceptable symbol in your Python function name is an underscore(_). If you don’t follow this rule, Python will raise an error(SyntaxError).

Including Spacing in Your Function Name

You can’t include a space in your function name rather Python accepts an underscore(_).

Using Python’s Keywords As Your Function Name

In Python, keywords are known as reserved words and they cannot be used as a function name.

  • False
  • None
  • True
  • and
  • as
  • assert
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • try
  • while
  • with
  • yield

Want to know the best part?

You don’t need to memorize these Python keywords.

Here is a short video tutorial on how to get all the keywords in Python 3.

Just run the following code snippet in Python interactive shell to get all the keywords in Python 3.

Python keywords Python
1234 >>>importkeyword>>>keyword.kwlist['False','None','True','and','as','assert','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']>>>

To determine if your function name is a keyword or not:

Type the following code snippet in Python’s interactive shell.

123456 >>>import keyword>>>keyword.iskeyword("raise")True>>>keyword.iskeyword("printstr")False>>>

Observe:

A True value is returned for the word “raise” because it is a keyword in Python.

A False value is returned for the word “printstr” because it is not a keyword in Python. Hence we can use it for a function name

Example of a Function in Python.

Now:

Let us write a Hello World program using function by following the 8 quick steps to define a function.

Type the following code snippet into Python’s interactive shell.

hello world program with function Python
12345678 >>>defHelloworld():"This block of code prints out Hello World"print("Hello World")return>>>Helloworld()Hello World>>>

Note: The program will still run fine without the return statement. I will explain the return statement later.

Let us see how we can add arguments to our function.

Project 1:

Write a function to print a string.

Type the following code snippet into Python’s interactive shell.

user-define print function
1234567 >>>def printstr(string):print(string)>>>printstr("My name is Godson")My name isGodson>>>

This program takes one argument which is a string and prints it.

Let us do something that’s a bit tougher.

Python
12345678910111213 >>>defstudent_info():name=input("Enter Student name:")dept=input("Enter Student dept:")level=input("Enter Student level:")print(name,"is a ",level," level student of the department of",dept)return>>>student_info()Enter Student name:GodsonEnter Student dept:Chemical EngineeringEnter Student level:400Godson isa400level student of the department of Chemical Engineering>>>

How to call a function in Python (3 Simple Hacks You Need to Know)

Here is something funny about function( a joke)

Funny Python joke on function.

Funny Python joke on function.

Alright, let’s be serious now.

You have learned how to define a function by giving it a name and including argument(s) within the parentheses.

A function can be called directly or from another function.

The following code snippet illustrates a function calling another function.

The program is saved as square_root.py( for those that will download the source code of this Python programming tutorial).

square_root.py Python
123456789 importmathdefmain():user_number=int(input("Enter an Integer number:"))square_root(user_number)defsquare_root(number):print("The square root of the number is",math.sqrt(number))main()

The above program is to find the square root of a number. We have two functions(main and square_root). The main function calls the square_root function.

Here are the arguments you can use to call a function.

  1. Required argument
  2. Keyword argument
  3. Default argument

Required argument

In required argument, the arguments are called according to the position as defined.

To understand you have to type the following code snippet into Python interactive shell.

Python
1234567 >>>defstudent_info(name,dept,level):print(name," is a",level," level student of the Department of",dept)>>>student_info("Godson","Chemical Engineering",400)Godson  isa400level student of the Department of Chemical Engineering>>>

Did you observe anything?

The required arguments are name, dept and level and when you call the function student_info you have to provide the arguments in the order of the name of the student, the dept and the level.

Keyword argument

In keyword argument, the order in which you put the arguments to call the function does not matter. All you have to do is assign the value to the argument when you call the function.

You will better understand this if you type the following code snippet into Python interactive shell.

Python
1234567 >>>defstudent_info(name,dept,level):print(name," is a",level," level student of the department of",dept)>>>student_info(dept="Chemical Engineering",level=400,name="Godson")Godson  isa400level student of the department of Chemical Engineering>>>

In the above code snippet, Chemical Engineering is assigned to dept, 400 is assigned to level and Godson is assigned to name.

I hope you observed that the order of the argument in the function definition is different in the function call.

Default argument

In default argument, a default value is assigned to an argument while defining the function.

Let say you what to write a function to deduct the tax of your income and return your net income.

Your tax is 10% of your income.

Type the following code snippet into Python’s interactive shell.

Income calculator program
12345678 >>>def Income_calculator(income,tax=0.1):net_income=income-(income*tax)print("My net income is",net_income)>>>Income_calculator(200)My net income is180.0>>>

Python Function with While loop

Let us try Python function with a condition statement(while loop) and write a cool program.

Project 2

We will write a function to print out a range of number from lower bound to upper bound with a step the user provides.

Type the following code snippet into Python’s interactive shell.

Python
123456789 >>>defprintRange(lower,upper,step):whilelower<=upper:print(lower,end=",")lower+=step>>>printRange(2,15,2)2,4,6,8,10,12,14,>>>

Our function(printRange) accepts three arguments(lower, upper and step).

The while loop runs only when the lower bound is less than or equal to the upper bound.

In Python <= means less than or equal to. It is a relational operator.

end=”,” ensures we print our range in one line with the numbers separated by commas(,)

When the function is executed the lower bound is incremented by the step size the user provided.

Note: I didn’t use the keyword return.  I will explain why I didn’t add it later.

Global and Local Variable

A local variable is a variable that can only be accessed by the function that contains the variable while a global variable is a variable that can be accessed by all the functions in your program.

Global Variable

I will illustrate a global variable in the following code snippet.

The program is saved as stats.py( for those that will download the source code of this Python programming tutorial).

stats.py
123456789