Home Education Python Examples and Functions-beginners

Python Examples and Functions-beginners

So far, we have learned only the fundamental features of Python variables, expression, control structures, input, etc. Now, we are going to learn the functions.

Hey! you can run Python Programs without installing the software. Visit OnlineGDB.

Before moving forward, Do you take Python Basics course.

Index

  1. What are the Functions?
  2. Examples
  3. Python Dictionary
  4. Conclusion
  5. QnA

What are the Functions in Python Programming?

A function is a block of organized, reusable code that is used to perform a single task or multiple tasks.

Syntax:

def function_name([parameter list]):
statement(s)

Ex.

def My_Func():
print(“Hello World”)
My_Func()

So, in the above program, in the first line, we declared the function with the name My_Func using the keyword def(define).

On the next line, which is inside that function, we print/display the Hello World message.

On the last line, we called the function, which is in the main function. 

python functions

Call by Reference

Call by reference means to call the function with some parameters or passing value from the main function to this function.

Syntax:

def function_name(parameters):

Statements

function_name( parameters )

Ex.

def swap(a,b):
  return b, a
a=1
b=2
print(a,b)
print(“\nAfter the swap\n”)
a,b=swap(a,b)
print(a , b)

In the above program, we swapped the variable’s data easily using a call by reference/ parameterized function.

In the main function, we assigned a as 1 and b as 2 and printed that.

You can see on the second last line, we used a,b = swap(a,b).

Here we passed the variables a & b to swap function and after getting returned values, it will store in a & b respectively.

You can see the function has two parameters def swap(a,b): which shows that we passed two variables and we return the variable without touching them but exchanging the positions because when the variable returns to the main function, then the first variable (b) will be stored in a and the second variable from function i.e. a will get stored in b.

Recursion

A method which calls itself is called recursion.

python recursion

To understand it fully let’s take an example of Factorial.

# Factorial using recursion
def factorial(n):
   if n == 1:
       return n
   else:
       return n*factorial(n-1)
n=5
factorial(n)
print("The factorial is: “,n)

In recursion the most important step is to write a terminating condition, otherwise, the recursion will be infinite.

When we call the factorial function with n, then you can see the first line after the function is our terminating condition.

When the n becomes 1 then it is going to terminate the function and pass the value to the main function.

Let’s see what happens to the recursive statement i.e. return n*factorial(n-1)

It is going to call the factorial function again and again until the condition is met i.e. n=1.

The factorial function will be executed like this:

return n*factorial(n-1)
= 5*factorial(4)
= 5*4*factorial(3)
= 5*4*3*factorial(2)
= 5*4*3*2*factorial(1)
= 5*4*3*2*1*factorial(0)
= 5*4*3*2*1*1
= 5*4*3*2*1
= 5*4*3*2
= 5*4*6
= 5*24
= 120

So, this is how we will get our answer.

Advantages of Recursion

  1. It makes the program look clean.
  2. A complex task can be broken down into subparts.
  3. Easy to do in the comparison of nested loops.

Disadvantages of Recursion

  1. Not easy to understand.
  2. It takes more memory and time.
  3. Hard to debug.

Python Examples

python examples
  1. Find Square Root
n = 12
n = n ** 0.5
print(“The square root is:”,n)
  1. Check for Prime Number
n =5
       for i in range(2,n):
       if (n % i) == 0:
           print(n,"is not a prime number”)
break
   else:
       print(n,"is a prime number")
  1. Fibonacci Numbers:
def fibonacci(n): 
a = 0
b = 1
if n < 0: 
print("Incorrect input") 
elif n == 0: 
return a 
elif n == 1: 
return b 
else: 
for i in range(2,n): 
             c = a + b 
             a = b 
            b = c 
return b 
print(fibonacci(10)) 
  1. Find Factors
def factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
            print(i)
num = 320
factors(n)
  1. Find the area of a circle
r=4
area=3.14*r*r
print(“The area of the circle is :”,area)

Python Dictionary

A dictionary is a mutable, associative data structure of variable length. In other words, a dictionary is an unordered collection of key/value pairs.

python dictionary methods

The dictionary elements will look like this:

[ key : value ]

Ex.

‘brand’: ‘Ford’

  1. Creating Dictionary

Each key is separated from its value by a colon(:), the items are separated by commas and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Ex.

dict = {‘Name’ : ‘Neeraj’, ‘Age’ : 4} 
  1. Accessing Values in Dictionary

To access, we have to use the square brackets.

Ex.

print(“Name: ”, dict[‘Name’])
  1. Updating Dictionary

Python dictionary is mutable, so we can update it by adding a new entry.

Ex.

dict = {‘Name’ : ‘Neeraj’, ‘Age’ : 4} 
dict[‘Age’]=3;  #we just update it.
  1. Delete Dictionary Elements

To delete, we can use the del keyword.

Ex.

del dict[‘Age’]  #This gonna remove the entry of the key ‘Age’

Or

Del dict  #This going to delete the dictionary named ‘dict’

Built-in Dictionary Functions and Methods

  1. Dictionary len() Method

Syntax:

len(dict)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(len(My_dict))
  1. Dictionary str() Method

Syntax:

str(dict)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(str(My_dict))
  1. Dictionary type() Method

Syntax:

type(dict)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(type(My_dict))
  1. Dictionary clear() Method

Syntax:

dict.clear()

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict)
My_dict.clear()
  1. Dictionary copy() Method

Syntax:

Method dict.copy()

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict)
dict2=My_dict.copy()
  1. Dictionary get() Method

Syntax:

dict.get(key, default = None)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict.get(‘Class’))
  1. Dictionary items() Method

Syntax:

dict.items()

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict.items(‘Class’))
  1. Dictionary keys() Method

Syntax:

dict.keys()

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict.keys(‘Class’))
  1. Dictionary setdefault() Method

Syntax:

method dict.setdefault(key, default=None)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(My_dict.setdefault(‘Class’,None))
  1. Dictionary update() Method

Syntax:

dict.update(dict2)

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
My_dict2={‘Name’: ‘ Arjun’, ‘Age’:15, ‘Class’:9)
My_dict.update(My_dict2)
print(My_dict2)
  1. Dictionary values() Method

Syntax:

dict.values()

Ex.

My_dict={‘Name’: ‘ Neeraj’, ‘Age’:12, ‘Class’:8)
print(list(My_dict.value()))

How to use dictionary methods and functions?

Syntax:

dict_name. methods_name( key )

Dictionary Methods

MethodDescription
dict.clear()Removes all elements
dict.copy()Return duplicate
dict.get()Returns values
dict.items()Returns list.
dict.setdefault()It will set default if the key is not present.
dict.update()Updates value
dict.values()Returns all the values
dict.keys()Returns all the list of keys

Conclusion

There’s a long journey to go, but with daily learning and practicing your skills you can easily achieve your goal in just 3 months from now, so all the best.

Btw, it’s never late to start. So, start today itself, we cover you basics(Beginner’s course), hence, you are ready to take the Intermediate course.

All the best.

Do check our SQL basics course. We provided the basics to cover the Beginner level and also, the SQL is that language that you need to implement on the server to perform the online tasks for an Application. Why wait, let’s start. Learn SQL programming for Free-Beginner’s

FAQ

Q1. Is Python programming used for analysis?

Yes.

Q2. What are Tuples in Python?

A tuple is an immutable sequence of Python objects.

Q3. Python real time examples.

Desktop GUI Applications, Science and Numeric Software Development, Database Access, Games and 3D Graphics, Web Apps.

Q4. Do I need to join a paid course for Python?

It’s totally up to you.

Q5. Do I use Python for Android apps?

No.

RELATED ARTICLES

How an Emergency Line of Credit Can Aid Your Financial Situation?

Whenever there is a financial emergency, people want quick funds to deal with the emergency. In order to cater to this, banks...

Things That Are Harming Your Credit Score

A credit score is a vital parameter to getting the best loan offers. A score of 630 or above is good enough...

The 10 Most Common Mistakes Made When Applying for a Business Loan

A business loan can be extremely useful for your business venture. Whether you are looking to obtain a working capital loan or...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

How an Emergency Line of Credit Can Aid Your Financial Situation?

Whenever there is a financial emergency, people want quick funds to deal with the emergency. In order to cater to this, banks...

Things That Are Harming Your Credit Score

A credit score is a vital parameter to getting the best loan offers. A score of 630 or above is good enough...

The 10 Most Common Mistakes Made When Applying for a Business Loan

A business loan can be extremely useful for your business venture. Whether you are looking to obtain a working capital loan or...

Top Trading Techniques & Strategies Traders Should Know

There are a number of effective trading tactics you will come across when trading on the financial markets...

Recent Comments