Unit 2 Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

What is Python

Python is a general-purpose programming language that is becoming more and


more popular for
• performing data analysis,
• automating tasks,
• learning data science,
• machine learning, etc
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. 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.
Application Area
• Web and Internet development: Python is used on the server side to create web
applications.
• Software development: Python is used to create GUI applications, connecting
databases, etc.
• Scientific and Numeric applications: Python is used to handle big data and
perform complex mathematics.
• Education: Python is a great language for teaching programming, both at the
introductory level and in more advanced courses.
• Desktop GUIs: The Tk GUI library2 included with most binary distributions
of Python is used extensively to build desktop applications.
• Business Applications: Python is also used to build ERP and ecommerce
systems.
Features
Python is characterized by many features. Let’s examine a few of them here:
• Simple – Compared to many other programming languages, coding in Python
is like writing simple strict English sentences. In fact, one of its oft-touted
strengths is how Python code appears like pseudo-code. It allows us to
concentrate on the solution to the problem rather than the language itself.
• Easy to Learn – As we will see, Python has a gentler learning curve
(compared to languages like C, Java, etc.) due to its simple syntax.
• Free and Open Source – Python and the majority of supporting libraries
available are open source and generally come with flexible and open licenses. It
is an example of a FLOSS(Free/Libré and Open Source Software). In layman
terms, we can freely distribute copies of open source software, access its source
code, make changes to it, and use it in new free programs.
• High-level – Python is a programming language with strong abstraction from
the details of the underlying platform or the machine. In contrast to low-level
programming languages, it uses natural language elements, is easier to use,
automates significant areas of computing systems such as resource allocation.
This simplifies the development process when compared to a lower-level
language.
• Interpreted – A programming language can be broadly classified into two
types viz. compiled or interpreted. – A program written in a compiled language
like C or C++ requires the code to be converted from the original language (C,
C++, etc.) to a machine-readable language (like binary code i.e. 0 and 1) that is
understood by a computer using a compiler with various flags and options. This
compiled program is then fed to a computer memory to run it. – Python, on
other hand, does not require compilation to machine language. We directly run
the program from the source code. Internally, Python converts the source code
into an intermediate form known as byte code and then translates this into the
native language of the underlying machine. We need not worry about proper
linking and the loading into memory. This also enables Python to be much more
portable, since we can run the same program onto another platform and it works
just fine! – The ’Python’ implementation is an interpreter of the language that
translates Python code at runtime to executable byte code
First Python Program

o Python provides us the two ways to run a program: Using Interactive


interpreter prompt
o Using a script file

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at the
interactive prompt. It is preferable in the case where 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.

it will open the following prompt where we can execute the Python statement
and check their impact on the console.

After writing the print statement, press the Enter key.


Here, we get the message "Welcome to the world of programming" printed
on the console.
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".

Indentation

Whitespaces are important in Python. Whitespace at the start of a line is called


indentation. It is used to mark the start of a new code block. A block or code
block is a group of statements in a program or a script. Leading spaces at the
beginning of a line are used to determine the indentation level, which in turn is
used to determine the grouping of statements. Also, statements which go
together must have same indentation level. A wrong indentation raises the error.
Python Variables

A variable is the name given to a memory location. A value-holding Python


variable is also known as an identifier.

Since Python is an infer language that is smart enough to determine the type of
a variable, we do not need to specify its type in Python.

Variable names must begin with a letter or an underscore, but they can be a
group of both letters and digits.

Identifiers are things like variables. An Identifier is utilized to recognize the


literals utilized in the program.

Rules to write identifiers

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might
be a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-
9).
o White space and special characters (!, @, #, %, etc.) are not allowed in
the identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the
language.
o Names of identifiers are case-sensitive; for instance, my name, and
MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Data Types

Every value has a datatype, and variables can hold values. Python is a
powerfully composed language; consequently, we don't have to characterize the
sort of variable while announcing it. The interpreter binds the value implicitly to
its type. a=5
Python has four basic data types:
• Integer
• Float
• String
• Boolean
Integer
An integer can be thought of as a numeric value without any decimal. In fact, it
is used to describe any whole number in Python such as 7, 256, 1024, etc.
Float
A float stands for floating point number which essentially means a number with
fractional parts. It can also be used for rational numbers, usually ending with a
decimal such as 6.5, 100.1, 123.45, etc.
Boolean
This built-in data type can have one of two values, True or False. We use an
assignment operator = to assign a boolean value to variables in a manner similar
to what we have seen for integer and float values.
String
A string is a collection of alphabets, numbers, and other characters written
within a single quote ' or double quotes ". In other words, it is a sequence of
characters within quotes.
#Program to demonstrate data types
Keywords

Python keywords are unique words reserved with defined meanings and
functions that we can only apply for those functions.

Python contains thirty-five keywords in the most recent version.

False await else import Pass

None break except in Raise

True class finally is Return

and conti for lambda Try


nue

as def from nonlocal While

assert del global not With

async elif if or Yield


Operators

Operators are constructs or special symbols which can manipulate or compute


the values of operands in an expression. In other words, they are used to
perform operations on variables and values. Python provides a bunch of
different operators to perform a variety of operations.

An operand is a value that a given operator is applied to.

• Example: 4+(3*k) +, * are operator and 4,3,k are operands

Different forms of operator

• Unary Operator: – Unary arithmetic operators perform mathematical


operations on one operand only. The „+‟ and „-„‟ are two unary operators. –

Example:

>>> x = -5 #Negates the value of X

>>> x -5

• Binary operator: – A Binary operator operates on two operands –

Example:

>>> 3 + 10

>>>13 >>> 10 – 7 >>> 3

1. Arithmetic operators

Arithmetic operators are used with numerical values to perform the common
mathematical operations.
Example

print("Arithmetic Operator")

a=10 b=5

print("Addition:",a+b)

print("Subtraction:",a-b)

print("Multiplication:",a*b)

print("Division:",a/b)

print("Floor Division:",a//b)

print("Modulus:",a%b)

print("Exponent",a**b)

2. Relational operator

• Relational operators are also called as Comparison operators

• It is used to compare values.

• It either returns True or False according to condition.

Example:

print("Relational Operator")
a=10
b=5
print(a>b)
print(a=b)
print(a<=b)

3. Logical operator
• Logical operator are typically used with Boolean(logical) values.
• They allow a program to make a decision based on multiple condition.

Example
print("Logical Operator")
print(10<20) and (10<20))
print(10<5 or 10<20)
print(not(10 <20))
4. Bitwise operator
Bitwise operators act on operands as if they are string of binary digits. It
operates bit by bit.
5. Special operator
• Python offers some special operators like identity operator and the
membership operator.
• Identity Operator: – is and is not are the identity operator

Example
a1=5
b1=5
a2="Hello"
b2="Hello"
a3=[1,2,3]
b3=[1,2,3]
print(a1 is not b1)
print(a2 is b2)
print(a2 is b3)
6. Ternary operator
The ternary operator determines if a condition is true or false and then returns
the appropriate value in accordance with the result. The ternary operator is
useful in cases where we need to assign a value to a variable based on a simple
condition, and we want to keep our code more concise — all in just one line of
code. It’s particularly handy when you want to avoid writing multiple lines for
a simple if-else situation.
Syntax of Ternary Operator in Python

Syntax: [on_true] if [expression] else [on_false]


expression: conditional_expression | lambda_expr

Example:
# Program to demonstrate conditional operator
a, b = 10, 20

# Copy value of a in min if a < b else copy b


min = a if a < b else b

print(min)

You might also like