Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Unit1puthon Programming

The document discusses Python programming including the differences between compilers and interpreters, automatic memory management in Python, and two modes of using Python. It also covers features of Python like its readability, dynamic typing, and being open source and free.

Uploaded by

Shakshi ranawat
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit1puthon Programming

The document discusses Python programming including the differences between compilers and interpreters, automatic memory management in Python, and two modes of using Python. It also covers features of Python like its readability, dynamic typing, and being open source and free.

Uploaded by

Shakshi ranawat
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Python Programming

(BCACCA3102)
Unit1 Lecture
Shakshi K Ranawat
Compiler versus interpreter

• Python is a “high level” language.


• To translate these “high level” programs into machine
readable form, two types of programs are used. They are:-
interpreters and compilers:-
• An interpreter reads a high-level program and executes it,
one statement at a time.
• A compiler on the other hand reads the entire program (Also
called “source code”) and first converts into a “machine
readable” form (Also called “object code”). It then “executes”
the entire translated program ie the object code in one go.
Difference between an interpreted
and a compiled language
Automatic memory management:
The Python interpreter does automatic memory
management by allocating memory when objects are
created and reclaiming it when they are no longer
used.
It does this through “garbage collection”. This
concept will be explained later.
Java also has a garbage collector
But C does not have a garbage collector. So in C, you
have to explicitly free the memory yourself, or else
there will be a “memory leak”
Command line mode versus script mode
• Python is an interpreted language. So there
are two ways to use it:-
• First one can type a command on an input
straight into a Python interpreter and get the
output (The command line mode).
• The second method is to write the entire
program or script in one file and then run it (The
script mode)
• Python is an interpreted language. So there
are two ways to use it:-
• First one can type a command on an input
straight into a Python interpreter and get the
output (The command line mode).
• The second method is to write the entire
program or script in one file and then run it (The
script mode)
Explicit vs Implicit line continuation
• In Python, the end of a statement is marked by
a newline character. But you can make a
statement extend over multiple lines with the
line continuation character (\. This is explicit line
continuation.
• Line continuation in Python, is implicit (ie
implied) inside brackets [ ], parentheses ()and
braces { }.
Python keywords
What is Python
 Python is an interpreted, object-oriented,
high-level programming language with
dynamic semantics.
 Its high-level built in data structures,
combined with dynamic typing and dynamic
binding, make it very attractive for Rapid
Application Development, as well as for use as
a scripting or glue language to connect
existing components together.
To be continued……
 Python's simple, easy to learn syntax
emphasizes readability and therefore reduces
the cost of program maintenance. Python
supports modules and packages, which
encourages program modularity and code
reuse.
 The Python interpreter and the extensive
standard library are available in source or
binary form without charge for all major
platforms, and can be freely distributed.
Why to learn python

Key Points python


 Open Source
 Huge Standard Library
 Low Cost
 Large community support
 Reliability
 Privacy
 Performance
 Fast And Easy Installation
 Python Code is Easy To Use and Read
Uses of python programming
1. AI & Machine Learning
 It is widely thought that Python is the best programming language for
Artificial Intelligence (AI) because of its syntaxes being simple and
quickly learned. When it comes to machine learning, the ideas exchange
platform, “Towards Data Science”, tells us that 57% of data scientists and
machine learning developers utilize Python, with 33% prioritizing it for
development.

2. Data Analytics
 Many of the most popular data mining and analytics tools are written in
Python. As a result, it is an excellent tool for data science. Python’s tools
allow developers to separate important and relevant data. Not only is big
data useful for retaining customers, but it can also help organizations learn
more about themselves. This type of information can show businesses
where their weaknesses are and allow them to react once identified.
Uses of python programming

3. Web Development
 Python, as a backend language, is wonderfully versatile. Its relative
simplicity is a key factor here. Because its simple syntax is so similar to
the English language, web developers who use it save a lot of time and
energy. Uses Python is put to for backend web development including
processing data, interacting with databases, and sending information
between servers. Due to its frequency of use, there are a number of
Python frameworks that can be used for backend development including
Django.
4. Search Engine Optimisation (SEO)
 Python helps SEO professionals automate tasks and assists them in
extracting and analyzing large amounts of data. Python can be used to
analyze large data sets to identify issues on websites, such as broken
links, and can automate solutions to these to help minimize tedious tasks
Uses of python programming
5. Blockchain
 While there may be a few popular languages for blockchain development, including
Javascript, Java, C++, and more, Python is proving itself as a strong language. As with other
uses, Python recommends itself well for blockchain development because of its high
flexibility and functionality, reinforced by its security.

6. Game Development
 Although Python is not the top programming language used in game development, it is still
incredibly popular, especially for simpler games. The speed at which games can be created in
Python, owing to its simplicity, means that it is also a fabulous option for building prototypes
and developing ideas in the gaming industry, allowing more flexibility and faster processes
than other alternatives.

7. Automation
 Outside the above uses, Python can be useful to just about anyone who interacts with big data
sets, in or out of work. It can automate tedious tasks, including checking the information in
databases, data visualizations, financial analysis, and much, much more. Learning Python will
allow you to save time throughout your life, and it has the bonus of being one of the easier
programming languages to learn!
Uses of python programming
8. Software testing and prototyping
In software development, Python can aid in tasks like build control, bug
tracking, and testing. With Python, software developers can automate testing
for new products or features. Some Python tools used for software testing
include Green and Requestium.
9. Miscellaneous Python Uses
Besides all those implementations considered above, what else is Python
used for? Below are some fresh ideas:

Monitoring the stock market


Web scraping
Keeping updated a to-do list
Creating bots
Generating lists of random names, colors, phone numbers, currencies, etc.
Features of Python programing
Continued….

1. Easy To Learn and Readable Language


Python is extremely easy to learn. Its syntax is super simple and the
learning curve of Python is very smooth. It is extremely easy to
learn and code in Python and the indentation used instead of curly
braces in Python makes it very easy to read Python code.
2. Interpreted Language
Python is an interpreted language (an interpreted language is a
programming language that is generally interpreted, without
compiling a program into machine instructions. It is one where the
instructions are not directly executed by the target machine, but
instead, read and executed by some other program known as the
interpreter) and an IDLE (Interactive Development Environment) is
packaged along
Continued….

3. Dynamically Typed Language


Python is a dynamically typed language. In other words, in
Python, we do not need to declare the data types of the
variables which we define. It is the job of the Python
interpreter to determine the data types of the variables at
runtime based on the types of the parts of the expression.
4. Open Source And Free
Python is an open-source programming language and one can
download it for free from Python’s official website. The
community of Python users is constantly contributing to the
code of Python in order to improve it.
Continued….

5. Automatic memory management


The Python interpreter does automatic memory
management by allocating memory when objects are
created and reclaiming it when objects are no longer in
use.
• It does this through “garbage collection”. This concept
will be explained later.
• Java also has a garbage collector
• But C does not have garbage collector. So in C, you
have to explicitly free the memory yourself, or else
there will be a “memory leak”
Continued….

6. Portable
• Portability, in relation to software, indicates
how easily an application can be transferred
from one computer environment to another.
• Standard Python is written in portable ANSI C.
It can compiles and runs on all major operating
Systems like Windows, Linux, Unix and Mac
7.Dynamic typing or dynamic binding
For the present it is sufficient to know that in
Python the type of a variable need not be
declared before it is used.
This is different from statically typed languages
like C++ or Java, where the “type” of a variable
has to be declared before it can be used
Python 2.x and Python3.x Differences
Python Environment setup and installation
 1. Open a browser to the Python website and download the
Windows installer.
2)Double click on the downloaded file and install Python for all
users, and ensure that Python is added to your path. Click on
Install now to begin. Adding Python to the path will enable us to
use the Python interpreter from any part of the filesystem.
3. After the installation is complete, click Disable path length
limit and then Close. Disabling the path length limit means we
can use more than 260 characters in a file path.
4. Click Close to end the installation.
Data types in python
 Understand the various “built-in” data types and
concepts of “sequence” and “containers”
 Comprehend the concept of “mutability” and related
concept of object ID.
 Describe “type casting” and the various “implicit” and
“explicit” ways of casting.
 Provide “input” to a python script.
 Explain what are modules and packages.
 Understand python strings, “binary literals” and
“boolean” types.
Built-in Data Types
• Python has what are known as “built in” data
types.
• These built in data are of following 2 types:
- Simple: They includes int, float, complex, bool,
str etc
- Compound: These data types act as
“containers” of other data types. They includes
lists, tuples, dictionaries, strings, sets and
frozensets
Tree structure of built in data types
Numbers (including integers, floating points,
complex and bool)
• In Python, numbers are represented by data types integers
(int), floating points (float), complex and boolean (bool).
Some important characteristics of numbers in Python are
as follows:
• They store numeric values.
• They are immutable data types.
• Numeric data types can be ‘literals’ or ‘variables’. As with
all others, numerics (whether literals or variables) are
objects in Python.
• Number data types are created when you assign a value to
them
int (signed integers)
• Some noteworthy points regarding integers in Python are
as follows:-
• Python 2.x had two separate types for integers, that is, int
and long.
• Python 3.x has just one integer type, that is, int, which
behaves mostly like the old long type from Python 2.x.
• The maximum value of the int data type in Python 2.x was
limited by sys.maxint. This may be different for different
platforms. (But usually it is 232).
• But the sys.maxint constant is no more there in Python 3.x.
So, there is no longer a limit to the value of integers
float (floating point real values):
• In Python, a floating point number is written with a decimal
point.
• The part to the left represents the integer part of the
number and the part to the right represents the fraction
part of the number.
• Floating point numbers in Python can also be represented
in scientific notation using E or e.
• Note that, here ‘e’ stands for base 10 (Not Euler number).
• So you can represent a floating point number in scientific
notation as say 3.33 e -2 which is the same as 3.33 x 10-2 .
complex (complex numbers)
• A complex number consists of an “ordered
pair” of numbers of type x + yj, where x and y
may be int or float.
• Here, x represents the “real” part of the
number while “y” represents the “imaginary”
part of the number.
• The term “ordered pair” means that the order
of the number x and y matter. So x + yj is
different from y + xj
Bool
• Boolean values in Python are True and False
(Not true and false, that is, first letter must be
capital).
• The Boolean type in Python is called bool (Not
Bool nor boolean nor Boolean).
Strings
• Strings in Python are a “sequence of characters enclosed by quotation
marks”. You can use pairs of either single or double quotes to mark the
beginning and end of a string. • Since a string is a sequence, you can
use an “index” to access its individual characters.
• All index in Python start from 0. This means, the first character in a
string will have index 0. If there are “n” characters in a string, then the
index of the last item will be n-1.
• You can use the slice operator “[m : n ]” with indexes m and n.
• You can use the plus ( + ) operator for “concatenation” of two strings.
• You can use the asterisk ( * ) operator to “multiply” a string with a
positive integer. Here, “multiply” means “repetition”. Strings McGraw-
Hill | Python Programming: Problem Solving, Packages and Libraries
11
Lists
• A list in Python is a sequenced container.
• What does ‘container’ mean? A container in Python is
an object which can contain other objects. Hence, a list
can contain any valid python object, such as strings,
numbers or even other lists.
• What does sequence mean? In a sequence in Python,
each item is identified by an index, which starts from 0.
Hence, if a list in Python has n items, then the sequence
of first item is 0 and the sequence of the nth item is n-1.
• A list contains items separated by commas and enclosed
within square brackets ([ ]).
Tuples
• Some important aspects of the tuple data type are as
follows:
• Tuples are also “sequences” and are very similar to lists.
• A tuple has a number items/ objects/ values separated by
commas.
• However, while lists are enclosed within “square brackets”,
tuples are enclosed within “parentheses”.
• The elements of a list can be changed. So, lists are
“mutable”. However, the elements of a tuple cannot be
changed. So, tuples are “immutable”.
• You can think of a tuple as a “read-only” list
Dictionary -
• Some important points regarding dictionary are as follows: It has
“unordered” key-value pairs.
• A dictionary is a container, which contains other objects. So, you cannot
“access” the items of a dictionary through an “index” but you can access
the items of a dictionary through its “keys”.
• So, a dictionary has keys and for each key there is a value, which can be
an object of any type.
• Just like in maths you have a function definition as y = f(x), dictionaries
are something similar. You can think of x as keys and y as their
corresponding values.
• Just like in a mathematical function for one key there can be only one
value (Though the reverse need not be true, that is, for the same value
there can be different keys or to put it differently, different keys may have
the same values).
Dictionaries -
• A dictionary is a ‘mapping’ between x and y or
between the keys and its values.
• Dictionaries are enclosed by curly braces { } and
values can be assigned and accessed using square
braces [].
• The keys in a dictionary must be unique. The key
value pairs are separated by a colon, that is, :.
• The keys of a dictionary must be of an “immutable
data type” such as strings, numbers, or tuples.
Sets -
• A set contains an unordered collection of
immutable and unique objects.
• Sets, unlike lists or tuples, cannot have multiple
occurrences of the same element. There are
three important words in this definition:
• A set is a collection.
• It is unordered.
• The elements must be unique.
Sets -
• You can think of a set in Python as a dictionary with no
value, that is, a dictionary which only has keys.
• Remember, a dictionary uses curly braces and has a pair
comprising a key and a value.
• Think of a set as a data type, which has no values but has
only keys.
• Just like a dictionary, the items of a set can be enclosed in
curly brackets, but they must all be unique.
• •In case there are duplicate items, the Python interpreter
will simply keep only one instance of the duplicate items.
Some other aspects about Python Sets
• With sets you cannot do “sequence-like behavior”, such as
indexing and slicing.
• In Python, sets cannot contain mutable elements, such as
lists or dictionaries.
• Please note that sets are themselves mutable (This means,
elements can be added or removed from a set).
• However, the items which comprise a set must be
immutable, that is, these items cannot be changed.
• Since lists and dictionaries in Python can be changed, they
cannot be items of a set. But you can “convert” a list or a
dictionary to a Python set using some operators.
None in Python
• The following points regarding the data type “None” are
relevant:
• “None” is used to define a “null” value or “no value”.
• None does not mean either “0” or “an empty container”, such
as an empty string.
• None also does not mean False.
• None does not mean undefined.
• None data type is a real data type, which occupies space in
memory and can be assigned to a variable just as any other data
type.
• In many programming languages, such as Java/ C++, the
keyword “null” is used rather than None
Mutable vs Immutable
• Mutable—Internal state of the object is
changeable.
• Immutable— Internal state of the object
cannot be modified.
Explicit versus implicit type casting
• The type of casting may be explicit or implicit.
In explicit type casting, the programmer
explicitly converts or casts one type of data
into another.
• In implicit type casting, on the other hand, the
interpreter implicitly (that is, without explicit
instructions from the programmer) converts or
casts one type of data into another.
Mixed arithmetic, “narrow” and “wide”
types
• Python supports mixed type of arithmetic as long as the data types,
which are linked together by operators are capable of being converted
to other data types.
• For instance, Python does not allow something like ‘Hello’ + 1, unlike C+
+. C++ would convert , that is, cast the 1 into a string and then
concatenate it to ‘Hello’.
• Why does Python not allow it? Because as per the Zen of Python,
“Explicit is better than implicit” meaning that the programmer should do
these things knowingly, that is, explicitly rather than unknowingly done
by the interpreter leading to bugs.
• Further, a type casting may be narrow or wide. If casting leads to loss of
data, it is ‘narrow’. For instance, casting a float to an int leads to a loss of
fraction portion so it is ‘narrow’ casting. But casting an integer to a float
is ‘wide’.
Some important Boolean type conversions

• Empty string is mapped to False.


• Non-empty string is mapped to True.
• Integer 0 is mapped to False.
• Every non-zero integer (Including negatives) is
mapped to True.
The following are considered False in
Python:
• None
• False
• Zero of any numeric type, for instance,
• - Numeric integer →0,
• - Numeric float→ 0.0,
• - Numeric complex→ 0j.
• Any empty sequence, for instance,
• - Empty string→ ‘’,
• - Empty tuple→ (),
• - Empty list→ [].
• Any empty mapping, for instance,
• - Empty dictionary→{}.
What is runnable code?
• A runnable code is that piece of code, which will be executed upon
loading of the module.
• For instance, if the module has a print() function, which is executed
when the module is loaded, then this print() function is an example of
runnable code.
• On the other hand, if the module has a class definition, then such code
is not executed till such time such an instance of a class, that is, an
object is created. So, a class definition in a module is not runnable code.
• Similarly, a method definition inside a module is not executed when the
module is loaded, because functions are executed when they are called
and not when the module is loaded.
• Therefore, function definitions in modules are also examples of
nonrunnable codes.
Modules, packages and libraries
• Module— A module is simply a file with .py extension, in which you
may put your script/ code.
• Package— A python package is a “directory of python modules”. It
is a “name space”, which contains “modules” or even other
packages”. In addition, a package contains an additional file named
__init__.py. This file exists just below the directory. This means, it is
not in one of the modules but rather directly under the directory,
which is the package. (Concepts of “name space” and __init__.py
are explained later )
• Library— In Python the term “library” does not have a “conceptually
different” meaning than “package”. Loosely, you may say that a
Python package is a “directory” of Python modules. (Which, in a
way, is same as a package).
Thank you
“Simple is better than Complex”

You might also like