0% found this document useful (0 votes)
31 views45 pages

Unit 1-1

Uploaded by

iasccoe354
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)
31 views45 pages

Unit 1-1

Uploaded by

iasccoe354
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/ 45

PYTHON PROGRAMMING – CCS 62

UNIT I
Identifiers – Keywords - Statements and Expressions – Variables – Operators – Arithmetic
operators – Assignment operators – Comparison operators – Logical operators – Bitwise
operators - Precedence and Associativity – Data types - Number – Booleans – Strings -
Indentation – Comments – Single line comment – Multiline comments - Reading Input –
Print Output – Type Conversions – int function – float function – str() function – chr()
function – complex() function – ord() function – hex() function – oct() function - type()
function and Is operator – Dynamic and Strongly typed language.

IDENTIFIERS IN PYTHON
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
„num‟ and „Num‟ and „NUM‟ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.

Rules for Naming Python Identifiers

 It cannot be a reserved python keyword.


 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).

Examples of Python Identifiers

Valid identifiers:

var1
_var1
_1_var
var_1

Invalid Identifiers:

!var1
1var
1_var
var#1
var 1

UNIT - I Page 1
PYTHON PROGRAMMING – CCS 62

Example :

myVariable="hello world"
print(myVariable)

var1=1
print(var1)

var2=2
print(var2)

OUTPUT:

KEYWORDS IN PYTHON

Python keywords are reserved words that have a special meaning associated with them
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:

Python keywords are case-sensitive.

1. All keywords contain only letters (no special symbols)


2. Except for three keywords (True, False, None), all keywords have lower case letters

and as assert break

class continue def del

elif else except False

UNIT - I Page 2
PYTHON PROGRAMMING – CCS 62

finally for from global

if import in is

lambda None nonlocal not

or pass raise return

True try while with

yield

To Get the List of Keywrods

As of Python 3.9.6, there are 36 keywords available. This number can vary slightly over
time.

We can use the following two ways to get the list of keywords in Python

 keyword module: The keyword is the buil-in module to get the list of keywords. Also,
this module allows a Python program to determine if a string is a keyword.
 help() function: Apart from a keyword module, we can use the help() function to get the
list of keywords
Example: keyword module

import keyword
print(keyword.kwlist)

Output

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',

'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',

'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',

UNIT - I Page 3
PYTHON PROGRAMMING – CCS 62

'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

All the keywords except, True, False, and None, must be written in a lowercase alphabet symbol.

Example 2: The help() function

help("keywords")

Output:

Here is a list of the Python keywords. Enter any keyword to get more help.

False break for not


None class from or
True continue global pass
__peg_parser__ def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield

STATEMENTS IN PYTHON
In Python, statements are used to instruct the interpreter to perform a specific action. A
statement is a single line of code or a group of lines that perform a specific task. Every line of
code in Python is a statement, and Python programs are essentially a sequence of statements.
There are several types of statements in Python:
Assignment statements: Used to assign values to variables. For example, x = 5 assigns the
value 5 to the variable x.
x=5
y = "hello"
Conditional statements: Used to execute different blocks of code based on a condition. For
example, the if-else statement if x > 10: print("x is greater than 10") else: print("x is less

UNIT - I Page 4
PYTHON PROGRAMMING – CCS 62

than or equal to 10") executes the first block of code if x is greater than 10, and the second
block of code otherwise.
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
Loop statements: Used to execute a block of code repeatedly. For example, the for loop for i in
range(10): print(i) prints the numbers 0 through 9.
for i in range(10):
print(i)
Function definition statements: Used to define a new function. For example, def square(x):
return x * x defines a function called square that takes one argument x and returns its square.
def square(x):
return x * x
Import statements: Used to import modules or specific functions from modules. For example,
import math imports the entire math module, while from random import randint imports the
randint function from the random module.
import math
from random import randint
Class definition statements: Used to define a new class. For example, class MyClass: def
__init__(self, x): self.x = x defines a class called MyClass with a constructor that takes one
argument x and initializes an instance variable called x with its value.
class MyClass:
def __init__(self, x):
self.x = x
def square(self):
return self.x * self.x

EXPRESSIONS IN PYTHON

UNIT - I Page 5
PYTHON PROGRAMMING – CCS 62

In Python, expressions are combinations of literals, variables, operators, and function


calls that evaluate to a single value. An expression can be as simple as a single variable or literal,
or it can be more complex, involving several variables, literals, and operators. Here are some
examples of expressions in Python:

1. Constant Expressions: These are the expressions that have constant values only.

Example:
Python3

# Constant Expressions
x = 15 + 1.3

print(x)

Output

16.3

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. Here are some arithmetic operators in Python:

Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

UNIT - I Page 6
PYTHON PROGRAMMING – CCS 62

** x ** y Exponentiation

Example:

# 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

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
b = 12.0

c = a + int(b)
print(c)

Output
25

UNIT - I Page 7
PYTHON PROGRAMMING – CCS 62

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

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 + b) >= (c - d)
print(p)

Output
True

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.

UNIT - I Page 8
PYTHON PROGRAMMING – CCS 62

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:

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

7. Bitwise Expressions: These are the kind of expressions in which computations are performed
at bit level.

Example:

# Bitwise Expressions
a = 12

UNIT - I Page 9
PYTHON PROGRAMMING – CCS 62

x = a >> 2
y = a << 1

print(x, y)

Output
3 24

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

VARIABLES IN PYTHON

Python Variable is containers which store values. Python is not “statically typed”. A
variable is created the moment we first assign a value to it. A Python variable is a name given to
a memory location. It is the basic unit of storage in a program.

Example of Python Variables

Var = "Geeksforgeeks"
print(Var)

Output:
Geeksforgeeks

Rules for creating variables in Python

UNIT - I Page 10
PYTHON PROGRAMMING – CCS 62

 A variable name must start with a letter or the underscore character.


 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
 Variable names are case-sensitive (name, Name and NAME are three different variables).
 The reserved words(keywords) cannot be used naming the variable.

Let’s see the simple variable creation:

# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:
45
1456.8
John

Declare the Variable

# declaring the var


Number = 100

# display
print( Number)

Output:
100

Re-declare the Variable

We can re-declare the python variable once we have declared the variable already.

UNIT - I Page 11
PYTHON PROGRAMMING – CCS 62

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)

Output:
Before declare: 100
After re-declare: 120.3

Assigning a single value to multiple variables

Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.

For example:

a = b = c = 10

print(a)
print(b)
print(c)

Output:
10
10
10

Assigning different values to multiple variables

Python allows adding different values in a single line with “,”operators.

UNIT - I Page 12
PYTHON PROGRAMMING – CCS 62

a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)
print(b)
print(c)

Output:

1
20.2
GeeksforGeeks

OPERATORS IN PYTHON

The operator is a symbol that performs a certain operation between two operands, according
to one definition. In a particular programming language, operators serve as the foundation upon
which logic is constructed in a programme. The different operators that Python offers are listed
here.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

ARITHMETIC OPERATORS IN PYTHON

Python Arithmetic operators are used to perform basic mathematical operations


like addition, subtraction, multiplication, and division.

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Operator Description Syntax

+ Addition: adds two operands x+y

UNIT - I Page 13
PYTHON PROGRAMMING – CCS 62

Operator Description Syntax

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when the first operand is divided by the
% second x%y

x **
** Power: Returns first raised to power second y

Example of Arithmetic Operators in Python

Division Operators

Division Operators allow you to divide two numbers and return a quotient, i.e., the first
number or number at the left is divided by the second number or number at the right and returns
the quotient.

There are two types of division operators:


Float division
Floor division

Float division
The quotient returned by this operator is always a float number, no matter if two numbers
are integers.

For example:

# python program to demonstrate the use of "/"


print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)

Output:
1.0
5.0
UNIT - I Page 14
PYTHON PROGRAMMING – CCS 62

-5.0
10.0

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any
of the numbers is float, it returns output in float. It is also known as Floor division because, if
any number is negative, then the output will be floored.

For example:

# python program to demonstrate the use of "//"


print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)

Output:
3
-3
2.0
-3.0

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in python is as follows:

P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction

The modulus operator helps us extract the last digit/s of a number. For example:

x % 10 -> yields the last digit


x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

UNIT - I Page 15
PYTHON PROGRAMMING – CCS 62

# Examples of Arithmetic Operator


a=9
b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Modulo of both number


mod = a % b

# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(mod)
print(p)

Output:
13
5
36
1
6561

COMPARISON OPERATORS IN PYTHON

In Python Comparison of Relational operators compares the values. It either


returns True or False according to the condition.

Operator Description Syntax

> Greater than: True if the left operand is greater than the right x>y

UNIT - I Page 16
PYTHON PROGRAMMING – CCS 62

< Less than: True if the left operand is less than the right x<y

x ==
== Equal to: True if both operands are equal y

!= Not equal to – True if operands are not equal x != y

Greater than or equal to True if the left operand is greater than or equal to x >=
>= the right y

Less than or equal to True if the left operand is less than or equal to the x <=
<= right y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In python, the comparison operators have lower precedence than the arithmetic operators.
All the operators within comparison operators have same precedence order.

Example of Comparison Operators in Python

Let‟s see an example of Comparision Operators in Python.

# Examples of Relational Operators


a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

UNIT - I Page 17
PYTHON PROGRAMMING – CCS 62

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

Output

False
True
False
True
False
True

LOGICAL OPERATORS IN PYTHON

Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.

Operator Description

and The condition will also be true if the expression is true. If the two expressions a
and b are the same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.

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

UNIT - I Page 18
PYTHON PROGRAMMING – CCS 62

Precedence of Logical Operators in Python

The precedence of Logical Operators in python is as follows:

 Logical not
 logical and
 logical or

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

# Examples of Logical Operator


a = True
b = False

# Print a and b is False


print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

Output
False
True
False

BITWISE OPERATORS IN PYTHON

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.

Operator Description

& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 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) If the two bits are different, the outcome bit will be 1, else it will be 0.

UNIT - I Page 19
PYTHON PROGRAMMING – CCS 62

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.

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

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

Bitwise Operators in Python

Here is an example showing how Bitwise Operators in Python work:

# Examples of Bitwise operators


a = 10
b=4

# Print bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)

# Print bitwise NOT operation


print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)

Output
0
14
-11
14
2
40

UNIT - I Page 20
PYTHON PROGRAMMING – CCS 62

ASSIGNMENT OPERATORS IN PYTHON

Python Assignment operators are used to assign values to the variables.

Operator Description Syntax

Assign the value of the right side of the expression to the left side
= operand x=y+z

Add AND: Add right-side operand with left-side operand and


+= then assign to left operand a+=b a=a+b

Subtract AND: Subtract right operand from left operand and then
-= assign to left operand a-=b a=a-b

Multiply AND: Multiply right operand with left operand and then
*= assign to left operand a*=b a=a*b

Divide AND: Divide left operand with right operand and then
/= assign to left operand a/=b a=a/b

Modulus AND: Takes modulus using left and right operands and a%=b
%= assign the result to left operand a=a%b

Divide(floor) AND: Divide left operand with right operand and


//= then assign the value(floor) to left operand a//=b a=a//b

Exponent AND: Calculate exponent(raise power) value using a**=b


**= operands and assign value to left operand a=a**b

Performs Bitwise AND on operands and assign value to left a&=b


&= operand a=a&b

Performs Bitwise OR on operands and assign value to left


|= operand a|=b a=a|b

Performs Bitwise xOR on operands and assign value to left


^= operand a^=b a=a^b

UNIT - I Page 21
PYTHON PROGRAMMING – CCS 62

Operator Description Syntax

Performs Bitwise right shift on operands and assign value to left a>>=b
>>= operand a=a>>b

Performs Bitwise left shift on operands and assign value to left a <<= b a=
<<= operand a << b

Assignment Operators in Python

Let‟s see an example of Assignment Operators in Python.

# Examples of Assignment Operators


a = 10

# Assign value
b=a
print(b)

# Add and assign value


b += a
print(b)

# Subtract and assign value


b -= a
print(b)

# multiply and assign


b *= a
print(b)

# bitwise lishift operator


b <<= a
print(b)

Output
10
20
10
100
102400

UNIT - I Page 22
PYTHON PROGRAMMING – CCS 62

PRECEDENCE AND ASSOCIATIVITY

OPERATOR PRECEDENCE: This is used in an expression with more than one operator with
different precedence to determine which operation to perform first.

Example: Solve

10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30

Code:

# Precedence of '+' & '*'


expr = 10 + 20 * 30

print(expr)

Output:
610

Example: Now, let‟s see an example on logical „or„ & logical „and„ operator. „if„ block is
executed even if the age is 0. Because precedence of logical „and„ is greater than the logical „or„.

UNIT - I Page 23
PYTHON PROGRAMMING – CCS 62

# Precedence of 'or' & 'and'


name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2 :


print("Hello! Welcome.")
else :
print("Good Bye!!")

Output:
Hello! Welcome.

Hence, To run the „else„ block we can use parenthesis( ) as their precedence is highest
among all the operators.

# Precedence of 'or' & 'and'


name = "Alex"
age = 0

if ( name == "Alex" or name == "John" ) and age >= 2 :


print("Hello! Welcome.")
else :
print("Good Bye!!")

Output:
Good Bye!!

OPERATOR ASSOCIATIVITY: If an expression contains two or more operators with the


same precedence then Operator Associativity is used to determine. It can either be Left to Right
or from Right to Left.

Example: „*‟ and „/‟ have the same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

UNIT - I Page 24
PYTHON PROGRAMMING – CCS 62

Code:

# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)

# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

UNIT - I Page 25
PYTHON PROGRAMMING – CCS 62

Output:

100
6
0
512

Operators Precedence and Associativity are two main characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets.

Example: Solve

100 + 200 / 10 - 3 * 10

100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10)


and not as (100 + 200) / (10 - 3) * 10

Code:

expression = 100 + 200 / 10 - 3 * 10


print(expression )

Output:
90.0

UNIT - I Page 26
PYTHON PROGRAMMING – CCS 62

This table lists all operators from the highest precedence to the lowest precedence.

Operator Description Associativity

() Parentheses left-to-right

** Exponent right-to-left

* / % Multiplication/division/modulus left-to-right

+ – Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to


> >= Relational greater than/greater than or equal to left-to-right

== != Relational is equal to/is not equal to left-to-right

is, is not Identity


in, not in Membership operators left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

not Logical NOT right-to-left

and Logical AND left-to-right

or Logical OR left-to-right

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment right-to-left

UNIT - I Page 27
PYTHON PROGRAMMING – CCS 62

Operator Description Associativity

%= &= Modulus/bitwise AND assignment


^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

DATA TYPES IN PYTHON

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. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

UNIT - I Page 28
PYTHON PROGRAMMING – CCS 62

NUMBERS

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5
2. print("The type of a", type(a))
3. b = 40.5
4. print("The type of b", type(b))
5. c = 1+3j
6. print("The type of c", type(c))
7. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Python numeric data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023

UNIT - I Page 29
PYTHON PROGRAMMING – CCS 62

Python supports four different numerical types −

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))

STRING

The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns


'Python Python'.

The following example illustrates the string in Python.

Example - 1

1. str = "string using double quotes"


2. print(str)

UNIT - I Page 30
PYTHON PROGRAMMING – CCS 62

3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

BOOLEAN

Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be represented
by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the
following example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

UNIT - I Page 31
PYTHON PROGRAMMING – CCS 62

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Examples
Following is a program which prints the value of boolean variables a and b −
a = True
# display the value of a
print(a)
# display the data type of a
print(type(a))

This produce the following result −


true
<class 'bool'>

Following is another program which evaluates the expressions and prints the return values:
# Returns false as a is not equal to b
a=2
b=4
print(bool(a==b))
# Following also prints the same
print(a==b)
# Returns False as a is None
a = None
print(bool(a))
# Returns false as a is an empty sequence
a = ()
print(bool(a))

UNIT - I Page 32
PYTHON PROGRAMMING – CCS 62

# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))

This produce the following result −


False
False
False
False
False
True

INDENTATION IN PYTHON

Python indentation refers to adding white space before a statement to a particular block of
code. In another word, all the statements with the same space to the right, belong to the same
code block.

Example of Python Indentation

 Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for execution.
 The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
 Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.

Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code. A block is a combination of all these statements. Block can
be regarded as the grouping of statements for a specific purpose.

Most programming languages like C, C++, and Java use braces { } to define a block of
code. Python uses indentation to highlight the blocks of code. Whitespace is used for indentation
in Python.

UNIT - I Page 33
PYTHON PROGRAMMING – CCS 62

All statements with the same distance to the right belong to the same block of code. If a
block has to be more deeply nested, it is simply indented further to the right. You can understand
it better by looking at the following lines of code.

Example 1

The lines print(„Logging on to geeksforgeeks…‟) and print(„retype the URL.‟) are two
separate code blocks. The two blocks of code in our example if-statement are both indented four
spaces. The final print(„All set!‟) is not indented, so it does not belong to the else block.

# Python program showing


# indentation

site = 'gfg'

if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')

Output:
Logging on to geeksforgeeks...
All set !

Example 2

To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is required
for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is
not indented, and so it is not within the Python while block. So, Python code structures by
indentation.

j=1

while(j<= 5):
print(j)
j=j+1

Output:
1
2
3
UNIT - I Page 34
PYTHON PROGRAMMING – CCS 62

4
5

COMMENTS IN PYTHON
In Python, comments are used to add explanations or annotations to the code. They are
ignored by the interpreter and do not affect the execution of the program. There are two types of
comments in Python: single-line comments and multi-line comments.

Single-line comments: These are comments that occupy only one line in the code. They are
created by using the hash symbol (#) at the beginning of the line. Any text following the hash
symbol on that line is considered a comment and is ignored by the interpreter.

Example :
# This is a single-line comment
print("Hello, World!") # This is another single-line comment

OUTPUT :

Multi-line comments: These are comments that span multiple lines in the code. They are
created by enclosing the text of the comment in triple quotes (""") at the beginning and end of the
comment.

Example :
"""

This is a multi-line comment.

It can span multiple lines.

This type of comment is also known as a docstring.

"""

print("Hello, World!")

UNIT - I Page 35
PYTHON PROGRAMMING – CCS 62

OUTPUT :

Multi-line comments are often used to provide documentation for functions, classes, and
modules. They can be accessed using the __doc__ attribute of the object.
For example, consider the following function with a docstring:
Example :
def add_numbers(x, y):
"""
This function adds two numbers and returns the result.
"""
return x + y
You can access the docstring of the above function using the __doc__ attribute:
Example :
print(add_numbers.__doc__)

OUTPUT :

READING INPUT AND PRINTING OUTPUT IN PYTHON

In Python, you can use the input() function to read input from the user and the print()
function to display output to the user.

Reading input:

The input() function allows the user to enter a value from the keyboard. The value
entered by the user is returned as a string. If you need to use the entered value as an integer or
float, you can convert it using the int() or float() function.
Example :

name = input("Enter your name: ")


age = int(input("Enter your age: "))

UNIT - I Page 36
PYTHON PROGRAMMING – CCS 62

height = float(input("Enter your height in meters: "))


print("Name:", name)
print("Age:", age)
print("Height:", height)

OUTPUT :

Printing output:

The print() function is used to display output to the user. You can pass one or more
values to the print() function, separated by commas, to display them on the screen. By default,
the print() function adds a newline character at the end of the output. You can change this
behavior by specifying the end parameter.

Example :

name = "John"
age = 25
height = 1.75
print("Name:", name, "Age:", age, "Height:", height)
print("Name: " + name + ", Age: " + str(age) + ", Height: " + str(height))
print("Name: {}\nAge: {}\nHeight: {}".format(name, age, height))

OUTPUT :

UNIT - I Page 37
PYTHON PROGRAMMING – CCS 62

In the first example, we use commas to separate the values and let print() handle the
formatting.
In the second example, we concatenate the values using string concatenation and convert
the integer and float values to strings using the str() function.
In the third example, we use the format() method to format the output. The curly braces
{} are replaced with the corresponding values passed to the format() method. The \n character is
used to add a newline after each value.

TYPE CONVERSION IN PYTHON


Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming. This article is aimed at providing
information about certain conversion functions.

There are two types of Type Conversion in Python:

 Implicit Type Conversion


 Explicit Type Conversion

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. To get a more clear view of the
topic see the below examples.

Example:

x = 10

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

y = 10.6
print("y is of type:",type(y))

z=x+y

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

Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
UNIT - I Page 38
PYTHON PROGRAMMING – CCS 62

20.6
z is of type: <class 'float'>

As we can see the data type of „z‟ got automatically changed to the “float” type while one
variable x is of integer type while the other variable y is of float type. The reason for the float
value not being converted into an integer instead is due to type promotion that allows performing
operations by converting data into a wider-sized data type without any loss of information. This
is a simple case of Implicit type conversion in python.

Explicit Type Conversion

In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type. Various forms of explicit type
conversion are explained below:

1. int(a, base): This function converts any data type to integer. „Base‟ specifies the base in
which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.

# Python code to demonstrate Type conversion


# using int(), float()

# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0

UNIT - I Page 39
PYTHON PROGRAMMING – CCS 62

3. ord() : This function is used to convert a character to integer.


4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.

# Python code to demonstrate Type conversion


# using ord(), hex(), oct()

# initializing integer
s = '4'

# printing character converting to integer


c = ord(s)
print ("After converting character to integer : ",end="")
print (c)

# printing integer converting to hexadecimal string


c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)

# printing integer converting to octal string


c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)

Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

6. tuple() : This function is used to convert to a tuple.


7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.

UNIT - I Page 40
PYTHON PROGRAMMING – CCS 62

# Python code to demonstrate Type conversion


# using tuple(), set(), list()

# initializing string
s = 'geeks'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)

Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']

9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.

# Python code to demonstrate Type conversion


# using dict(), complex(), str()

# initializing integers
a=1
b=2

# initializing tuple

UNIT - I Page 41
PYTHON PROGRAMMING – CCS 62

tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)

# printing integer converting to string


c = str(a)
print ("After converting integer to string : ",end="")
print (c)

# printing tuple converting to expression dictionary


c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)

Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}

12. chr(number): This function converts number to its corresponding ASCII character.

# Convert ASCII value to characters


a = chr(76)
b = chr(77)

print(a)
print(b)

Output:
L
M

TYPE () FUNCTION and Is Operator :

Python type() returns the type of the specified object if a single argument is passed to the
type(). If three arguments are passed, it returns a new type of object.

UNIT - I Page 42
PYTHON PROGRAMMING – CCS 62

Signature

type(object, bases, dict)

Parameters

object: The type() returns the type of this object if one parameter is specified.

bases (optional): It specifies the base classes.

dict (optional): It specifies the namespace with the definition for the class.

Return

It returns the type of the specified object if a single argument is passed to the type(). If
three arguments are passed, it returns a new type of object.

Python type() Function Example 1

The below example shows how to get the type of an object.

1. List = [4, 5]
2. print(type(List))
3. Dict = {4: 'four', 5: 'five'}
4. print(type(Dict))
5. class Python:
6. a=0
7. InstanceOfPython = Python()
8. print(type(InstanceOfPython))

Output:

<class 'list'>
<class 'dict'>
<class '__main__.Python'>

In the above example, we have taken a List that contains some values, and in return, it
prints the type of the List.

In the second case, we have taken a Dict that contains some values, and in return, it prints
the type of the Dict.

UNIT - I Page 43
PYTHON PROGRAMMING – CCS 62

Then, we have defined a class named as Python and produced


an InstanceOfPython which prints its type.

IS OPERATORS IN PYTHON

In Python, is and is not operators are called identity operators. Each object in computer's
memory is assigned a unique identification number (id) by Python interpreter. ]
Identity operators check if id() of two objects is same. 'is' operator returns false of id() values are
different and true if they are same.
The is operator is used to test whether two variables or objects refer to the same object in
memory. For example:

x = [1, 2, 3]

y = [1, 2, 3]

z=x

print(x is y) # Output: False

print(x is z) # Output: True


In the above example, the is operator is used to compare the variables x, y, and z. The
output shows that x and y are not the same object in memory, while x and z are the same object
in memory.

It is important to note that the is operator tests for identity (whether two objects are the
same object in memory), while the == operator tests for equality (whether two objects have the
same value).

Example :
>>> a=10
>>> b=a
>>> id(a), id(b)
(490067904, 490067904)
>>> a is b
True
>>> a=10
>>> b=20
>>> id(a), id(b)

UNIT - I Page 44
PYTHON PROGRAMMING – CCS 62

(490067904, 490068064)
>>> a is b
False

DYNAMIC AND STRONGLY TYPED LANGUAGE

Python is a dynamically typed language, which means that the type of a variable is
determined at runtime, based on the value that is assigned to it. This allows for more flexibility
and ease of use, as variables can be reassigned to different types throughout the program.

For example, the following code is perfectly valid in Python:

x=5
print(type(x)) # Output: <class 'int'>

x = "hello"
print(type(x)) # Output: <class 'str'>

In this example, the variable x is assigned an integer value at first, but later it is
reassigned a string value. This is possible because Python is dynamically typed and does not
require the type of the variable to be declared ahead of time.

Python is also a strongly typed language, which means that the type of a variable is
enforced at all times. This means that operations performed on variables must be compatible
with their data types, and Python will not automatically convert the data types for you.

For example, the following code will result in a TypeError because Python cannot add a
string and an integer together:

x=5
y = "hello"
print(x + y) # Output: TypeError: unsupported operand type(s) for +: 'int' and 'str'

In this example, Python enforces strong typing and does not allow adding an integer and
a string together. This is because the two data types are not compatible and cannot be
automatically converted.

UNIT - I Page 45

You might also like