Python Fundamentals
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
• 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.
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.
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.
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.
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
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.
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.
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
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
“””
Example:
If True:
Print(“True”)
else:
print(“False”)
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.
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.
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.
• Identifiers.
• Keywords
• Literals
• Operators
• 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.
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.
• 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
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
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'>
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.
a=5
print("The type of a", type(a))
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:
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.
❖ Sequence Type
In the case of string handling, the operator + is used to concatenate two strings as
the operation "hello"+" python" returns "hello python".
Example - 1
Output:
Example - 2
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 [].
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.
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
• 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.
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
• 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 {}.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
• 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.
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
braces and separated by the comma. It can contain various types of values.
Consider the following example.
set2.add(10)
print(set2)
Output:
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Example of a function
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
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!
def greet(name):
"""
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.
>>> print(greet.__doc__)
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:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
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.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output :
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 .
Types of Functions
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.
# 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:
ADVERTISEMENT
# empty iterable
k = []
print(all(k))
Output:
True
False
False
False
True
x = 10
y = bin(x)
print (y)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard
truth testing procedure.
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.
Output:
x=8
print(callable(x))
Output:
False
ADVERTISEMENT
Output:
<class 'code'>
sum = 15
x=8
exec('print(x==8)')
exec('print(x+4)')
Output:
True
12
s = sum([1, 2,4 ])
print(s)
Output:
ADVERTISEMENT
7
17
l = [4, 3, 2, 0]
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
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.
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
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")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
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:
• Python3
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.
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.
• Python3
# initializing string
s = "10010"
c = int(s,2)
print (c)
e = float(s)
print (e)
Output:
• Python3
# initializing integer
s = '4'
c = ord(s)
print (c)
c = hex(56)
print (c)
c = oct(56)
print (c)
Output:
• Python3
# initializing string
s = 'geeks'
c = tuple(s)
print (c)
c = set(s)
print (c)
c = list(s)
print (c)
Output:
• Python3
# initializing integers
a =1
b =2
# initializing tuple
c = complex(1,2)
print (c)
c = str(a)
print (c)
c = dict(tup)
print (c)
Output:
• Python3
a = chr(76)
b = chr(77)
print(a)
print(b)
Output:
L
M