100% found this document useful (1 vote)
168 views

Unit 1

The document provides an introduction to Python programming, covering its history, features, data types, and basic input/output operations. It explains various data types such as numeric, sequence, boolean, set, and dictionary, along with rules for creating variables and operators used in Python. Additionally, it includes examples of arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators.
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
100% found this document useful (1 vote)
168 views

Unit 1

The document provides an introduction to Python programming, covering its history, features, data types, and basic input/output operations. It explains various data types such as numeric, sequence, boolean, set, and dictionary, along with rules for creating variables and operators used in Python. Additionally, it includes examples of arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators.
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/ 69

Sanjivani Rural Education Society’s

Sanjivani College of Engineering, Kopargaon-423 603


Department of Computer Engineering

ESIT135: PROBLEM SOLVING USING PYTHON

By,
Ms. Swapnali S. Gawali,
Asst. Prof. Computer Engineering
Sanjivani College of Engineering, Kopargaon
UNIT-I CONTENT

2
WHAT IS PYTHON?

• Python is a popular high-level, interpreted programming language


used in various applications
• Python is an easy language to learn because of its simple syntax
• Python can be used for simple tasks such as plotting or for more
complex tasks like machine learning

3
HISTORY OF PYTHON

• Created in 1990 by Guido van Rossum


• Named after Monty Python
• First public release in 1991
• comp.lang.python founded in 1994
• Open source from the start
• Considered a scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Used by Google from the beginning
• Increasingly popular

4
FEATURES OF PYTHON

2. Easy to 3. Easy to
1. Free and code Read 4. Object-Oriented
Open Source Language

10. Large Standard 5. GUI Programming


Library Features of Python Support

6. High-Level
9. Integrated and Language
Interpreted
8. Easy to
7. Portable
Debug

5
VALUES

• A value is one of the basic things a program work with, like


letter or a number.
• Example:
• 2 – Integer
• 42.0 – Floating Point
• ‘Hello’ – String
• We use variable to stored value.

6
DATA TYPE

• A data type defines the type of data stored in a variable.


• Python is a dynamically typed language, so we do not need to defined data types
while declaring.
• Data types are the classification or categorization of data items.
Data Type

Numeric Dictionary Boolean Set Sequence

Integer Complex Float Strings Tuple


Number List

7
NUMERIC DATA TYPE

• It represents data that has a numeric value.


• Three Categories:
• Integer: int
• Float: float
• Complex Number: complex
• Integer: It contains negative and positive whole numbers. (without decimal
or fraction) Example:101,-319,20
• Float: It is real number with floating-point. Example: 1.5,4.5,3.5
• Complex Number: It is specified as (real part)+(imaginary part)j
example: -2+6j
8
SEQUENCE TYPE

• It is the ordered collection of similar or different data


types.
• Sequences used to stored multiple values in an organized
and efficient fashion.
• Three Categories:
• String: ' '," ",''' '''
• List: [ ]
• Tuple: ()
• String: It is a collection of one or more characters put in
‘single quote’, “double quote” and ‘‘‘ Triple quote”’

9
CONTINUE..

• List: It is like a array, which is ordered collection of data.


• It contains data of different types.
• The items are separated by comma(,) and enclosed with
in square bracket[].
• Example:A
list = [1,2,3,4,5,6]
fruit=["Apple", "mango", "banana"]

10
CONTINUE..

• Tuple: It is Like list, it also contains data of different types.


The items are separated by comma(,) and enclosed with in
square bracket().
• Tuple is immutable.
• Example:
fruit=("Apple", "mango", "banana")
tuple= (1,2,3,4,5)

11
BOOLEAN

• It provides two built in values, True and False.


• It determine the given value is true or false.
• It is denoted by class ' bool '.
• It also represented by ' 0 ' or ' 1 '
Example:
print(11>9)
a=200, b=33
print(a<b)

12
SET

• It is unordered collection of the data type.


• It is iterable, mutable and has unique elements.
• In it order of element is undefined.
• It is created by using built-in set() function, or a sequence of
elements is passed in curly braces and separated by comma.
• Example:
my_set = {1,2,3}
myset = {1.0, ' Hi ', (1,2,3,4)}

13
DICTIONARY

• It is an unordered set of a key-value pair of items.


• It is like an associative array or hash table where each key stores
a specific value.
• Key can store primitive data types.
• Value is an arbitrary Python Object.
• Example:
thisdict = {' brand ' : ' Maruti ', ' model ' : ' Swift ', ' year ' : 2000}

14
VARIABLES

• Variables are containers for storing data values.


• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment we first assign a value to it.
• x=5
y = "John"
print(x) 5
print(y) John
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
• String variables can be declared either by using single or double quotes: ‘John’ or”John”

15
RULES FOR CREATING VARIABLES IN PYTHON

• Following are rules for creating variables in Python


1. A variable name must start with a letter or the underscore character.
• example: a, name, _name_
2. A variable name cannot start with a number.
• Example: This is not allowed: 12a
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
• Example: Name, a12
4.Variable names are case-sensitive (name, Name and NAME are three different variables).
• Example: This A is different than a
5. The reserved words(keywords) cannot be used naming the variable.
• Example: This word not allowed
and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from,
global, if, import, in, is, not, or, pass, print, raise, return, try, while
16
BASIC INPUT/OUTPUT IN PYTHON

• Input is any information provided to the program


– Keyboard input
– Mouse input
– File input
– Sensor
input (microphone, camera, photo cell, etc.)
• Output is any information (or effect) that a program produces:
– sounds, lights, pictures, text, motion, etc.
Output( on a screen, in a file, on a disk or tape, etc.)

17
OUTPUT FUNCTION

• print(): Used to print output.


• Example 1:
print ('Hello World’) Output
Hello World
print ("Sanjivani") Sanjivani
College of Engineering
print('''College of Engineering''')

18
OUTPUT FUNCTION (CONTINUE)

• Example 2:
name='Sonal’
rollno=10 Output
Name is Sonal
print('Name is ',name) Roll no is 10
print('Roll no is ',rollno)
Example 3:
name='Sonal’
Output
rollno=10 Name is Sonal Roll no is 10
print('Name is ',name, 'Roll no is ',rollno)
19
OUTPUT FUNCTION (CONTINUE)

• Example 4:
name='Sonal’
Output
rollno=10 Name is Sonal. Roll no is 10.
print(f'Name is {name}. Roll no is {rollno}.')

20
OUTPUT FUNCTION (CONTINUE)

• Syntax of print()
print(object(s), sep=separator, end=end, file=file, flush=flush)

Parameter Description
object(s) Any object, 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 is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
file Optional. An object with a write method. Default is sys.stdout
flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False

21
OUTPUT FUNCTION (CONTINUE)

• sep parameter: is used to specify the separator


between the strings.
• Example: Output
Name is Sonal. Roll no is 10
name='Sonal’
rollno=10
print(f'Name is {name}',f' Roll no is {rollno}',sep='.')

22
OUTPUT FUNCTION (CONTINUE)

• end parameter: . Specify what to print at the end.


• Example:
name='Sonal’ Output
Name is Sonal. Roll no is 10.
rollno=10
print(f'Name is {name}.',end=' ‘)
print(f' Roll no is {rollno}.')

23
INPUT FUNCTION

• Python input() function is used to take user input.


• By default, it returns the user input in form of a string.
• Syntax:
input('prompt message’)
Output
• Example: Enter your nameSonal
name=input('Enter your name’) Name is Sonal.<class 'str'>

print(f'Name is {name}.’)
print(type(name))

24
INPUT FUNCTION

• Example:
name=input('Enter your name’)
Output
print(f'Name is {name}.’) Enter your nameSonal
print(type(name)) Name is Sonal.
rollno=int(input('Enter roll no’)) <class 'str’>
Enter roll no10
#int() use to convert string to integer value Roll no is 10.
print(f'Roll no is {rollno}.’) <class 'int'>
print(type(rollno))

25
OPERATORS AND OPERANDS

• Operators:Operators are symbol used to perform operations on variables


and values.
• Operands:
The values or variables that an operator acts on are called operands.
• A sequence of operands and operators is called expression.
Example: a+b-5 Operator

A+B-5

Operands

26
DIFFERENT OPERATOR IN PYTHON

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators

27
ARITHMETIC OPERATORS

1. Arithmetic operators are used with numeric values to perform common


mathematical operations:
2. Assume x=10, y=5
Operator Name Example Output
+ Addition print(x+y) 15
- Subtraction print(x-y) 5
* Multiplication print(x*y) 50
/ Division print(x/y) 2.0
% Modulus print(x%y) 0
** Exponentiation print(x**y) 100000
// Floor Division x//y 2

28
PROGRAM

a=10
b=20
c=a+b
print(“Addition is ”,c) Output:
c=a-b Addition is 30
Subtraction is -10
print(“Subtraction is ”,c) Multiplication is 200
Division is 0.5
c=a*b
print(“Multiplication is ”,c)
c=a/b
print(“Division is ”,c)
29
ASSIGNMENT OPERATORS

• Assignment operators are used to assign values to variables:


Operator Description

= Assign value of right side of expression to left side operand

+= Add and Assign: Add right side operand with left side operand and then assign to left operand

-= Subtract AND: Subtract right operand from left operand and then assign to left operand: True if both operands
are equal
*= Multiply AND: Multiply right operand with left operand and then assign to left operand
/= Divide AND: Divide left operand with right operand and then assign to left operand
%= Modulus AND: Takes modulus using left and right operands and assign result to left operand
//= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand

**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand

30
PROGRAM

a=10
b=20
print("a is ",a)
print("b is ",b)
a += 1 Output:
a is 10
print("Add 1 to a ",a) b is 20
b -= 1 Add 1 to a 11
Subtract 1 from b 19
print("Subtract 1 from b ",b) a square is 121
a **= 2
print("a square is ", a)

31
COMPARISON OPERATORS

• Comparison operators are used to compare two values:

Operator Name Example


== Equal a==b
!= Not Equal a!=b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a>=b
<= Less than or equal to a<=b

32
PROGRAM

x=10
y=20
print(x==y)
Output:
print(x!=y) False
print(x<y) True
print(x>y) True
False
print(x<=y)
True
print(x>=y) False

33
LOGICAL OPERATORS

• Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are x<5 and x<10
true
or Returns True if one of the statements x<5 or x<4
is true
not Reverse the result, returns False if the not(x<5 and x<10)
result is true

34
PROGRAM

x=10
y=20
print(x==y and x<y) Output:
False
print(x!=y or x>y) True
False
print(not(x<y))

35
IDENTITY OPERATORS

• Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location:

Operator Description Example


is Returns true if both variables are a is y
the same object
is not Returns true if both variables are a is not y
not the same object

36
PROGRAM

x=10
y=10 Output:
print(x is y) True
False
print(x is not y)

37
MEMBERSHIP OPERATORS

• Membership operators are used to test if a sequence is


presented in an object:

Operator Description Example


in Returns True if a sequence with the specified a in b
value is present in the object
not in Returns True if a sequence with the specified a not in b
value is not present in the object

38
PROGRAM

x='sanjivani’
print('s' in x)
print('s' not in x) Output:
True
print('S' in x) False
print('S' not in x) False
y='anji’ True
True
print(y in x) False
print(x in y)

39
BITWISE OPERATOR

• In Python, bitwise operators are used to performing bitwise calculations on integers.


• The integers are first converted into binary and then operations are performed on bit by bit, hence the
name bitwise operators.
• Then the result is returned in decimal format.
OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<


40
BITWISE AND OPERATOR

• Bitwise AND operator Returns 1 if both the bits are 1 else 0.


• Example:
a=10= 1010 (Binary)
b=4=0100 (Binary)
a&b = 1010
&
0100
=0000(Binary)
=0 (Decimal)

41
BITWISE OR OPERATOR

• Bitwise or operator Returns 1 if either of the bit is 1 else 0.


• Example:
a=10= 1010 (Binary)
b=4=0100 (Binary)
A|b = 1010
|
0100
=1110(Binary)
=14 (Decimal)

42
BITWISE XOR OPERATOR

• Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else
returns false.
• Example:
a=10= 1010 (Binary)
b=4=0100 (Binary)
a^b = 1010
^
0100
=1110(Binary)
=14 (Decimal)
43
PROGRAM

a = 10
b=4

print("a & b =", a & b) Output:


a&b=0
a | b = 14
print("a | b =", a | b) a ^ b = 14

print("a ^ b =", a ^ b)

44
BITWISE RIGHT SHIFT

• Bitwise right shift: Shifts the bits of the number to the right and fills
0 on voids left( fills 1 in the case of a negative number) as a result.
• Similar effect as of dividing the number with some power of two.
• Example:
a=10= 0000 1010 (Binary)
a>>1=0000 0101 = 5
Example 2:
a= -10 = 1111 0110
a>>1 = 1111 1011 = -5

45
BITWISE LEFT SHIFT

• Bitwise left shift: Shifts the bits of the number to the left and fills 0
on voids right as a result.
• Similar effect as of multiplying the number with some power of two.
• Example:
a=10= 0000 1010 (Binary)
A<<1= 0001 0100 = 20
Example 2:
a= -10 = 1111 0110
A<<1 = 1110 1100 = -20

46
PROGRAM

a = 10
b = -10
print("a >> 1 =", a >> 1) Output:
print("b >> 1 =", b >> 1) a >> 1 = 5
b >> 1 = -5
a=5 a << 1 = 10
b = -10 b << 1 = -20

print("a << 1 =", a << 1)


print("b << 1 =", b << 1)

47
STATEMENT

• A statement is an instruction that the Python interpreter can execute.


• Python statement ends with the token NEWLINE character. It means each
line in a Python script is a statement.
• There are mainly four types of statements in Python,
• print statements: print(“hello”)
• Assignment statements: a=100
• Conditional statements: if (a>10):
Print(“a is greater than 10”)
• Looping statements.: for x in range(6):
print(x)
48
MULTI-LINE STATEMENTS

Python statement ends with the token NEWLINE character.


But we can extend the statement over multiple lines using line continuation
character (\).
This is known as an explicit continuation.

add=20+30+\
50+60+\
90
print(add)
Output: 250

49
IMPLICIT CONTINUATION:

We can use parentheses () to write a multi-line statement.


We can add a line continuation statement inside it.
Whatever we add inside a parentheses () will treat as a single statement even it is
placed on multiple lines.

addition = (10 + 20 +
30 + 40 +
50 + 60 + 70)
print(addition)
# Output: 280

50
COMPOUND STATEMENTS

• Compound statement contain (groups of) other statements; they affect or control the execution of those
other statements in some way.
• The compound statement includes the conditional and loop statement.
• if statement: t is a control flow statement that will execute statements under it if the condition
is true. Also known as a conditional statement.
• while statement: The while loop statement repeatedly executes a code block while a particular
condition is true. Also known as a looping statement.
• for statement: Using for loop statement, we can iterate any sequence or iterable variable. The
sequence can be string, list, dictionary, set, or tuple. Also known as a looping statement.
• try statement: specifies exception handlers.
• with statement: Used to cleanup code for a group of statements, while the with statement
allows the execution of initialization and finalization code around a block of code.
51
SIMPLE STATEMENTS

• Python has various simple statements for a specific purpose.


1. Expression Statement
2. The pass statement
3. The del statement
4. The return statement
5. The import statement
6. The continue and break statement

52
EXPRESSION IN PYTHON

• A combination of operands and operators is called an expression.


• The expression in Python produces some value or result after being interpreted by
the Python interpreter.
• Example:
r = a+b
res =10+a
result = 20+30
• An expression in Python can contain identifiers, operators, and operands.
• An identifier is a name that is used to define and identify a class, variable, or
function in Python.
53
TYPES OF EXPRESSION IN PYTHON

1.Constant Expressions
2.Arithmetic Expressions
3.Integral Expressions
4.Floating Expressions
5.Relational Expressions
6.Logical Expressions
7.Combinational Expression

54
CONSTANT EXPRESSION

• A constant expression in Python that contains only constant values is known


as a constant expression.
• In a constant expression in Python, the operator(s) is a constant.
• A constant is a value that cannot be changed after its initialization.
• Example:
a = 20 +10

55
ARITHMETIC EXPRESSION

• An expression in Python that contains a combination of arithmetic operators,


operands, and sometimes parenthesis is known as an arithmetic expression.
• The result of an arithmetic expression is also a numeric value
• Example:
x = c+d
x=c*a

56
INTEGRAL EXPRESSIONS

• An integral expression in Python is used for computations and type


conversion (integer to float, a string to integer, etc.).
• An integral expression always produces an integer value as a resultant.
• Example:
a=5
b = 5.0
res = a + int(b)

57
FLOATING EXPRESSIONS

• A floating expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.).
• A floating expression always produces a floating-point number as a resultant.
• Example:
a=5
b = 5.0
res = float(a) + b

58
RELATIONAL EXPRESSIONS

• A relational expression in Python can be considered as a combination of two or


more arithmetic expressions joined using relational operators.
• The overall expression results in either True or False (boolean result).
• We have four types of relational operators in Python (i.e. > , < , >= ,
<=)(i.e.>,<,>=,<=).
• A relational operator produces a boolean result so they are also known
as Boolean Expressions.
• Example:
10+15>20

59
LOGICAL EXPRESSIONS

• As the name suggests, a logical expression performs the logical computation using
logical operators, and the overall expression results in either True or False (boolean
result).
• Example:
a and b
a or b
a not b
a=3
b=3
if a>0 and b>0:
print(“a and b greater than zero”)

60
COMBINATIONAL EXPRESSIONS

• As the name suggests, a combination expression can contain a single or


multiple expressions which result in an integer or boolean value depending upon
the expressions involved.
• Example:
x=5
y=5
res = x + (2 *6)

61
BOOLEAN EXPRESSIONS

• A boolean expression is an expression that is either true or false.


• Example:
5>3
True
5 >9
False

62
CONVERSION FUNCTIONS

• Python defines type conversion functions to directly convert one


data type to another which is useful in day-to-day and competitive
programming.
• There are two types of Type Conversion in Python:
• Implicit Type Conversion
• Explicit Type Conversion

63
IMPLICIT TYPE CONVERSION

• In Implicit type conversion of data types in Python, the Python interpreter


automatically converts one data type to another without any user
involvement.
Program Output
x = 10 x is of type: <class 'int'>
print("x is of type:",type(x)) y is of type: <class 'float'>
y = 10.6 20.6
print("y is of type:",type(y)) z is of type: <class 'float'>
z=x+y
print(z)
print("z is of type:",type(z))

64
EXPLICIT TYPE CONVERSION

In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement.
Various forms of explicit type conversion are explained below:
1.int(a, base): This function converts any 5.list() : This function is used to convert any
data type to integer. ‘Base’ specifies data type to a list type.
the base in which string is if the data
6.dict() : This function is used to convert a
type is a string.
tuple of order (key,value) into a
2.float(): This function is used to dictionary.
convert any data type to a floating- 7.str() : Used to convert integer into a
point number. string.
3.tuple() : This function is used to convert 8.complex(real,imag) : This
to a tuple. function converts real numbers to
4.set() : This function returns the type complex(real,imag) number.
after converting to set. 65
PROGRAM

x=5
print("x is of type:",type(x))
y=float(x)
Output:
print("y is of type:",type(y)) x is of type: <class 'int’>
y is of type: <class ‘float’>
z=str(x) z is of type: <class ‘str'>

print("z is of type:",type(z))

66
PRECEDENCE OF OPERATORS

Solve this :

3+4x2–1
3+4/2–1

• BIDMAS
• BIDMAS, which stands
for Brackets, Indices, Division, Multiplication, Addition
and Subtraction.

67
• The operator precedence in Python is listed in the following table. It is in
descending order (upper group has higher precedence than the lower ones).
Priority Operator Meaning
1 () Parentheses
2 ** Exponent
3 +,-,~ Unary plus, Unary Minus, Bitwise NOT
4 *,/,//,% Multiplication, Division, Floor division, Modulus
5 +,- Addition, Subtraction
6 <<,>> Bitwise shift operators
7 & Bitwise AND
8 ^ Bitwise XOR
9 | Bitwise OR
10 ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
11 not Logical NOT
12 and Logical AND
13 or Logical OR
68
THANK YOU..

69

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy