0% found this document useful (0 votes)
2 views20 pages

Python CHAP2

The document covers the basics of Python programming, focusing on input/output operations, data types, and operators. It explains how to use functions like input() and raw_input() for user input, various data types including numeric and boolean, and type casting methods. Additionally, it describes different operators such as arithmetic, comparison, and logical operators with examples.

Uploaded by

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

Python CHAP2

The document covers the basics of Python programming, focusing on input/output operations, data types, and operators. It explains how to use functions like input() and raw_input() for user input, various data types including numeric and boolean, and type casting methods. Additionally, it describes different operators such as arithmetic, comparison, and logical operators with examples.

Uploaded by

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

PYTHON PROGRAMMING (20CS31P) 2023-24

Chapter-2
Basics I/O operations Input- input (), raw_input() ; output – print (), formatting output.
Datatypes Scalar type: Numeric (int, long, float, complex), Boolean, bytes, None; Type
casting Operators Arithmetic, Comparison/Relational, Logical/Boolean, Bitwise; string
operators; Expressions and operator precedence

2.1 Basics I/O operations Input- input (), raw_input() :


In Python input() function is used to take the values from the user. This function is called to tell the
program to stop and wait for the user to input the values. It is a built-in function.

# Python program to demonstrate

# input() function in Python3.x

val1 = input("Enter the name: ")

# print the type of input value

print(type(val1))

print(val1)

val2 = input("Enter the number: ")

print(type(val2))

val2 = int(val2)

print(type(val2))

print(val2)

P a g e | 1 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

To obtain user input from the command line is with the raw_input() built-in function. It reads from
standard input and assigns the string value to the variable you designate. You can use the int() built-in
function to convert any numeric input string to an integer representation.

>>> user = raw_input('Enter login name: ')

Enter login name: root

>>> print 'Your login is:', user

Your login is: root

A numeric string input (with conversion to a real integer) example follows below:

>>> num = raw_input('Now enter a number: ')

Now enter a number: 1024

>>> print 'Doubling your number: %d' % (int(num) * 2)

Doubling your number: 2048

The int() function converts the string num to an integer so that the mathematical operation can be
performed.

val1 = raw_input("Enter the name: ")

print(type(val1))

print(val1)

val2 = raw_input("Enter the number: ")

print(type(val2))

val2 = int(val2)

print(type(val2))

print(val2)

P a g e | 2 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

2.2 output – print (), formatting output:


There are several ways to present the output of a program, data can be printed in a human-readable
form, or written to a file for future use, or even in some other specified form. Sometimes user often
wants more control over the formatting of output than simply printing space-separated values.

q = 459

p = 0.098

print(q, p, p * q)

OUTPUT:

459 0.098 44.982

print(q, p, p * q, sep=",")

OUTPUT:

459,0.098,44.982

print(q, p, p * q, sep=" :-) ")

OUTPUT:

459 :-) 0.098 :-) 44.982

by using the string concatenation operator:

print(str(q) + " " + str(p) + " " + str(p * q))

OUTPUT:

459 0.098 44.982

P a g e | 3 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Formatting output using String modulo operator(%) :


The % operator can also be used for string formatting. It interprets the left argument much like a
printf()-style format as in C language string to be applied to the right argument.

The general syntax for a format placeholder is

%[flags][width][.precision]type

2.3 Data types:


Variables can store data of different types, and different types can do different things. Python
has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

P a g e | 4 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Binary Types: bytes, bytearray, memoryview

2.3.1 Scalar type: Numeric (int, long, float, complex):


In Python, numeric data type represents the data which has numeric value. Numeric value can
be integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.

 Integers – This value is represented by int class. It contains positive or negative


whole numbers (without fraction or decimal). In Python there is no limit to how long
an integer value can be.

 Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.

 Complex Numbers – Complex number is represented by complex class. It is


specified as (real part) + (imaginary part)j. For example – 2+3j

Note – type() function is used to determine the type of data type. Example:

x = 20 int

x = 20.5 float

x = 1j complex

# Python program to

# demonstrate numeric value

a=5

print("Type of a: ", type(a))

b = 5.0

print("\nType of b: ", type(b))

c = 2 + 4j

print("\nType of c: ", type(c))

Output:

P a g e | 5 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

x = 20

#display x:

print(x)

#display the data type of x:

print(type(x))

2.3.2 Boolean data type:


Booleans represent one of two values: True or False. You can evaluate any expression in
Python, and get one of two answers, True or False. When you compare two values, the
expression is evaluated and Python returns the Boolean answer:

Example : Print a message based on whether the condition is True or False:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Evaluate Values and Variables:The bool() function allows you to evaluate any value, and
give you True or False in return,

Example

x = "Hello"
y = 15
print(bool(x))
print(bool(y))

output:

True
True

2.3.3. Python bytes() Function:


Example

P a g e | 6 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Return an array of 4 bytes:

x = bytes(4)

print(x)

output:

b'\x00\x00\x00\x00'

The bytes() function returns a bytes object. It can convert objects into bytes objects, or create
empty bytes object of the specified size.

The difference between bytes() and bytearray() is that bytes() returns an object that cannot be
modified, and bytearray() returns an object that can be modified.

Syntax

bytes(x, encoding, error)

Parameter Description

x A source to use when creating the bytes object.

If it is an integer, an empty bytes object of the specified size will be created.

If it is a String, make sure you specify the encoding of the source.

encoding The encoding of the string

error Specifies what to do if the encoding fails.

Parameter Values

None:

The None keyword is used to define a null variable or an object. In Python, None keyword is
an object, and it is a data type of the class NoneType.

We can assign None to any variable, but you cannot create other NoneType objects.

Syntax is: None

Note: None statement supports both is and == operators.

# Declaring a None variable

P a g e | 7 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

var = None

if var is None: # Checking if the variable is None

print("None")

else:

print("Not None")

# Declaring a None variable

var = None

if var == None: # Checking if the variable is None

print("None")

else:

print("Not None")

 None is not the same as False.

 None is not 0.

 None is not an empty string.

 Comparing None to anything will always return False except None itself.

2.3.4 Type casting :


Type casting is a method used to change the variables/ values declared in a certain data type
into a different data type to match the operation required to be performed by the code

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)

 float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)

 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

y = int(2.8) # y will be 2
z = int("3") # z will be 3

P a g e | 8 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

x = float(1) # x will be 1.0


z = float("3") # z will be 3.0

y = str(2) # y will be '2'


z = str(3.0) # z will be '3.0'

2.4 Python Operators:


The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described
as follows.

o Arithmetic operators

o Comparison operators

o Assignment Operators

o Logical Operators

o Bitwise Operators

o Membership Operators

o Identity Operators

2.4.1 Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value results negative. For example, if a = 20, b = 10 =>
a - b = 10

/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0

P a g e | 9 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b =
(Multiplication) 200

% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand power to the
second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)

Example 1: Arithmetic operators in Python

x = 15

y=4

# Output: x + y = 19

print('x + y =',x+y)

# Output: x - y = 11

print('x - y =',x-y)

# Output: x * y = 60

print('x * y =',x*y)

# Output: x / y = 3.75

print('x / y =',x/y)

# Output: x // y = 3

print('x // y =',x//y)

# Output: x ** y = 50625

print('x ** y =',x**y)

Output

x + y = 19

x - y = 11

x * y = 60

x / y = 3.75

x // y = 3
P a g e | 10 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

x ** y = 50625

2.4.2 Comparison/Relational operators


Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly. The comparison operators are described in the following
table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition becomes true.

>= If the first operand is greater than or equal to the second operand, then the condition becomes true.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

Example 2: Comparison operators in Python

x = 10

y = 12

# Output: x > y is False

print('x > y is',x>y)

# Output: x < y is True

print('x < y is',x<y)

# Output: x == y is False

print('x == y is',x==y)

# Output: x != y is True

print('x != y is',x!=y)

# Output: x >= y is False

print('x >= y is',x>=y)

P a g e | 11 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

# Output: x <= y is True

print('x <= y is',x<=y)

Output

x > y is False

x < y is True

x == y is False

x != y is True

x >= y is False

x <= y is True

2.4.3. Logical Operators


The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a and b are the two
expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are the two
expressions, a → true, b → false => a or b → true.

not If an expression a is true, then not (a) will be false and vice versa.

Example 3: Logical Operators in Python

x = True

y = False

print('x and y is',x and y)

print('x or y is',x or y)

print('not x is',not x)

Output

x and y is False

x or y is True

not x is False
P a g e | 12 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

2.4.4 Bitwise Operators


The bitwise operators perform bit by bit operation on the values of the two operands.
Consider the following example.

For example,

1. if a = 7

2. b=6

3. then, binary (a) = 0111

4. binary (b) = 0110

5. hence, a & b = 0011

6. a | b = 0111

7. a ^ b = 0100

8. ~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the result.
and) Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will
be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in the right operand.

>> (right The left operand is moved right by the number of bits present in the right operand.
shift)

2.4.5 String operators

P a g e | 13 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.

For example −

var1 = 'Hello World!'

var2 = "Python Programming"

2.3.5.1 Accessing Values in Strings

Python does not support a character type; these are treated as strings of length one, thus also
considered a substring. To access substrings, use the square brackets for slicing along with the index
or indices to obtain your substring.

For example −

var1 = 'Hello World!'

var2 = "Python Programming"

print "var1[0]: ", var1[0]

print "var2[1:5]: ", var2[1:5]

When the above code is executed, it produces the following result −

var1[0]: H

var2[1:5]: ytho

2.5 Expressions and operator precedence


An expression is a combination of operators and operands that is interpreted to produce some other
value. So that if there is more than one operator in an expression, their precedence decides which
operation will be performed first and which operation is next. The interpreter evaluates the expression
and displays the result.

2.5.1. Constant Expressions:

These are the expressions that have constant values only.

# Constant Expressions

x = 15 + 1.3

print(x)

Output
P a g e | 14 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

16.3

2.5.2. Arithmetic Expressions:

An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis.


The result of this type of expression is also a numeric value. The operators used in these expressions
are arithmetic operators like addition, subtraction, etc.

# Arithmetic Expressions

x = 40

y = 12

add = x + y

sub = x - y

pro = x * y

div = x / y

print(add)

print(sub)

print(pro)

print(div)

Output

52

28

480

3.3333333333333335

2.5.3 Integral Expressions:

These are the kind of expressions that produce only integer results after all
computations and type conversions.

Example:

# Integral Expressions

a = 13

P a g e | 15 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

b = 12.0

c = a + int(b)

print(c)

Output

25

2.5.4. Floating Expressions:

These are the kind of expressions which produce floating point numbers as result after all
computations and type conversions.

Example:

# Floating Expressions

a = 13

b=5

c=a/b

print(c)

Output

2.6

2.5.5. Relational Expressions:

In these types of expressions, arithmetic expressions are written on both sides of relational operator
(> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational
operator and produce a boolean output in the end. These expressions are also called Boolean
expressions.

Example:

# Relational Expressions

a = 21

b = 13

c = 40

d = 37

P a g e | 16 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

p = (a + b) >= (c - d)

print(p)

Output

True

2.5.6. Logical Expressions:

These are kinds of expressions that result in either True or False. It basically specifies one or
more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some
logical operators which can be seen in logical expressions most often. Here are some logical
operators in Python:

Example:

Let’s have a look at an exemplar code :

P = (10 == 9)

Q = (7 > 5)

# Logical Expressions

R = P and Q

S = P or Q

T = not P

print(R)

print(S)

print(T)

Output

False

True

True

2.5.7. Bitwise Expressions:

These are the kind of expressions in which computations are performed at bit level.

Example:
P a g e | 17 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

# Bitwise Expressions

a = 12

x = a >> 2

y = a << 1

print(x, y)

Output

3 24

3.5.8. Combinational Expressions:

We can also use different types of expressions in a single expression, and that will be termed
as combinational expressions.

Example:

# Combinational Expressions

a = 16

b = 12

c = a + (b >> 1)

print(c)

Output

22

2.6 Operator Precedence


The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given
below.

Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

P a g e | 18 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

Precedence Name Operator

3 Unary plus or minus, complement -a , +a , ~a

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

is, is not, in, not


13 Identity and membership operators in

14 Logical Operators and, or, not

So, if we have more than one operator in an expression, it is evaluated as per operator
precedence. For example, if we have the expression “10 + 3 * 4”. Going without precedence

P a g e | 19 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan
PYTHON PROGRAMMING (20CS31P) 2023-24

it could have given two different outputs 22 or 52. But now looking at operator precedence, it
must yield 22. Let’s discuss this with the help of a Python program:

# Multi-operator expression

a = 10 + 3 * 4

print(a)

b = (10 + 3) * 4

print(b)

c = 10 + (3 * 4)

print(c)

Output

22

52

22

Hence, operator precedence plays an important role in the evaluation of a Python expression.

----------------------***************************************************------------------------

P a g e | 20 SHIVA H.Y, SELECTION GRADE LECTURER, Smt. L.V. Govt. Polytechnic, Hassan

You might also like