[go: up one dir, main page]

0% found this document useful (0 votes)
32 views27 pages

Unit 1 (First)

Uploaded by

yadavsumit1908
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)
32 views27 pages

Unit 1 (First)

Uploaded by

yadavsumit1908
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/ 27

Unit - 1

Basic Introduction, control Structure & Strings


Python
• Python is a very popular general-purpose interpreted, interactive,
object-oriented, and high-level programming language. It was
created by Guido van Rossum, and released in 1991.
• Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style
or technique of programming that encapsulates code within
objects.
• It is used for:
– Python can be used for web development (server-side),
– software development
– 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.
Characteristics of Python
• Following are important characteristics of Python
Programming −
• It supports functional and structured programming
methods as well as OOP.
• It can be used as a scripting language or can be
compiled to byte-code for building large applications.
• It provides very high-level dynamic data types and
supports dynamic type checking.
• It supports automatic garbage collection.(the process
of automatic deletion of unwanted or unused objects
to free the memory is called garbage collection )
• It can be easily integrated with C, C++, COM, ActiveX,
CORBA, and Java.
Applications of Python
• Python is a general-purpose, popular programming language, and it is used in
almost every technical field. The various areas of Python use are given below.

• Data Science: Data Science is a vast field, and Python is an important language for
this field because of its simplicity, ease of use, and availability of powerful data
analysis and visualization libraries like NumPy, Pandas, and Matplotlib.
• Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI
based Desktop Applications.
• Console-based Applications: Python is also commonly used to create command-
line or console-based applications because of its ease of use and support for
advanced features such as input/output redirection and piping.
• Software Development: Python is considered one of the best software-making
languages. Python is easily compatible with both from Small Scale to Large Scale
software.
• Artificial Intelligence: AI is an emerging Technology, and Python is a perfect
language for artificial intelligence and machine learning because of the availability
of powerful libraries such as TensorFlow, Keras, and PyTorch.
• Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing,networking, and parallel
processing.
• 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
• Machine Learning: Python is widely used for machine learning due to its simplicity,
ease of use, and availability of powerful machine learning libraries.
• Computer Vision or Image Processing Applications: Python can be used for
computer vision and image processing applications through powerful libraries such
as OpenCV and Scikit-image.
• Speech Recognition: Python can be used for speech recognition applications
through libraries such as Speech Recognition and PyAudio.
• Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like dataanalysis, machine learning, and
more.
• Education: Python's easy-to-learn syntax and availability of many resources make it
an ideal language for teaching programming to beginners.
• Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
• IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
• Networking: Python is used in networking for developing scripts and applications
for network automation, monitoring, and management.
• Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
• Audio and Music: Python has libraries like Pyaudio, which is used for audio
processing, synthesis, and analysis, and Music21, which isused for music analysis
and generation.
• Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
Features in Python
• Python is a high level language. It is a free and open source
language.
• It is an interpreted language, as Python programs are
executed by an interpreter. The interpreter is also called
Python shell.
• Python programs are easy to understand as they have a
clearly defined syntax and relatively simple structure.
• Python is case-sensitive. For example, NUMBER and
number are not same in Python.
• Python is portable and platform independent, means it can
run on various operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular
web services and applications are builtusing Python.
• Python uses indentation for blocks and nested blocks.
Working with Python
• To write and run (execute) a Python program, we need
to have a Python interpreter installed on our computer
or we can use any online Python interpreter.
• There are two ways to use the Python interpreter:
• a) Interactive mode : Interactive mode allows execution
of individual statement instantly. In the interactive
mode, we cannot save the statements for future use
and we have to retype the statements to run them
again.
• b) Script mode : In the script mode, we can write a
Python program in a file, save it and then use the
interpreter to execute it. Python scripts are saved as
files where file name has extension “.py”. By default,
the Python scripts are saved in the Python installation
folder.
Tokens in Python

• The smallest individual unit in a program is


called as token or a lexical unit.
• Python has following tokens:
– Keywords
– Identifiers
– Literals
– Operators
– Punctuators
Keywords
• Keywords are predefined words with special
meaning to the language compiler or interpreter.
These are reserved for special purpose and not
be used as normal identifier names.
• Python programming language contain following
keywords:
• False, none, true, and, as, assert, break, class,
continue, def, finally, except, else,elif, del, for,
from global, if, import, is, in, lambda, nonlocal,
not, try, return, raise, pass, or, while, with, yield.
VARIABLES
• A variable in a program is uniquely identified
by a name (identifier). Variable in Python
refers to an object — an item or element that
is stored in the memory. Value of a variable
can be a string (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of
alphanumeric characters (CD67). In Python we
can use an assignment statement to create
new variables and assign specific values to
them.
• Write a Python program to find the area of a
rectangle given that its length is 10 units and
breadth is 20 units.
• Write a Python program to find the sum of
two numbers.
Identifiers
• Identifiers are the names given to different parts of the
program, like variables, objects, class, functions, list,
dictionaries etc.
• Rules :
• The name should begin with an uppercase or a lowercase
alphabet or an underscore sign (_). This may be followed by
any combination of characters a–z, A–Z, 0–9 or underscore
(_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it
short and meaningful).
• It should not be a keyword or reserved word.
• We cannot use special symbols like !, @, #, $, %, etc., in
identifiers.
• Note : Python is a case sensitive as it treats upper and
lower case characters differently.
Literals / Values
• Literals are data items that have a fixed or
constant value.
• Python allows several kind of literals. These
are :
• String Literals : A string literal is a sequence of
characters surrounded by quotes(single or
double quotes or triple quotes). String literals
can be single line or multiline strings.
– Single line strings must terminate in one line i.e.
the closing quotes should be on the same line as
that of the opening quotes.
• Eg : text1=“Hello world”
• Multiline strings: are strings which spreads
across multiple lines. With single and double
quotes, each line other that the concluding
line has an end character as \(backslash) but
with triple quotes, no backslash is needed at
the end of intermediate lines.
• Eg : text2=“hello\
• World” ------------------------ Multiline string
• Eg : text3=‘’’ Hello
• World ’’’ -------------no backslash needed
Numerical Literals
• Numerical literals are numeric values and these can be :
a) int(signed integer): often called just integers or ints, are positive or negative whole numbers with
no decimal point. The integer literals can be written in.
• Decimal Integer: consists of set of digits 0 to 9 preceded by an optional – or + sign.
Commas, spaces and non digits characters are not allowed between digits of
integer constants.
• Example
• 456
• 017
• +124567
• -876

• Octal Integer Constant: It consists of any combination of digits between 0 to 7
with leading 0.

• Example

• 01
• 078- wrong
• 0465
• 07564

• Hexadecimal Integer Constant: It consists of any
combination of digits between 0 and 9 and A to F
or a to f. It must begin with 0x or 0X.

• Example

• 0x5
• 0X9A
• 0x7FF
• 0Xabc8
Floating point literals
• Number containing fraction parts are called as
real or floating point literals. The real can also be
expressed in exponential or scientific notation.
These can be written in fractional form.
– Eg. -13.0, .75,7., 0.17E5,3.E3,.6E4 etc.
• Boolean Literals : A Boolean literal is used to
represent one of the two boolean values i.e.
True(Boolean true) or False(Boolean false). A
boolean literal can either have value as True or as
False.
• Special Literal :
– None – python has one special literal, which is none.
The None literal is used to indicate absence of value.
Python can also store literal collection in the form of
tuples and lists etc.
Escape Sequence Character
• An escape sequence is a special
character used in the form
of backslash(\) followed by
a character that is required.
• These characters are used to
represent whitespace.
• Whitespace gives characters like
space, tab, formfeed, and vertical
tab.
Escape sequence Description Example Output
\n New line print("Hello\nWorld") Hello
World

\t Horizontal tab print("Hello\tWorld") Hello World

\' Single quote print("Hello \'World\' ") Hello 'World'

\" Double quote print("Hello \"World\" ") Hello "World"

\\ Backslash print("Hello \\World") Hello \World

Oct and Hex To print octal and hexa no x = oct(42) 0o52


print(x) 0x2a
x = hex(42)
print(x)
Data Type
• Data type identifies the type of data values a
variable can hold and the operations that can be
performed on that data.
• Types :
– Numbers : integer, floating point, complex
– Boolean type :Boolean
– Text type : str
– Sequences type: range, Lists, Tuples
– Set types : Set
– None type:None
– Mappings type: Dictionaries
• Number Number data type stores numerical
values only. It is further classified into three
different types: int, float and complex.

Type/ Class Description Examples

Int Integer numbers -12,-3.0,125,2

Float Real or floating -2.04,4.0,14.23

Complex Complex numbers 3+4J,2-2J


• Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True value is non-zero, non-null and
non-empty. Boolean False is the value zero.
• EXAMPLES :
• >>> num1 = 10
• >>> type(num1)
• <class 'int'>
• >>> num2 = -1210
• >>> type(num2)
• <class 'int'>
• >>> var1 = True
• >>> type(var1)
• <class 'bool'>
• >>> float1 = -1921.9
• >>> type(float1)
• <class 'float'>
• >>> float2 = -9.8*10**2
• >>> print(float2, type(float2))
• -980.0000000000001
• <class 'float'>
• var2 = -3+7.2j
• >>> print(var2, type(var2))
• (-3+7.2j) <class 'complex'>
• Variables of simple data types like integers, float,
Boolean, etc., hold single values. But such variables are
not useful to hold a long list of information.
• For this, Python provides data types like tuples, lists,
dictionaries and sets.

• Note : # To verify the type of any object in Python, use


the type() function:
• >>> type(10)
• <class 'int'>
• >>> a=11
• >>> print(type(a))
• <class 'int'>
• String:
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example: print("hello").
Suppressing Special Character:
• Specifying a backslash (\) in front of the quote character in a string “escapes” it
and causes Python to suppress its usual special meaning. It is then interpreted
simply as a literal single quote character.
• Eg : print("mrcet is an autonomous (\') college")
• Eg : print('a\
• ....b')
• O/P : a....b
• Eg : print('a\
• b\
• c')
• O/P : abc
• Eg : print('a \n b')
• O/P : a
• b
• To combine both text and a variable, Python uses the “+” character:
• Example
• x = "awesome"
• print("Python is " + x)
• You can also use the + character to add a variable to another
variable:
• Example
• x = "Python is "
• y = "awesome"
• z=x+y
• print(z)
• Expressions:
• An expression is a combination of values, variables, and operators.
An expression is evaluated using assignment operator.
• Examples: Y=x + 17
• >>> x=10
• >>> z=x+20
• >>> z
• 30

You might also like