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

Chapter-2

The document provides an overview of Python programming concepts, including variable assignment, data types (numeric, boolean, sequence), string operations, and expressions. It explains how to create variables, their rules, and the importance of casting data types. Additionally, it covers operators, statements, and the order of operations in Python.

Uploaded by

Prashant Sapkota
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)
30 views20 pages

Chapter-2

The document provides an overview of Python programming concepts, including variable assignment, data types (numeric, boolean, sequence), string operations, and expressions. It explains how to create variables, their rules, and the importance of casting data types. Additionally, it covers operators, statements, and the order of operations in Python.

Uploaded by

Prashant Sapkota
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/ 20

An assignment statement creates a new variable and gives it a value:

message = 'And now for something completely different'


n = 17
pi = 3.141592653589793

This example makes three assignments. The first assigns a string to a new variable named
message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to
pi.

Data Types
Python Data types are the classification or categorization of data items. Python data types are
classes and variables are instances (objects) of these classes.
To define the values of various data types of Python and check their data types we use the type()
function.

Numeric Data Types


1) Integers
x=10
print(x)

type(x)

2) Float
y =10.0
print(type(y))

3) Complex Number
z = 3 + 4j
print(type(z))

Boolean Data Type


It is data type with one of the two built-in values, True or False.

w = True
print(type(w))

Sequene Data Type


string = 'This is a string'
string1 = "This is a string"

### The triple quotes can be used to declare multiline strings in


Python.
string2 = '''This
is
a
string'''
print(string)
print(string1)
print(string2)

Strings and string operations


It is helpful to think of a string as an ordered sequence. Each element in the sequence can be
accessed using an index represented by the array of numbers:
Name = "Michael Jackson"

# Printing First character


print(Name[0])

# Printing Second character


print(Name[1])

We can also use negative indexing with strings:

Negative index can help us to count the element from the end of the string.

The last element is given by the index -1:

# Prints the last element in the string

print(Name[-1])

# Prints the first element in the string

print(Name[-15])

We can find the number of characters in a string by using len, short for length:

# length of string
print(len(Name))

len("Michael Jackson")

We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th
to the 12th element:
# Taking the slice on variable name with only index 0 to index 3

print(Name[:4])

# Taking the slice on variable name with only index 8 to index 11

print(Name[8:12])

print(Name[12:])

We can also input a stride value as follows, with the '2' indicating that we are selecting every
second variable:

# Get every second element. The elments on index 1, 3, 5 ...

Name[1::2]

Python Strings are Immutable

In Python, strings are immutable. That means the characters of a string cannot be changed.
Name[0] = 'H'

String methods
upper()

lower()

count()

replace()

title()

capitalize()

split()

s = 'Introduction to Python'
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())

print(s.count('o'))
print(s.replace(' ','_'))

new = 'Python Programming'


print(new.replace(' ','*').capitalize())
new2 = new.replace(' ','*')
print(new2)
print(new2.capitalize())

The method split splits the string at the specified separator, and returns a list:

#Split the substring into list


name = "KFA,Business,School & IT"
split_string = (name.split(' '))
split_string

Reverse of a string

print(new[::-1])

Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 10

Variables do not need to be declared with any particular type, and can even change type after
they have been set.

x = 'ABC'

Variables – data – shaped boxes


• Variables:
– Think of variables as named containers or boxes.
– They are used to store data within a program.
– You can assign a name to a variable to identify it.
• Data:
– The information or values that you want to store in a variable.
– This data can be of various types, such as:
• Numbers (integers, floating-point numbers)
• Text (strings)
• True/False values (Booleans)
• Lists, tuples, dictionaries (collections of data)
• Shaped Boxes:
– The shape of the box can represent the type of data it holds.
– For example: A rectangular box for numbers A rounded box for text A square box
for Boolean values A more complex shape for collections
# Creating variables
name = "Alice"
age = 30
is_student = True

# Visual representation:
# +---------+ +---+ +--------+
# | Alice | | 30 | | True |
# +---------+ +---+ +--------+

Variable Rules
Variable names can contain only letters, numbers, and underscores _ . They can start with a
letter or an underscore _ , not with a number.
Variable names cannot contain spaces. To separate words in variables, you use underscores for
example sorted_list.

Variable names cannot be the same as keywords, reserved words, and built-in functions in
Python.

Guidelines to define good variable names:


• Variable names should be concise and descriptive. For example, the 'active_user'
variable is more descriptive than the 'au'.

• Use underscores (_) to separate multiple words in the variable names.

• Avoid using the letter 'l' and the uppercase letter O because they look like the
number 1 and 0.

Casting
If you want to specify the data type of a variable, this can be done with casting.

x =10
print(type(x))

x=float(x)

print(type(x))

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

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 = str(2) # y will be ?
z = int("3") # z will be ?
print(y)
print(z)
Python's keywords
Python 3 has these keywords:

Multiple Choice Questions

1) What is the output of the following code?

s = "hello_world_python"
print(s.split("_", -1))

1. ['hello', 'world', 'python']


2. ['hello', 'world_python']
3. ['hello_world_python']
4. Error

2) What does the following code print?

s = "Python"
print(s[::-1][::-1])
1. 'onhtyP'
2. 'nohtyP'
3. 'Python'
4. Error

3) What is the output of this code?

s = "hello"
print(s.replace("", "-"))

1. -h-e-l-l-o-
2. h-e-l-l-o
3. '------'
4. Error

4) What is the output of this code?

s = "Python"
print(s[0:100][-1:1:-2])

1. nhy
2. nohtyP
3. nh
4. Error

5) What is the output of this code?

s = "Hello World!"
x = s.find("World")
print(x)

1. True
2. False
3. 6
4. Error

Expressions in Python
An expression is a combination of values, variables, and operators.

A value all by itself is considered an expression, and so is a variable.

An expression can include variables, constants, function calls, and operators.

For example, 3 + 4 is an expression that evaluates to 7, and x * y is an expression that evaluates


to the product of x and y.
1 Constant Expression
These are the expressions that have constant values only. In a constant expression in Python, the
operator(s) is a constant. A constant is a value that cannot be changed after its initialization.

x=2+3
print('Sum:',x)

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

a = 10

b = 5

c = a + b # c will get 15
c = a - b # c will get 5
c = a/b # c will get 2.0
c = a//b # c will get 2
c = a * b # c will get 50

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.

a = 5
b = 10.0

# we need result in integer


res = a + int(b)

print("a + b =", res)

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.

a = 5
b = 10.0

# we need result in float


res = float(a) + b
print("a + b =", res)

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

print(a+b>=15)

Logical Expressions

As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.

age = 25
has_license = True

if age >= 18 and has_license:


print("You can drive!")
else:
print("You cannot drive.")

Bitwise Expressions

The expression in which the operation or computation is performed at the bit level is known as a
bitwise expression in Python. The bitwise expression contains the bitwise operators.

x = 2
left_shift = x << 1
right_shift = x >> 1
print("One left shift: ", left_shift)
print("One right shift: ", right_shift)

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.

a = 5
b = 2

res = a + (b << 1)

print("Result: ", res)


Statements
An instruction that the Python interpreter can execute (e.g., assignment statements, print
statements).

Types of statements:

• Simple Statements
– Assignment Statement (x = 10)
– Expression Statement (print("Hello, World!"))
– Augmented Assignment (x+=10)
• Conditional Statements
– if Statement
– if-else Statement
– if-elif-else Statement
• Looping Statements
– for Loop
– while Loop
– break & continue
• Control Flow Statements
– pass
– return
– yield
• Exception Handling Statements
– try-except
– try-except-finally
– raise
• Import Statements
– Basic Import
– Alias Import
– Selective Import
• Function & Class Definitions
– Function Definition
– class Definition

Question What is difference between Expressions and Statements?


Operators - data manipulation tools

Bitwise Operator
AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<)

Arithmatic Operator
Arithmetic operators perform mathematical operations on numbers (int, float, complex).

Arithmetic Operators in Python


Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 2 8
* Multiplication 4 * 3 12
Operator Name Example Result
/ Division / Float 10 / 2 5.0
Division
% Modulus 10 % 3 1
** Exponentiation 2 ** 3 8
// Floor/Truncation 10 // 3 3
Division
55/5

55//5

55%5

Bitwise Operator
AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<)

a = 2
b = 3
print(a & b)
print(a | b)
print(~a) # -(a+1)
print(a ^ b)
print(a >> 2)
print(a << 2)

In Python, ~x gives -(x + 1), so ~5 becomes -6.

Orders of Operations
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.

PEMDAS

Parentheses

Exponentiation

Multiplication and Division

Addition and Subtraction

* Operations in parentheses are resolved first, moving from left to


right.
* ** is resolved second, moving from right to left
* *, @, /, // and % are resolved third, moving from left to right.
* + and - are resolved fourth, moving from left to right.

Note: Operators with the same precedence are evaluated from left to right (except
exponentiation).

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

The precedence of Logical Operators in Python is as follows:

Logical not
Logical and
Logical or

The precedence of Bitwise Operators in Python is as follows:

Bitwise NOT
Bitwise Shift
Bitwise AND
Bitwise XOR
Bitwise OR

Preceden
ce Operators Description Associativity
1 () Parentheses Left to right
2 x[index], x[index:index] Subscription, slicing Left to right
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, negative, bitwise NOT Right to left
6 *, @, /, //, % Multiplication, matrix, division, Left to right
etc.
7 +, - Addition, subtraction Left to right
8 <<, >> Bitwise shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 1 Bitwise OR Left to right
12 in, not in, is, is not, <, <=, Comparisons, membership, Left to right
>, >=, !=, == identity tests
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional expression Right to left
Preceden
ce Operators Description Associativity
17 lambda Lambda expression N/A
18 := Assignment expression (walrus Right to left
operator)

Examples
# 1
5 + 3 * 2.0

11.0

# 2
(5 + 3) * 2

16

2**3**2

512

# 3
10 > 5 and 8 < 12

True

# 4
10 > 5 or 8 > 12

# 5
5 & 3

# 6
10 | 15

15

# 7
10 ^ 15

# 8
~5

-6
# 9
15<<1

30

# 10
15>>2

# 11
8 + 5 > 10 and 2 * 3 < 10

True

# 12
5 | 3 and 8 > 7

True

# 13
(10 & 8) == 8 or (15 ^ 1) < 16

True

# 14
2 ** 3 << 1

16

# 15
10 / 2 + 3 * 2 - 1

10.0

# 16
10 + 3 * 2 ** 2

# 17
3 & 2 | 1 ^ 4

# 18
~(5 & 3) | 4

# 19
15 >> 2 + 1

# 20
2 + 3 << 1

# 21
(5 + 3 * 2) > (10 / 2) and 6 | 1 == 7
# 22
((4 + 2) << 1) & ((3 ^ 1) | 4)

# 23
5 * (3 + 2) ** 2 - (6 >> 1)

# 24
((8 & 3) << 2) | ((5 + 7) >> 1)

Control Structures: Loops and Decision


*Conditional statements (if, elif, else).

*Loops (for, while).

*Break and continue statements.

Conditional statements (Decision)


Conditional statements allow the program to make decisions and execute certain code based on
conditions.

if Statement: Executes a block of code if a condition is true.

grade = 75
if grade > 85:
print("A+")

if-else Statement: Executes one block of code if a condition is true and another if it is false.

if grade > 85:


print("A+")
else:
print("B-")

elif Statement: Adds multiple conditions to an if statement.

if grade > 85:


print("A+")
elif grade < 35:
print("F")
else:
print("B")
Activity
num1 = int(input('Enter your first number:'))
num2 = int(input('Enter your second number:'))

if num2 == num1:
print("Number 1 is equal to Number 2")

elif num2 > num1:


print("Number 2 is greater than Number 1")

else:
print("Number 2 is less than Number 1")

Python Nested if Statements


num = 7

# outer if statement
if num >= 0:
# inner if statement
if num == 0:
print('Number is 0')

# inner else statement


else:
print('Number is positive')

# outer else statement


else:
print('Number is negative')

Loops
Loops allow the program to execute a block of code multiple times.

for Loop: Iterates over a sequence (e.g., list, string).

for i in range(0,5):
print(i) # Prints 0 to 4

while Loop: Repeats as long as a condition is true.

count = 0
while count < 5:
print(count)
count += 1

Activity
number = int(input("Enter a number to generate its multiplication
table: "))
print(f"Multiplication Table for {number}:")

Using 'for' loop

for i in range(1, 11):


print(f"{number} x {i} = {number * i}")

Using 'while' loop

i = 1
while i <= 10:
print(f"{number} x {i} = {number * i}")
i += 1

Break and Continue Statements


'break' statement: Exits the loop prematurely.

'continue' statement: Skips the current iteration and continues with the next one.

Activity: Find the First Even Number

Find the first even number in a list and skip printing numbers greater than 50.

numbers = [3, 7,52, 45, 67, 8, 34, 2]

for num in numbers:


if num > 50:
continue
if num % 2 == 0:
print(f"First even number found: {num}")
break

You might also like