0% found this document useful (0 votes)
76 views46 pages

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

VIT Bhopal University

Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Introduction to Problem Solving and Programming


Course Code: CSE 1021

By:
Ramraj Dangi
Chapter 2: Python Data, Expressions and Statements

– Python interpreter and interactive mode


– values and types
– variables, expressions, statements, tuple assignment,
– precedence of operators, comments
– modules and functions, function definition and use, flow of execution, parameters and
arguments.
What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting language.

Python is designed to be highly readable. It uses English keywords frequently, where as


other languages use punctuation, and it has fewer syntactic constructions than other
languages.

It was created by Guido van Rossum, and released in 1991.

Python is simpler to use, available on Windows, Mac OS X, and Unix operating systems,
and will help you get the job done more quickly.
Python Features
1) Easy to Learn and Use
Python is easy to learn- compared to other PL. Its syntax is straightforward - same as the English language. No use of the
semicolon or curly-bracket, the indentation defines the code block.

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.

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.
Python Features Cont.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website www.python.org. 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. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

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

8) 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.
Python Features Cont.
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. It can embed other language into our code.
Usage of Python

The various areas of Python use are given below. Some Research Areas

● Software Development ● Artificial Intelligence


● 3D CAD Applications ● Data Science
● Web Applications ● Machine Learning
● Desktop Applications ● Computer Vision or Image Processing
● Console-based Applications Applications.
● Mobile Applications ● Speech Recognitions
● Data Mining
Python Programming

● Beginner level — IDLE (or Online Python Editors) is perfect choice for the first steps in python
language. PyCharm is also good but takes the help of some experienced person while using this.
● Intermediate level— PyCharm, Sublime, Atom, Vs Code.
● Advanced level— PyCharm, Vim, Emacs, Sublime, Atom, Vs Code.

What’s Your End Goal?


● Web development — PyCharm Professional, VS Code Pycharm
● Data Science — Spyder, Jupyter Notebook, PyCharm Professional
● Scripting — Sublime, Atom, PyCharm Community, Eclipse + PyDev
● QA — Sublime, Atom, PyCharm Community, Jupyter Notebook
Chapter 2: Python Data, Expressions and Statements

– Python interpreter and interactive mode


– values and types
– variables, expressions, statements, tuple assignment,
– precedence of operators, comments
– modules and functions, function definition and use, flow of execution, parameters and
arguments.
Values in Python

● A value is one of the fundamental things — like a letter or a number — that a program
manipulates.
● These values can belong to different data types.

Assigning Values to a Variable

● Python variable do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign value to a variable.
● The assignment operator (=) is used to assign values to the variables.

Ex. a = 10, here ‘a’ is variable name and ‘10’ is value assigned to the variable ‘a’.
Type Checking in Python

Actual type of the variable can be checked by type(<variable_name>),


Ex. 3
a= 3
type(a)
aa
Integer type

name = ‘Saksham’
type(name)
String type
Chapter 2: Python Data, Expressions and Statements

– Python interpreter and interactive mode


– values and types
– variables, expressions, statements, tuple assignment,
– precedence of operators, comments
– modules and functions, function definition and use, flow of execution, parameters and
arguments.
Python Identifier

Python identifiers refer to a name used to identify a variable, function, module,


class, or other objects.
Constant

● Fixed values such as numbers, letters, and strings are called “constants”
- because their value does not change
● Numeric constants are as you expect
● String constants use single-quotes (') or double-quotes (")

Example:
● >>> print 123
123
● >>> print 98.6
98.6
● >>> print 'Hello world'
Hello world
Variable

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.
Variable or Identifier Naming

● Variables are the example of identifiers. An Identifier is used to identify the literals used in
the program. The rules to name an identifier are given below.
● The first character of the variable must be an alphabet or underscore ( _ ).
● 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).
● Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
● Identifier name must not be similar to any keyword defined in the language.
● Identifier names are case sensitive; for example, my name, and MyName is not the same.
● Examples of valid identifiers: a123, _n, n_9, etc.
● Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values

● Python does not bind us to declare a variable before using it in the


application. It allows us to create a variable at the required time.
● We don't need to declare explicitly variable in Python. When we assign any
value to the variable, that variable is declared automatically.
● The equal (=) operator is used to assign value to a variable.
Declaring Variable and Assigning Values

In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are
used to denote objects by that name.
Let's understand the following example
a = 50
In the image, the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
b=a

The variable b refers to the same object that a points to because Python does not create another object.
Declaring Variable and Assigning Values

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100

Python manages memory efficiently if we assign the same variable to two different values.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length can have
uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_). Consider the following
example of valid variables names.
name = "Devansh"
age = 20
marks = 80.50

print(name)
print(age)
print(marks)
Output:
Devansh
20
80.5
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as
multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or
assigning multiple values to multiple variables. Consider the following example.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
Multiple Assignment
2. Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
Python Variable Types
There are two types of variables in Python - Local variable and Global variable. Let's understand the following variables.

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 Output:
print("The sum is:", c)
# Calling a function The sum is: 50
add()
Local Variable
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

We tried to use local variable outside their scope; it threw the NameError.
Global Variable
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. Let's understand the following example.
Example -
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
Output:
print(x)
# modifying a global variable 101
x = 'Welcome To Class' Welcome To Class
print(x) Welcome To Class

mainFunction()
print(x)
Global Variable

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.
Reserved Words Or Keywords

● You can not use reserved words as variable names / identifiers.


● Keywords define the language’s rules and structure.
● Python has thirty-one keywords:
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Expression

● An expression is a combination of values, variables, and operators. If you type an expression on


the command line, the interpreter evaluates it and displays the result.
● The evaluation of an expression produces a value, which is why expressions can appear on the
right hand side of assignment statements. A value all by itself is a simple expression, and so is a
variable.
● Confusingly, evaluating an expression is not quite the same thing as printing a value.
● Example:
a=1+1
print a
Statement in Python

● A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
● When you type a statement on the command line, Python executes it and displays the result, if
there is one. The result of a print statement is a value. Assignment statements don’t produce a
result.
● A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
● Example:
print 1 1
x=2 2
print x
Chapter 2: Python Data, Expressions and Statements

– Python interpreter and interactive mode


– values and types
– variables, expressions, statements, tuple assignment,
– precedence of operators, comments
– modules and functions, function definition and use, flow of execution, parameters and
arguments.
Operators

● Arithmetic Operators
● Comparison Operators
● Logical Operators
● Bitwise Operators
● Identity Operators
● Operator Precedence
● Augmented Assignment Operators
Arithmetic Operator
+ (unary) +a Unary Positive In other words, it doesn’t really do anything. It mostly
exists for the sake of completeness, to complement
Unary Negation.

+ (binary) a+b Addition Sum of a and b

- (unary) -a Unary Negation Value equal to a but opposite in sign

- (binary) a-b Subtraction b subtracted from a

* a*b Multiplication Product of a and b

/ a/b Division Quotient when a is divided by b.


The result always has type float.

% a%b Modulo Remainder when a is divided by b


Arithmetic Operator

// a // b Floor Division (also Quotient when a is divided by b, rounded to the next


called Integer Division) smallest whole number

** a ** b Exponentiation a raised to the power of b


Comparison Operator

== a == b Equal to True if the value of a is equal to the value of b


False otherwise

!= a != b Not equal to True if a is not equal to b, False otherwise

< a<b Less than True if a is less than b, False otherwise

<= a <= b Less than or equal to True if a is less than or equal to b, False otherwise

> a>b Greater than True if a is greater than b, False otherwise

>= a >= b Greater than or equal to True if a is greater than or equal to b, False otherwise
Logical Operator
True if x is False
False if x is True
not not x (Logically reverses the sense of x)

True if either x or y is True


or x or y False otherwise

True if both x and y are True


and x and y
False otherwise
Bitwise Operator
& a&b bitwise AND Each bit position in the result is the logical AND of the bits in
the corresponding position of the operands. (1 if both are 1,
otherwise 0.)

| a|b bitwise OR Each bit position in the result is the logical OR of the bits in
the corresponding position of the operands. (1 if either is 1,
otherwise 0.)

~ ~a bitwise negation Each bit position in the result is the logical negation of the bit
in the corresponding position of the operand. (1 if 0, 0 if 1.)

^ a^b bitwise XOR Each bit position in the result is the logical XOR of the bits in
(exclusive OR) the corresponding position of the operands. (1 if the bits in the
operands are different, 0 if they are the same.)

>> a >> n Shift right n places Each bit is shifted right n places.

<< a << n Shift left n places Each bit is shifted left n places.
Identity Operator

Python provides two operators,


● is
● is not,
that determine whether the given operands have the same identity—that is, refer to the same object.

>>> x = 1001 >>> a = 'I am a string'


>>> y = 1000+1 >>> b = a
>>> print(x, y)
1001 1001 >>> a is b
>>> id(x) True >>> id(a)
>>> x == y 60307920 >>> a == b 55993992
True >>> id(y) >>> id(b)
True 55993992
>>> x is y 60307936
False
Membership Operator

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.

● In :- It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).

● not in :- It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Operator Precedence

When we string operators together - Python must know which one to do first. This is called
“operator precedence”.
Here is the order of precedence of the Python operators you have seen so far,
from lowest to highest:
1. Boolean (or, and, not)
2. Comparison (==, !=, <, <=, >, >=)
3. Identity (is, is not)
4. Bitwise (|, ^, &, <<, >>)
5. Arithmetic (+, -,*, /, //, %,+x, -x, ~x(bitwise negation), **)
Order of Operation

When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. Python follows the same precedence rules for its mathematical operators that
mathematics does.

1. Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Ex. 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27.
3. Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is
-1, not 1 (remember that in integer division, 2/3=0).
4. Operators with the same precedence are evaluated from left to right.
Comments in Python

To add notes to your programs to explain in natural language what the program is doing. These notes are called
comments, and they are marked with the ‘#’ symbol.

Everything from the ‘#’ to the end of the line is ignored. It has no effect on the program. The message is intended
for the programmer or for future programmers who might use this code.
Single-Line Comments

Ex.
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60

OR
percentage = (minute * 100) / 60 # caution: integer division
Comments in Python
Multi-Line Comments - Python doesn't have explicit support for multi-line comments but we can use hash #
character to the multiple lines. For example -

1. # we are defining for loop


2. # To iterate the given list.
3. # run this code.
Basic Syntax of Python

Indentation in Python
Indentation is the most significant concept of the Python programming language. Improper use
of indentation will end up "IndentationError" in our code.

Indentation is nothing but adding whitespaces before the statement when it is needed. Without
indentation Python doesn't know which statement to be executed to next. Indentation also
defines which statements belong to which block. If there is no indentation or improper
indentation, it will display "IndentationError" and interrupt our code.
Basic Syntax of Python

Indentation in Python
Data Types in Python

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 Output:
print(type(a)) <type 'int'>
print(type(b)) <type 'str'>
<type 'float'>
print(type(c))
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. Number
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

You might also like