0% found this document useful (0 votes)
37 views40 pages

Python Fundamentals

Uploaded by

Swapnil Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
37 views40 pages

Python Fundamentals

Uploaded by

Swapnil Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

Unit :2 Python Fundamentals

Python is a General Purpose object-oriented programming language, which means that it can
model real-world entities. It is also dynamically-typed because it carries out type-checking at
runtime. It is a dynamic ,high level, free open source and interpreted programming language.
It supports object-oriented programming as well as procedural programming.
Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation ,and it has fewer syntactical constructions than other languages.
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991. There are two major Python versions-Python-2 and Python-3.
Python is used for :
• Web development (server side)
• Software development
• Mathematics
• System Scripting
• Graphical user interface

There are some organizations that are using python at a higher level:
• Microsoft
• Google
• Yahoo
• YouTube

1 IQRA BCA College


Unit :2 Python Fundamentals

• Mozilla
• DropBox
• Cisco
• Spotify
• Facebook
• OpenStack

Advantages of Python
• It is open-source and readily available to use.
• It is easy to learn and explore.
• Third-party modules can be easily integrated.
• It is high level and object-oriented programming language
• It is interactive and portable.
• Applications can be run on any platform.
• It is a dynamically typed language.
• It has great online support and community forums.
• It has a user-friendly data structure.
• It has extensive support libraries.
• It is interpreted language.
• Python provides database connectivity.
• It improves programmer productivity.

• Python works on different platforms(Windows,Mac,Linux ,Raspberry Pi,etc).


• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system that allows developers to write programs with
fewer

There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn
the language as compared to other languages like C, C#, Javascript, Java,
etc. It is very easy to code in python language and anybody can learn python
basics in a few hours or days. It is also a developer-friendly language.

2 IQRA BCA College


Unit :2 Python Fundamentals

2. Free and Open Source:


Python language is freely available at the official website and you can
download it from the given download link below click on the Download
Python keyword.

Since it is open-source, this means that source code is also available to the
public. So you can download it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, objects
encapsulation, etc.

4. GUI Programming Support:


Graphical User interfaces can be made using a module such as PyQt5,
PyQt4, wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.

5. High-Level Language:
Python is a high-level language. When we write programs in python, we do
not need to remember the system architecture, nor do we need to manage
the memory.

6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C
or C++ language and also we can compile that code in C/C++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have
python code for windows and if we want to run this code on other platforms
such as Linux, Unix, and Mac then we do not need to change it, we can run
this code on any platform.

8. Python is Integrated language:


Python is also an integrated language because we can easily integrated
python with other languages like c, c++, etc.

9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by
line at a time. Like other languages C, C++, Java, etc. there is no need to
compile python code this makes it easier to debug our code. The source
code of python is converted into an immediate form called byte code.
10. Large Standard Library
Python has a large standard library which provides a rich set of module and
functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions,
unit-testing, web browsers, etc.
3 IQRA BCA College
Unit :2 Python Fundamentals

11. Dynamically Typed Language:


Python is a dynamically-typed language. That means the type (for example-
int, double, long, etc.) for a variable is decided at run time not in advance
because of this feature we don’t need to specify the type of variable.

Interpreted language?
When you write a program in C/C++, you must compile it. Compilation
involves translating your human understandable code to machine
understandable code, or Machine Code.
Machine code is the base level form of instructions that can be directly
executed by the CPU. Upon successful compilation, your code generates an
executable file.
Executing this file runs the operations in your code step by step.

For the most part, Python is an interpreted language and not a compiled
once, although compilation is a step. Python code, written in .py file is first
compiled to what is called bytecode which is stored with a .pyc or. pyo
format.

Instead of translating source code to machine code like C++, Python code it
translated to bytecode. This bytecode is a low-level set of instructions that
can be executed by an interpreter. In most PCs, Python interpreter is
installed at /user/local/bin/python3.8. Instead of executing the instructions on
CPU, bytecode instructions are executed on a Virtual Machine.

Why Python is Interpreted?


One popular advantage of interpreted languages is that they are platform-
independent. As long as the Python bytecode and the Virtual Machine have
the same version, Python bytecode can be executed on any platform
(Windows, MacOS, etc).

Dynamic typing is another advantage. In static-typed languages like C++,


you have to declare the variable type and any discrepancy like adding a
string and an integer is checked during compile time. In strongly typed
languages like Python, it is the job of the interpreter to check the validity of
the variable types and operations performed.

4 IQRA BCA College


Unit :2 Python Fundamentals

Disadvantages of Interpreted languages:


Dynamic typing provides a lot of freedom, but simultaneously it makes our
code risky and sometimes difficult to debug.
Python is often accused of being ‘slow’. Now while the term is relative and
argued a lot, the reason for being slow is because the interpreter has to do
extra work to have the bytecode instruction translated into a form that can be
executed on the machine.

If you can talk in your native language to someone, that would generally
work faster than having an interpreter having to translate your language into
some other language for the listener to understand.

Downloading python
You can download from official website of python from python.org. click on the
download tab to get releases or install thonny.

Python program
Python provides two ways to run a program:
• Using Interactive interpreter prompt
• Using a script file.

Interactive interpreter prompt:

Python provides us the feature to execute the python statement one by one at the
interactive prompt. It is preferable in the case where are concerned about the
output of each line of our python program.
To open the interactive mode, open the terminal (or command prompt) and type
python
It will open the following prompt where we can execute the python statement and
check their impact on the console.
The standard prompt for the interactive mode is >>>, so as soon as you see
these characters, you’ll know you are in.

Now, you can write and run Python code as you wish, with the only
drawback being that when you close the session, your code will be gone.

When you work interactively, every expression and statement you type in is
evaluated and executed immediately:

>>>
>>> print('Hello World!')
Hello World!
>>> 2 + 5

5 IQRA BCA College


Unit :2 Python Fundamentals

7
>>> print('Welcome to Real Python!')
Welcome to Real Python!
Using script file:
We need to write code into a file which can be executed later. For this purpose, open an editor like
notepad, create a file named prog1.py (python uses .py extension) and write the following code in it.

To run the script file, you have to set the path variable.

To run this file named as prog1.py, we need to run the following command on the terminal.

Python Comments:
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the
#, up to the end of the physical line, are part of the comment and the Python interpreter ignores
them.

Example,

# This is a comment

Note: Python does not have a syntax for multiline string. Since Python will ignore string literals that
are not assigned to a variable, you can add a multiline string(Triple quotes) in your comment inside
it:

Example:

“””

This is a comment

Written in

More than just one line

“””

Lines and Indentation:


• Python does not use braces ({}) to indicate blocks of code for class and function definitions
or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all the statements within the block
must be indented the same amount.

Example:

If True:

Print(“True”)

else:

print(“False”)

6 IQRA BCA College


Unit :2 Python Fundamentals

In Python all the continuous lines indented with same number of spaces would form a block.
The following example has various statement blocks −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Python allows for user input.That means we are able to ask the user for
input.The method is a bit different in Python 3 than Python 2.

Python 3 uses the input() method.

Python 2 uses the raw_input() method.

The following example asks for the username, and when you entered the
username, it gets printed on the screen:

Python 3
username = input("Enter username:")
print("Username is: " + username)

input ( ) : This function first takes the input from the user and then evaluates
the expression, which means Python automatically identifies whether user
entered a string or a number or list. If the input provided is not correct then
either syntax error or exception is raised by python.

How the input function works in Python :


• When input() function executes program flow will be stopped until the
user has given an input.
• The text or message display on the output screen to ask a user to enter
input value is optional i.e. the prompt, will be printed on the screen is
optional.
• Whatever you enter as input, input function convert it into a string. if you
enter an integer value still input() function convert it into a string. You
need to explicitly convert it into an integer in your code using typecasting.

7 IQRA BCA College


Unit :2 Python Fundamentals

Variables hold values. In Python, variables do not require forward declaration


- all you need to do is provide a variable name and assign it some value.

Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or
characters in these variables.

Example:
x=12

y=”programming”

print(x)
print(y)

Example:

pi=3

radius=11
area=pi*(radius**2)

radius =14

It first binds the name pi and radius to different objects of type int. it then
binds the name area to a third object of type int.

pi 3

pi
radius 363
3

radius 11 14
area

363
area
In Python variable is just a name ,nothing more.

8 IQRA BCA College


Unit :2 Python Fundamentals

Python breaks each logical line into a sequence of elementary lexical


components known as tokens. Each token corresponds to a substring of the
logical line. The normal token types
are identifiers, keywords, operators, delimiters, and literals, as covered in
the following sections. We may freely use whitespace between tokens to
separate them. Some whitespace separation is necessary between logically
adjacent identifiers or keywords; otherwise, Python would parse them as a
single, longer identifier. For example, printx is a single identifier; to write the
keyword print followed by the identifier x, you need to insert some
whitespace (e.g., print x).

There are following tokens in Python:

• Identifiers.
• Keywords
• Literals
• Operators

A Python identifier is a name used to identify a variable, function, class,


module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to
9).

Python does not allow punctuation characters such as @, $, and % within


identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −

• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strongly private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.

9 IQRA BCA College


Unit :2 Python Fundamentals

Python has 30 keywords, which are identifiers that Python reserves for special
syntactic uses. Keywords contain lowercase letters only. You cannot use keywords
as regular identifiers.They are used to define the syntax and structure of the Python
language.

• In Python, keywords are case sensitive.There are 33 keywords in Python 3.7.


This number can vary slightly over the course of time.

• All the keywords except True, False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.
False await else import pass

None break except in raise

True class finally is return

And continue for lambda try

As def from nonlocal while

assert del global not with

async elif if or yield

Python uses nonalphanumeric characters and character combinations as operators.


Python recognizes the following operators, which are covered in detail
in Expressions and Operators:

10 IQRA BCA College


Unit :2 Python Fundamentals

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically
typed language; hence we do not need to define the type of the variable while
declaring it. The interpreter implicitly binds the value with its type.

1. a = 5

The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python
provides us the type() function, which returns the type of the variable passed.

Consider the following example to define the values of different data types and
checking its type.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

❖ Standard data types


A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.

11 IQRA BCA College


Unit :2 Python Fundamentals

Python provides various standard data types that define the storage method on each
of them. The data types defined in Python are given below.

1. Numbers

2. Sequence Type

3. Boolean

4. Set

5. Dictionary

In this section of the tutorial, we will give a brief introduction of the above data-
types. We will discuss each one of them in detail later in this tutorial.

Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type. Python provides the type() function to know the data-
type of the variable. Similarly, the isinstance() function is used to check an object
belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For


example;

a=5
print("The type of a", type(a))

12 IQRA BCA College


Unit :2 Python Fundamentals

b = 40.5
print("The type of b", type(b))

c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Data types are the classification or categorization of data items. Python supports the
following built-in data types.

❖ Scalar Types
• int: Positive or negative whole numbers (without a fractional part) e.g. -10,
10, 456, 4654654. Python has no restriction on the length of an integer.

1. float: Any real number with a floating-point representation in which a


fractional component is denoted by a decimal symbol or scientific notation It
is accurate upto 15 decimal points.e.g. 1.23, 3.4556789e2.

• complex: A number with a real and imaginary component represented as x +


2y.
• bool: Data with one of two built-in values True or False. Notice that 'T' and 'F'
are capital. true and false are not valid booleans and Python will throw an
error for them.
• None: The None represents the null object in Python. A None is returned by
functions that don't explicitly return a value.

❖ Sequence Type

• String: The string can be defined as the sequence of characters


represented in the quotation marks. In Python, we can use single, double, or
triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the string.

13 IQRA BCA College


Unit :2 Python Fundamentals

In the case of string handling, the operator + is used to concatenate two strings as
the operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2


returns 'Python Python'.

The following example illustrates the string in Python.

Example - 1

str = "string using double quotes"


print(str)
s = '''A multiline
string'''
print(s)

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

• List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed
within square brackets [].

14 IQRA BCA College


Unit :2 Python Fundamentals

We can use slice [:] operators to access the data of the list. The concatenation
operator (+) and repetition operator (*) works with the list in the same way as they
were working with the strings.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


Print (list1 + list1)

# List repetation using * operator


print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

• Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are separated
with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the
items of a tuple.

Let's see a simple example of the tuple.

15 IQRA BCA College


Unit :2 Python Fundamentals

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

• Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative
array or a hash table where each key stores a specific value. Key can hold any
primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the
curly braces {}.

Consider the following example.

16 IQRA BCA College


Unit :2 Python Fundamentals

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print (d.keys())
print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

• Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can
be represented by any non-zero value or 'T' whereas false can be represented by the
0 or 'F'. Consider the following example.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

• Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element. The set is created by
using a built-in function set(), or a sequence of elements is passed in the curly

17 IQRA BCA College


Unit :2 Python Fundamentals

braces and separated by the comma. It can contain various types of values.
Consider the following example.

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}


#Printing Set value
print(set2)

# Adding element to the set

set2.add(10)
print(set2)

Removing element from the set


set2.remove(2)
print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

• What is a function in Python?


In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters):

"""docstring"""

18 IQRA BCA College


Unit :2 Python Fundamentals

statement(s)

Above shown is a function definition that consists of the following components.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They
are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

How to call a function in python?

Once we have defined a function, we can call it from another function, program or

even the Python prompt. To call a function we simply type the function name with

appropriate parameters.

>>> greet('Paul')
Hello, Paul. Good morning!

explain what a function does.

def greet(name):

19 IQRA BCA College


Unit :2 Python Fundamentals

"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Paul')

Docstrings

The first string after the function header is called the docstring and is short
for documentation string. It is briefly used to explain what a function does.

Although optional, documentation is a good programming practice. Unless


you can remember what you had for dinner last week, always document
your code.

In the above example, we have a docstring immediately below the function


header. We generally use triple quotes so that docstring can extend up to
multiple lines. This string is available to us as the __doc__ attribute of the
function.
For example:
Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)

This function greets to


the person passed in as
a parameter

20 IQRA BCA College


Unit :2 Python Fundamentals

To learn more about docstrings in Python, visit Python Docstrings.

The return statement

The return statement is used to exit a function and go back to the place
from where it was called.
Syntax of return

return [expression_list]

This statement can contain an expression that gets evaluated and the
value is returned. If there is no expression in the statement or
the return statement itself is not present inside a function, then the function
will return the None object.
For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value since greet() directly prints the name and
no return statement is used.

Example of return

def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

if num >= 0:

21 IQRA BCA College


Unit :2 Python Fundamentals

return num
else:
return -num

print(absolute_value(2))

print(absolute_value(-4))

Output

2
4

How Function works in Python?

Working of functions in Python

Default Parameter Value

The following example shows how to use a default parameter value.

22 IQRA BCA College


Unit :2 Python Fundamentals

We can provide a default value to an argument by using the assignment


operator (=).If we call the function without argument, it uses the default
value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is


recognized. Parameters and variables defined inside a function are not
visible from outside the function. Hence, they have a local scope.

The lifetime of a variable is the period throughout which the variable exits in
the memory. The lifetime of variables inside a function is as long as the
function executes.

They are destroyed once we return from the function. Hence, a function
does not remember the value of a variable from its previous calls.

Here is an example to illustrate the scope of a variable inside a function.

def my_func():

23 IQRA BCA College


Unit :2 Python Fundamentals

x = 10
print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

Output :

Value inside function: 10


Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the
function my_func() changed the value of x to 10, it did not affect the value
outside the function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have the same names, they
are two different variables with different scopes.
On the other hand, variables outside of the function are visible from inside.
They have a global scope.

We can read these values from inside the function but cannot change
(write) them. In order to modify the value of variables outside the function,
they must be declared as global variables using the keyword global .

24 IQRA BCA College


Unit :2 Python Fundamentals

Types of Functions

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

1. Python Built-in Functions


The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always
present for use. These functions are known as Built-in Functions. There are several
built-in functions in Python which are listed below:

abs() Function
The python abs() function is used to return the absolute value of a number. It takes
only one argument, a number whose absolute value is to be returned. The argument
can be an integer and floating-point number. If the argument is a complex number,
then, abs() returns its magnitude.

Python abs() Function Example

# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))

Output:

Absolute value of -20 is: 20


Absolute value of -20.83 is: 20.83

Python all() Function


The python all() function accepts an iterable object (such as list, dictionary, etc.). It
returns true if all items in passed iterable are true. Otherwise, it returns False. If the
iterable object is empty, the all() function returns True.

25 IQRA BCA College


Unit :2 Python Fundamentals

Python all() Function Example

ADVERTISEMENT

# all values true


k = [1, 3, 4, 6]
print(all(k))

# all values false


k = [0, False]
print(all(k))

# one false value


k = [1, 3, 7, 0]
print(all(k))

# one true value


k = [0, False, 5]
print(all(k))

# empty iterable
k = []
print(all(k))

Output:

True
False
False
False
True

Python bin() Function


The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.

Python bin() Function Example

x = 10
y = bin(x)
print (y)

26 IQRA BCA College


Unit :2 Python Fundamentals

Output:

0b1010

Python bool()
The python bool() converts a value to boolean(True or False) using the standard
truth testing procedure.

Python bool() Example

test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))

Output:

ADVERTISEMENT
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True

Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an
immutable version of the bytearray() function.

It can create empty bytes object of the specified size.

Python bytes() Example

string = "Hello World."

27 IQRA BCA College


Unit :2 Python Fundamentals

array = bytes(string, 'utf-8')


print(array)

Output:

b ' Hello World.'

Python callable() Function


A python callable() function in Python is something that can be called. This built-in
function checks and returns true if the object passed appears to be callable,
otherwise false.

Python callable() Function Example

x=8
print(callable(x))

Output:

False

Python compile() Function


The python compile() function takes source code as input and returns a code object
which can later be executed by exec() function.

ADVERTISEMENT

Python compile() Function Example

# compile string source to code


code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)

Output:

<class 'code'>
sum = 15

28 IQRA BCA College


Unit :2 Python Fundamentals

Python exec() Function


The python exec() function is used for the dynamic execution of Python program
which can either be a string or object code and it accepts large blocks of code, unlike
the eval() function which only accepts a single expression.

Python exec() Function Example

x=8
exec('print(x==8)')
exec('print(x+4)')

Output:

True
12

Python sum() Function


As the name says, python sum() function is used to get the sum of numbers of an
iterable, i.e., list.

Python sum() Function Example

s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)


print(s)

Output:

ADVERTISEMENT
7
17

Python any() Function


The python any() function returns true if any item in an iterable is true. Otherwise,
it returns False.

Python any() Function Example

l = [4, 3, 2, 0]

29 IQRA BCA College


Unit :2 Python Fundamentals

print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

Output:

True
False
True
False

2.What are user-defined functions in Python?

Functions that we define ourselves to do certain specific task are referred


as user-defined functions. The way in which we define and call functions in
Python are already discussed.
Functions that readily come with Python are called built-in functions. If we
use functions written by others in the form of library, it can be termed as
library functions.

All the other functions that we write on our own fall under user-defined
functions. So, our user-defined function could be a library function to
someone else.

30 IQRA BCA College


Unit :2 Python Fundamentals

Advantages of user-defined functions


1. User-defined functions help to decompose a large program into small
segments which makes program easy to understand, maintain and debug.

2. If repeated code occurs in a program. Function can be used to include


those codes and execute when needed by calling that function.

3. Programmers working on large project can divide the workload by making


different functions.

Example of a user-defined function

# Program to illustrate
# the use of user-defined functions

def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Arguments
Information can be passed into functions as arguments.

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

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")

31 IQRA BCA College


Unit :2 Python Fundamentals

my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

Type conversion

Python defines type conversion functions to directly convert one data type to
another which is useful in day to day and competitive programming. This
article is aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:

1.Implicit Type Conversion

2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user
involvement. To get a more clear view of the topic see the below examples.
Example:

• Python3

32 IQRA BCA College


Unit :2 Python Fundamentals

x = 10

print("x is of type:",type(x))

y = 10.6

print("y is of type:",type(y))

x =x +y

print(x)

print("x is of type:",type(x))

Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>
As we can see the type od ‘x’ got automatically changed to the “float” type
from the “integer” type. this is a simple case of Implicit type conversion in
python.

Explicit Type Conversion


In Explicit Type Conversion in Python, the data type is manually changed by
the user as per their requirement. Various form of explicit type conversion
are explained below:

1. int(a, base): This function converts any data type to integer. ‘Base’
specifies the base in which string is if the data type is a string.

33 IQRA BCA College


Unit :2 Python Fundamentals

2. float(): This function is used to convert any data type to a floating-


point number
.

• Python3

# Python code to demonstrate Type conversion

# using int(), float()

# initializing string

s = "10010"

# printing string converting to int base 2

c = int(s,2)

print ("After converting to integer base 2 :


", end="")

print (c)

# printing string converting to float

e = float(s)

print ("After converting to float : ",


end="")

print (e)

Output:

34 IQRA BCA College


Unit :2 Python Fundamentals

After converting to integer base 2 : 18


After converting to float : 10010.0
1. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.

• Python3

# Python code to demonstrate Type conversion

# using ord(), hex(), oct()

# initializing integer

s = '4'

# printing character converting to integer

c = ord(s)

print ("After converting character to integer


: ",end="")

print (c)

35 IQRA BCA College


Unit :2 Python Fundamentals

# printing integer converting to hexadecimal


string

c = hex(56)

print ("After converting 56 to hexadecimal


string : ",end="")

print (c)

# printing integer converting to octal


string

c = oct(56)

print ("After converting 56 to octal string :


",end="")

print (c)

Output:

After converting character to integer : 52


After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.

• Python3

# Python code to demonstrate Type conversion

36 IQRA BCA College


Unit :2 Python Fundamentals

# using tuple(), set(), list()

# initializing string

s = 'geeks'

# printing string converting to tuple

c = tuple(s)

print ("After converting string to tuple : ",end="")

print (c)

# printing string converting to set

c = set(s)

print ("After converting string to set : ",end="")

print (c)

# printing string converting to list

c = list(s)

print ("After converting string to list : ",end="")

print (c)

Output:

After converting string to tuple : ('g', 'e', 'e', 'k', 's')


After converting string to set : {'k', 'e', 's', 'g'}

37 IQRA BCA College


Unit :2 Python Fundamentals

After converting string to list : ['g', 'e', 'e', 'k', 's']


9. dict() : This function is used to convert a tuple of order (key,value) into
a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : : This function converts real numbers to
complex(real,imag) number.

• Python3

# Python code to demonstrate Type conversion

# using dict(), complex(), str()

# initializing integers

a =1

b =2

# initializing tuple

tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex


number

c = complex(1,2)

print ("After converting integer to complex


number : ",end="")

print (c)

38 IQRA BCA College


Unit :2 Python Fundamentals

# printing integer converting to string

c = str(a)

print ("After converting integer to string :


",end="")

print (c)

# printing tuple converting to expression


dictionary

c = dict(tup)

print ("After converting tuple to dictionary


: ",end="")

print (c)

Output:

After converting integer to complex number : (1+2j)


After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}

12. chr(number) : : This function converts number to its corresponding


ASCII character.

• Python3

# Convert ASCII value to characters

a = chr(76)

39 IQRA BCA College


Unit :2 Python Fundamentals

b = chr(77)

print(a)

print(b)

Output:

L
M

40 IQRA BCA College

You might also like