[go: up one dir, main page]

0% found this document useful (0 votes)
77 views32 pages

CH 1

Uploaded by

Parth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views32 pages

CH 1

Uploaded by

Parth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit – 1 Fundamentals of Python

1 Fundamentals of Python

Topics Covered

 Install and configure Python


 Introduction to Python, History of Python, Python Features, Python Applications
 Installing Python
 Explain general structure of python program
 Basic Structure of Python program
 Keywords and Identifiers
 Develop programs using variables, operators and input-output functions
 Data types and Variables
 Type Casting
 Input-Output functions: input, print
 Operators

What is Python?
• Python is a general purpose, dynamic, high-level, and interpreted programming
language.
• It supports Object Oriented programming approach to develop applications.
• It is simple and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.
• Python supports multiple programming pattern, including object-oriented, imperative,
and functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with
web, enterprise, 3D CAD, etc.
• We don't need to use data types to declare variable because it is dynamically typed so
we can write a=10 to assign an integer value in an integer variable.
• Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

Why learn Python?


• 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, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.

Prepared By:Prof. Mayuri M. Rajpara


Page 1 of 32
Unit – 1 Fundamentals of Python

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

Python History, Features & Installation


Python History
• Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
• Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under the
General Public License (GPL).
• Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.

Features of Python
• Python provides many useful features which make it popular and valuable from the
other programming languages.
• It supports object-oriented programming; procedural programming approaches and
provides dynamic memory allocation.
• We have listed below a few essential features.

1. Easy to Learn and Use:


• Python is easy to learn as compared to other programming languages.
• Its syntax is straightforward and much the same as the English language.
• There is no use of the semicolon or curly-bracket, the indentation defines the code
block.
• It is the recommended programming language for beginners.

2. Expressive Language:
• Python can perform complex tasks using a few lines of code.
• A simple example, the hello world program you simply type print("Hello World").
• It will take only one line to execute, while Java or C takes multiple lines.

3. Interpreted Language:
• Python is an interpreted language; it means the Python program is executed one line at a
time.
• The advantage of being interpreted language, it makes debugging easy and portable.

Prepared By:Prof. Mayuri M. Rajpara


Page 2 of 32
Unit – 1 Fundamentals of Python

4. Cross-platform Language:
• Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc.
• So, we can say that Python is a portable language.
• It enables programmers to develop the software for several competing platforms by
writing a program only once.

5. Free and Open Source:


• Python is freely available for everyone.
• It is freely available on its official website www.python.org.
• It has a large community across the world that is dedicatedly working towards make
new python modules and functions.
• Anyone can contribute to the Python community.
• The open-source means, "Anyone can download its source code without paying any
penny."

6. Object-Oriented Language:
• Python supports object-oriented language and concepts of classes and objects come into
existence.
• It supports inheritance, polymorphism, and encapsulation, etc.
• The object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.

7. Extensible:
• It implies that other languages such as C/C++ can be used to compile the code and thus
it can be used further in our Python code.
• It converts the program into byte code, and any platform can use that byte code.

8. Large Standard Library:


• It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting.
• There are various machine learning libraries, such as Tensor flow, Pandas, Numpy,
Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python
web development.

9. GUI Programming Support:


• Graphical User Interface is used for the developing Desktop application.
• PyQT5, Tkinter, Kivy are the libraries which are used for developing the web
application.

10. Integrated:
• It can be easily integrated with languages like C, C++, and JAVA, etc.
• Python runs code line by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable:
• The code of the other programming language can use in the Python source code.
• We can use Python source code in another programming language as well.

Prepared By:Prof. Mayuri M. Rajpara


Page 3 of 32
Unit – 1 Fundamentals of Python

• It can embed other language into our code.

12. Dynamic Memory Allocation:


• In Python, we don't need to specify the data-type of the variable.
• When we assign some value to the variable, it automatically allocates the memory to
the variable at run time.
• Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.

Python Applications
• Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development.
• Python makes its presence in every emerging field.
• It is the fastest-growing programming language and can develop any application.
• Here, we are specifying application areas where Python can be applied.

1. Web Applications:
• We can use Python to develop web applications.
• It provides libraries to handle internet protocols such as HTML and XML, JSON, Email
processing, request, beautifulSoup, Feedparser, etc.
• One of Python web-framework named Django is used on Instagram.
• Python provides many useful frameworks, and these are given below:
 Django and Pyramid framework(Use for heavy applications)

Prepared By:Prof. Mayuri M. Rajpara


Page 4 of 32
Unit – 1 Fundamentals of Python

 Flask and Bottle (Micro-framework)


 Plone and Django CMS (Advance Content management)

2. Desktop GUI Applications:


• The GUI stands for the Graphical User Interface, which provides a smooth interaction
to any application.
• Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
 Tkinter or Tk
 wxWidgetM
 Kivy (used for writing multitouch applications )
 PyQt or Pyside

3. Console-based Application:
• Console-based applications run from the command-line or shell.
• These applications are computer program which are used commands to execute.
• This kind of application was more popular in the old generation of computers.
• Python can develop this kind of application very effectively.
• It is famous for having REPL, which means the Read-Eval-Print Loop that makes it
the most suitable language for the command-line applications.
• Python provides many free library or module which helps to build the command-line
apps.
• The necessary IO libraries are used to read and write.
• It helps to parse argument and create console help text out-of-the-box.
• There are also advance libraries that can develop independent console apps.

4. Software Development:
• Python is useful for the software development process.
• It works as a support language and can be used to build control and management,
testing, etc.
 SCons is used to build control.
 Buildbot and Apache Gumps are used for automated continuous compilation and
testing.
 Round or Trac for bug tracking and project management.

5. Scientific and Numeric:


• This is the era of Artificial intelligence where the machine can perform the task the
same as the hu-man.
• Python language is the most suitable language for Artificial intelligence or machine
learning.
• It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
• Implementing machine learning algorithms require complex mathematical calculation.
• Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy,
Scikit-learn, etc.
• If you have some basic knowledge of Python, you need to import libraries on the top of
the code.
• Few popular frameworks of machine libraries are given below.

Prepared By:Prof. Mayuri M. Rajpara


Page 5 of 32
Unit – 1 Fundamentals of Python

 SciPy
 Scikit-learn
 NumPy
 Pandas
 Matplotlib

6. Business Applications:
• Business Applications differ from standard applications.
• E-commerce and ERP are an example of a business application.
• This kind of application requires extensively, scalability and readability, and Python
provides all these features.
• Oddo is an example of the all-in-one Python-based application which offers a range of
business applications.
• Python provides a Tryton platform which is used to develop the business application.

7. Audio or Video-based Applications:


• Python is flexible to perform multiple tasks and can be used to create multimedia
applications.
• Some multimedia applications which are made by using Python are TimPlayer,
cplay, etc.
• The few multimedia libraries are given below.
 Gstreamer
 Pyglet
 QT Phonon

8. 3D CAD Applications:
• The CAD (Computer-aided design) is used to design engineering related architecture.
• It is used to develop the 3D representation of a part of a system.
• Python can create a 3D CAD application by using the following functionalities.
 Fandango (Popular )
 CAMVOX
 HeeksCNC
 AnyCAD
 RCAM

9. Enterprise Applications:
• Python can be used to create applications that can be used within an Enterprise or an
Organization.
• Some real-time applications are OpenERP, Tryton, Picalo, etc.

10. Image Processing Application:


• Python contains many libraries that are used to work with the image.
• The image can be manipulated according to our requirements.
• Some libraries of image processing are given below.
 OpenCV
 Pillow
 SimpleITK

Prepared By:Prof. Mayuri M. Rajpara


Page 6 of 32
Unit – 1 Fundamentals of Python

Installation of Python
How to Install Python (Environment Set-up)?:
• In order to become Python developer, the first step is to learn how to install or update
Python on a local machine or computer.
• We will discuss the installation of Python on various operating systems.

Installation on Windows:
• Visit the link https://www.python.org/downloads/ to download the latest release
of Python.
• In this process, we will install Python 3.8.6 on our Windows operating system.
• When we click on the above link, it will bring us the following page.

Step - 1: Select the Python's version to download.

Click on the download button.

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded; the following window will
open. Select Customize installation and proceed. Click on the Add Path check box, it
will set the Python path automatically.

Prepared By:Prof. Mayuri M. Rajpara


Page 7 of 32
Unit – 1 Fundamentals of Python

We can also click on the customize installation to choose desired location and features.
Other important thing is install launcher for the all user must be checked.

Step - 3 Installations in Process

• Now, try to run python on the command prompt.


• Type the command python --version in case of python3.

Prepared By:Prof. Mayuri M. Rajpara


Page 8 of 32
Unit – 1 Fundamentals of Python

• We are ready to work with the Python.

Basic Structure of Python program


Basic Syntax
First Python Program
• In this Section, we will discuss the basic syntax of Python, we will run a simple
program to print Hello World on the console.
• Python provides us the two ways to run a program:
1. Using Interactive interpreter prompt
2. Using a script file

• Let's discuss each one of them in detail.

1. 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 we 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
(python3 in case if you have Python2 and Python3 both installed on your system).
• It will open the following prompt where we can execute the Python statement and check
their impact on the console.

Prepared By:Prof. Mayuri M. Rajpara


Page 9 of 32
Unit – 1 Fundamentals of Python

• After writing the print statement, press the Enter key.

• Here, we get the message "Hello World !" printed on the console.

2. Using a script file (Script Mode Programming):


• The interpreter prompt is best to run the single-line statements of the code.
• However, we cannot write the code every-time on the terminal.
• It is not suitable to write multiple lines of code.
• Using the script mode, we can write multiple lines code into a file which can be
executed later.
• For this purpose, we need to open an editor like notepad, create a file named and save it
with .py extension, which stands for "Python".
• Now, we will implement the above example using the script mode.

print ("hello world"); #here, we have used print() function to print the message on the
console.

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

Prepared By:Prof. Mayuri M. Rajpara


Page 10 of 32
Unit – 1 Fundamentals of Python

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a
new blank script in which we can write our code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.

Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will
display the output to the shell.

Prepared By:Prof. Mayuri M. Rajpara


Page 11 of 32
Unit – 1 Fundamentals of Python

• The output will be shown as follows.

Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we
should be aware of the path of the directory where we have saved our file.
• Open the command line prompt and navigate to the directory.

Prepared By:Prof. Mayuri M. Rajpara


Page 12 of 32
Unit – 1 Fundamentals of Python

• We need to type the python keyword, followed by the file name and hit enter to run the
Python file.

Keywords/Reserved Words
• Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers:
• All the Python keywords contain lowercase letters only.

Keywords/ Reserved Description


Words
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception
occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be
executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator

Prepared By:Prof. Mayuri M. Rajpara


Page 13 of 32
Unit – 1 Fundamentals of Python

or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
With Used to simplify exception handling
Yield To end a function, returns a generator

Python Identifiers (Naming conventions for Python identifiers)


• 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).
• Identifiers are case sensitive
(Manpower and manpower are two different identifiers in Python.)
• Class names start with an uppercase letter
• Other identifiers start with a lowercase letter.
• Starting with a single leading underscore indicates private.
• Starting with two leading underscores indicates strongly private.
• Ends with two underscores means a language defined special name.
• Python does not allow punctuation characters such as @, $, and % within identifiers.

Python Variables & Data Types

Python Variables
• Variable is a name that is used to refer to memory location.
• Python variable is also known as an identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but they have to begin with
a letter or an underscore.
• It is recommended to use lowercase letters for the variable name.
• Rahul and rahul both are two different variables.
• 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.

Identifier Naming:
• Variables are the example of identifiers.
• An Identifier is used to identify the literals used in the program.

Prepared By:Prof. Mayuri M. Rajpara


Page 14 of 32
Unit – 1 Fundamentals of Python

• The rules to name an identifier are given below.


1. The first character of the variable must be an alphabet or underscore ( _ ).
2. All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore, or digit (0-9).
3. Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
4. Identifier name must not be similar to any keyword defined in the language.
5. Identifier names are case sensitive; for example, myname and MyName is not the same.
6. Examples of valid identifiers: a123, _n, n_9, etc.
7. Examples of invalid identifiers: 1a, n%4, n 9, etc.

Assigning Values to Variables:


• Python variables do not need explicit declaration to reserve memory space.
• The declaration happens automatically when you assign a value to a variable.
• The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
• For example −

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print (counter)
print(miles)
print (name)

• Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively.
• This produces the following result –
100
1000.0
John

Multiple Assignment:
• Python allows you to assign a single value to several variables simultaneously.
• For example −
a=b=c=1
• Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location.
• You can also assign multiple objects to multiple variables.
• For example −
a,b,c = 1,2,"john"
• Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

Prepared By:Prof. Mayuri M. Rajpara


Page 15 of 32
Unit – 1 Fundamentals of Python

Python Variable Types OR Scope of Variable:


• All variables in a program may not be accessible at all locations in that program.
• This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can access a
particular identifier.
• There are two types of variables in Python:
1. Local variables
2. Global variables

1. Local Variable:
• Local variables are the variables that declared inside the function and have scope within
the function.
• Let's understand the following example.
Example:
# Declaring a function
def add ():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)

# Calling a function
add ()

Output:
The sum is: 50

Explanation:
• In the above code, we declared a function named add () and assigned a few variables
within the function.
• These variables will be referred to as the local variables which have scope only inside
the function.
• If we try to use them outside the function, we get a following error.

add ()
# Accessing local variable outside the function
print (a)

Output:
The sum is: 50
print(a)
NameError: name ‘a’ is not defined

Prepared By:Prof. Mayuri M. Rajpara


Page 16 of 32
Unit – 1 Fundamentals of Python

• We tried to use local variable outside their scope; it threw the NameError.

2. Global Variables:
• Global variables can be used throughout the program, and its scope is in the entire
program.
• We can use global variables inside or outside the function.
• A variable declared outside the function is the global variable by default.
• Python provides the global keyword to use global variable inside the function.
• If we don't use the global keyword, the function treats it as a local variable.

Example:
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To python'
print(x)

mainFunction()
print(x)

Output:
101
Welcome To python
Welcome To python

Explanation:
• In the above code, we declare a global variable x and assign a value to it.
• Next, we defined a function and accessed the declared variable using
the global keyword inside the function.
• Now we can modify its value.
• Then, we assigned a new string value to the variable x.
• Now, we called the function and proceeded to print x.
• It printed the as newly assigned value of x.

Global Variables V/S Local Variables:


• Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
• This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body by
all functions.

Prepared By:Prof. Mayuri M. Rajpara


Page 17 of 32
Unit – 1 Fundamentals of Python

• When you call a function, the variables declared inside it are brought into scope.

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.
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.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
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.
• 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

Prepared By:Prof. Mayuri M. Rajpara


Page 18 of 32
Unit – 1 Fundamentals of Python

• We will give a brief introduction of the above data-types.

1. 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))

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'>

Prepared By:Prof. Mayuri M. Rajpara


Page 19 of 32
Unit – 1 Fundamentals of Python

The type of b <class 'float'>


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

• Python supports three types of numeric data.

1. int: Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. float: Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex: A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0
+ 2.3j, etc.

2. 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.
• 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

Example – 2
str1 = 'hello python' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator

Prepared By:Prof. Mayuri M. Rajpara


Page 20 of 32
Unit – 1 Fundamentals of Python

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 python hello python
hello python 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.
• 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']

Prepared By:Prof. Mayuri M. Rajpara


Page 21 of 32
Unit – 1 Fundamentals of Python

[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.
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.


tup[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>

Prepared By:Prof. Mayuri M. Rajpara


Page 22 of 32
Unit – 1 Fundamentals of Python

t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

3. 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.
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'])

4. 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)

Prepared By:Prof. Mayuri M. Rajpara


Page 23 of 32
Unit – 1 Fundamentals of Python

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

5. 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.
# 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}

Type Casting:
• We come across different kinds of arithmetic operations in which multiple data types
are involved and then results are obtained accordingly.
• Here we will discuss both,
1. Implicit type conversion
2. Explicit type conversion

Prepared By:Prof. Mayuri M. Rajpara


Page 24 of 32
Unit – 1 Fundamentals of Python

1. Implicit Type Conversion:


• During the implicit type conversion, the user is not supposed to mention any specific
data type during the conversion.
• The following program illustrates how it can be done in Python.

#program to demonstrate implicit type conversion


#initializing the value of a
a = 10
print(a)
print("The type of a is ", type(a))
#initializing the value of b
b = 4.5
print(b)
print("The type of b is ", type(b))
#initializing the value of c
c = 4.0
print(c)
print("The type of c is ", type(c))
#initializing the value of d
d = 5.0
print(d)
print("The type of d is ", type(d))
#performing arithmetic operations
res = a * b
print("The product of a and b is ", res)
add = c + d
print("The addition of c and d is ", add)

Output:
10
The type of a is <class 'int'>
4.5
The type of b is <class 'float'>
4.0
The type of c is <class 'float'>
5.0
The type of d is <class 'float'>
The product of a and b is 45.0
The addition of c and d is 9.0

2. Explicit Type Conversion:


• In this type conversion, the user is supposed to pass the value in a function to obtain the
required data type.
• The int(), float() and str() are mostly used for the explicit type conversion.
• Consider the program given below,

#program to demonstrate explicit type conversion


#initializing the value of a

Prepared By:Prof. Mayuri M. Rajpara


Page 25 of 32
Unit – 1 Fundamentals of Python

a=10.6
print("The type of 'a' before typecasting is ",type(a))
print(int(a))
print("The type of 'a' after typecasting is",type(a))
#initializing the value of b
b=8.3
print("The type of 'b' before typecasting is ",type(b))
print(int(b))
print("The type of 'b' after typecasting is",type(b))
#initializing the value of c
c=7
print("The type of 'c' before typecasting is ",type(c))
print(float(c))
print("The type of 'c' after typecasting is",type(c))

Output:
The type of 'a' before typecasting is <class 'float'>
10
The type of 'a' after typecasting is <class 'float'>
The type of 'b' before typecasting is <class 'float'>
8
The type of 'b' after typecasting is <class 'float'>
The type of 'c' before typecasting is <class 'int'>
7.0
The type of 'c' after typecasting is <class 'int'>

Input-Output functions: input, print:


1. Taking Input from the user (Input()):
• Sometimes a developer might want to take input from the user at some point in the
program.
• To do this Python provides an input() function.
Syntax:
input('prompt')

• Where, prompt is a string that is displayed on the string at the time of taking input.
Example 1: Taking input from the user with a message.
# Taking input from the user
name = input("Enter your name: ")

# Output
print("Hello, " + name)

Output:
Enter your name: Krishna
Hello, Krishna

Prepared By:Prof. Mayuri M. Rajpara


Page 26 of 32
Unit – 1 Fundamentals of Python

Example 2:
By default input() function takes the user’s input in a string. So, to take the input in the form of
int, you need to use int() along with input function.

# Taking input from the user as integer


num = int(input("Enter a number: "))

add = num + 1

# Output
print(add)

Output:
Enter a number: 25
26
2. Displaying Output(Print()):
• Python provides the print() function to display output to the console.
Syntax:
print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:

Parameter Description
value(s) Any value, and as many as you like. Will be converted to string before
printed
sep=’separator’ (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’ (Optional) Specify what to print at the end.Default : ‘\n’

file (Optional) An object with a write method. Default :sys.stdout


flush (Optional) A Boolean, specifying if the output is flushed (True) or buffered
(False). Default: False

Returns It returns output to the screen.

Example:
# Python program to demonstrate
# print() method
print("GFG")

# code for disabling the softspace feature


print('G', 'F', 'G', sep ='')

Prepared By:Prof. Mayuri M. Rajpara


Page 27 of 32
Unit – 1 Fundamentals of Python

# using end argument


print("Python", end = '@')
print("Welcome")

Output:
GFG
GFG
Python@Welcome

Operators:
• The operator can be defined as a symbol which is responsible for a particular operation
between two operands.
• Operators are the pillars of a program on which the logic is built in a specific
programming language.
• Python provides a variety of operators, which are described as follows.
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators:
• Arithmetic operators are used to perform arithmetic operations between two operands.
• It includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**) operators.
• Consider the following table for a detailed explanation of arithmetic operators.

Operator Description Example


+ (Addition) It is used to add two operands. a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand a = 20, b = 10 => a - b = 10
from the first operand. If the first operand is
less than the second operand, the value
results negative.
/ (divide) It returns the quotient after dividing the first a = 20, b = 10 => a/b = 2.0
operand by the second operand.
* It is used to multiply one operand with the a = 20, b = 10 => a * b = 200
(Multiplication) other.
% (reminder) It returns the reminder after dividing the a = 20, b = 10 => a%b = 0
first operand by the second operand.
** (Exponent) It is an exponent operator represented as it a**b =10 to the power 20
calculates the first operand power to the
second operand.
//(Floor It gives the floor value of the quotient 9//2 = 4 and 9.0//2.0 = 4.0, -

Prepared By:Prof. Mayuri M. Rajpara


Page 28 of 32
Unit – 1 Fundamentals of Python

division) produced by dividing the two operands. 11//3 = -4, -11.0//3 = -4.0

2. Comparison Operator:
• Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly.
• The comparison operators are described in the following table.
• Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


== If the value of two operands is equal, then the (a == b) is not true.
condition becomes true.
!= If the value of two operands is not equal, then (a != b) is true.
the condition becomes true.
<= If the first operand is less than or equal to the (a <= b) is true.
second operand, then the condition becomes
true.
>= If the first operand is greater than or equal to (a >= b) is not true.
the second operand, then the condition
becomes true.
> If the first operand is greater than the second (a > b) is not true.
operand, then the condition becomes true.
< If the first operand is less than the second (a < b) is true.
operand, then the condition becomes true.
<> If values of two operands are not equal, then (a <> b) is true. This is similar
condition becomes true. to != operator.

3. Assignment Operators:
• The assignment operators are used to assign the value of the right expression to the left
operand.
• The assignment operators are described in the following table.

Operator Description Example


= It assigns the value of the right expression to c = a + b assigns value of a +
the left operand. b into c
+= It increases the value of the left operand by the a = 10, b = 20 => a+ = b will
value of the right operand and assigns the be equal to a = a+ b and
modified value back to left operand. therefore, a = 30.
-= It decreases the value of the left operand by a = 20, b = 10 => a- = b will
the value of the right operand and assigns the be equal to a = a- b and
modified value back to left operand. therefore, a = 10.
*= It multiplies the value of the left operand by a = 10, b = 20 => a* = b will
the value of the right operand and assigns the be equal to a = a* b and
modified value back to then the left operand. therefore, a = 200.
%= It divides the value of the left operand by the a = 20, b = 10 => a % = b will
value of the right operand and assigns the be equal to a = a % b and
reminder back to the left operand. therefore, a = 0.

Prepared By:Prof. Mayuri M. Rajpara


Page 29 of 32
Unit – 1 Fundamentals of Python

**= a**=b will be equal to a=a**b a = 4, b =2, a**=b will assign


4**2 = 16 to a.
//= A//=b will be equal to a = a// b a = 4, b = 3, a//=b will assign
4//3 = 1 to a.

4. Bitwise Operators:
• The bitwise operators perform bit by bit operation on the values of the two operands.
• Bitwise operator works on bits and performs bit by bit operation.
• Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100
and 0000 1101 respectively.
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

• Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands:

Operator Description Example


& (binary and) If both the bits at the same place in two (a & b) (means 0000 1100)
operands are 1, then 1 is copied to the
result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits (a | b) = 61 (means 0011
are zero; otherwise, the resulting bit will be 1101)
1.
^ (binary xor) The resulting bit will be 1 if both the bits (a ^ b) = 49 (means 0011
are different; otherwise, the resulting bit 0001)
will be 0.
~ (negation) It calculates the negation of each bit of the (~a ) = -61 (means 1100 0011
operand, i.e., if the bit is 0, the resulting bit in 2's complement form due
will be 1 and vice versa. to a signed binary number.
<< (left shift) The left operand value is moved left by the a << 2 = 240 (means 1111
number of bits present in the right operand. 0000)
>> (right shift) The left operand is moved right by the a >> 2 = 15 (means 0000
number of bits present in the right operand. 1111)

5. Logical Operators:
• The logical operators are used primarily in the expression evaluation to make a
decision.
• Python supports the following logical operators.

Prepared By:Prof. Mayuri M. Rajpara


Page 30 of 32
Unit – 1 Fundamentals of Python

Operator Description
and If both the expression are true, then the condition will be true. If
a and b are the two expressions, a → true, b → true => a and b
→ true.
or If one of the expressions is true, then the condition will be true. If
a and b are the two expressions, a → true, b → false => a or b →
true.
not If an expression a is true, then not (a) will be false and vice
versa.

6. Membership Operators:
• Python membership operators are used to check the membership of value inside a
Python data structure.
• If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

Operator Description Example


in It is evaluated to be true if the first operand is x in y, here in results in a 1 if x
found in the second operand (list, tuple, or is a member of sequence y.
dictionary).
not in It is evaluated to be true if the first operand is not x not in y, here not in results in
found in the second operand (list, tuple, or a 1 if x is not a member of
dictionary). sequence y.

7. Identity Operators:
• The identity operators are used to decide whether an element certain class or type.

Operator Description Example


is It is evaluated to be true if the reference present x is y, here is results in 1 if
at both sides point to the same object. id(x) equals id(y).
is not It is evaluated to be true if the reference present x is not y, here is not results in
at both sides do not point to the same object. 1 if id(x) is not equal to id(y).

Comments:
• Python Comment is an essential tool for the programmers.
• Comments are generally used to explain the code.
• We can easily understand the code if it has a proper explanation.
• A good programmer must use the comments because in the future anyone wants to
modify the code as well as implement the new module; then, it can be done easily.
• In the other programming language such as C++, It provides the // for single-lined
comment and /*.... */ for multiple-lined comment, but Python provides the single-lined
Python comment.
• To apply the comment in the code we use the hash(#) at the beginning of the statement
or code.
• Let's understand the following example.

Prepared By:Prof. Mayuri M. Rajpara


Page 31 of 32
Unit – 1 Fundamentals of Python

# This is the print statement


print("Hello Python")

• Here we have written comment over the print statement using the hash(#).
• It will not affect our print statement.

Multiline Python Comment:


• We must use the hash(#) at the beginning of every line of code to apply the multiline
Python comment.
• Consider the following example.

# First line of the comment


# Second line of the comment
# Third line of the comment

Example:
# Variable a holds value 5
# Variable b holds value 10
# Variable c holds sum of a and b
# Print the result
a=5
b = 10
c = a+b
print("The sum is:", c)

Output:
The sum is: 15

• The above code is very readable even the absolute beginners can under that what is
happening in each line of the code.
• This is the advantage of using comments in code.
• We can also use the triple quotes ('''''') for multiline comment.
• The triple quotes are also used to string formatting.

Example:
def intro():
"""
This function prints Hello Joseph
"""
print("Hello Joseph")
intro()
Output:
Hello Joseph

Prepared By:Prof. Mayuri M. Rajpara


Page 32 of 32

You might also like