0% found this document useful (0 votes)
8 views39 pages

Presentation2

Uploaded by

bnhatm216
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)
8 views39 pages

Presentation2

Uploaded by

bnhatm216
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/ 39

Python Introduction

Python Data Types

{1:”1”,2:”b”} True,False {2,3,4}

20 35.75 ‘seed’ (3,3.4,”b”)

3+3j (2,’a’,5.7
Python Introduction

Python Data Types


returns the data
type() type of the
variable
To check the data
Str class type of variable use
the built-in function checks whether an
isinstance() object belongs to a
particular class

• Checking if an object is an instance of a specific class x = 10; print(isinstance(x, int))

• Checking if an object is an instance of multiple classes (using a tuple) x = 10 print(isinstance(x, (int, float)))
isinstance() class Animal:
• Checking inheritance # Create an object of the subclass
pass my_dog = Dog()
class Dog(Animal): # Check if the object is an instance of Animal (base class)
pass print(isinstance(my_dog, Animal))
Python Introduction

Python Data Types

To work with text or character data in Python, we use Strings.

Str class Once a string is created, we can do many operations on it, such
as searching inside it, creating a substring from it, and splitting it.

Note: The string is immutable, i.e., it can not be changed once defined. You need to create a copy of it if you
want to modify it. This non-changeable behavior is called immutability.

string.count(substring)
platform = "PYnative" # Now let's try to change 2nd character of a string. string.find(substring)
platform[0] = 'p'
# Gives TypeError: 'str' object does not support item assignment string.index(substring)
text = "Hello World! Welcome to Python."
result = text.split()/text.split(‘,’)
text = "Hello, World!"
substring = text[0:5]
Python Introduction

Python Data Types

Python uses the int data You can store positive and negative integer
Int data type type to represent whole numbers of any length such as 235, -758,
integer values. 235689741.

We can create an integer variable using the two ways

1. Directly assigning an integer value to a variable


roll_no = 33
2. Using a int() class.
id = int(25)
Python Introduction

Python Data Types


You can also store integer values other than base 10 such as

1. Binary (base 2)
Int data type
2. Octal (base 8)

3. Hexadecimal numbers (base 16)

# decimal int 16 with base 8 # decimal int 16 with base 16 # decimal int 16 with base 2
# Prefix with zero + letter o # Prefix with zero + letter x # Prefix with zero + letter b
octal_num = 0o20 hexadecimal_num = 0x10 binary_num = 0b10000
print(octal_num) # 16 print(hexadecimal_num) # 16 print(binary_num) # 16
print(type(octal_num)) # class 'int' print(type(hexadecimal_num)) # class 'int print(type(binary_num)) # class 'int'
Python Introduction

Python Data Types

We can create a float variable using the two ways

Float data type 1. Directly assigning a float value to a variable salary = 8000.456

2. Using a float() class. num = float(54.75)

Floating-point values can be represented using the exponential form, also called scientific notation.
exponential form : represent large values using less memory num1 = 1.22e4
Python Introduction

Python Data Types

A complex number is a number with a real and an imaginary component represented


Complex data type
as a+bj where a and b contain integers or floating-point values.

The integer value can be in the form of either decimal, float, binary, x = 9 + 8j # both value are int type

or hexadecimal. But the imaginary part should be represented y = 10 + 4.5j # one int and one float
z = 11.2 + 1.2j # both value are float type
using the decimal form only.
Python Introduction

Python Data Types

The Python List is an ordered collection (also known as a sequence ) of elements


• accessed,
List data type List elements can
• iterated,

we can use list type.


• and removed

1. The list can contain data of all data types such as int, float, string
2. Duplicates elements are allowed in the list
3. The list is mutable which means we can modify the value of list
elements
We can create a list using the two ways
1. By enclosing elements in the square brackets []. my_list = ["Jessa", "Kelly", 20, 35.75]

2. Using a list() class. my_list2 = list(["Jessa", "Kelly", 20, 35.75])


Python Introduction

Python Data Types

Tuples are ordered collections of elements that are unchangeable

Tuple data type List elements can • accessed, • read-only


• iterated, • can’t modify

We can create a tuple using the two ways


1. By enclosing elements in the parenthesis () my_tuple = (11, 24, 56, 88, 78)

2. Using a tuple() class. my_tuple2 = tuple((10, 20, 30, 40))

Note: Tuple maintains the insertion order and also, allows us to store duplicate elements.
Python Introduction

Python Data Types

dictionaries are unordered collections of unique values stored in (Key-Value) pairs


• duplicate keys are not allowed
Dict data type as a key-value pair
• value can be duplicated and accessed
• can modify

Dictionary has some characteristics which are listed below:

1. The dictionary is mutable which means we can modify its items

2. Dictionary is unordered so we can’t perform indexing and slicing


Python Introduction

Python Data Types

dictionaries are unordered collections of unique values stored in (Key-Value) pairs


• duplicate keys are not allowed
Dict data type as a key-value pair
• value can be duplicated and accessed
• can modify
We can create a dictionary using the two ways

1. By enclosing key and values in the curly brackets {} my_dict = {1: "Smith", 2: "Emma", 3: "Jessa"}

2. Using a dict() class my_dict = dict({1: "Smith", 2: "Emma", 3: "Jessa"}


Python Introduction

Python Data Types

a set is an unordered collection of data items that are unique and set of elements collection
1. It is mutable which means we can change set items
Set data type unique elements 2. Duplicate elements are not allowed
3. Heterogeneous (values of all data types) elements are allowed
4. Insertion order of elements is not preserved, so we can’t perform indexing on a Set

We can create a Set using the two ways


my_set.add(300)
1. By enclosing values in the curly brackets {} my_set = {100, 25.75, "Jessa"}

my_set.remove(100)
2. Using a set() class. my_set = set({100, 25.75, "Jessa"})

my_set.update ([4, 5, 6])


Python Introduction

Python Data Types


The frozenset data type is used to create the immutable Set.

Frozenset can’t perform any changes on it Use a frozenset() class to create a frozenset.
my_set = {11, 44, 75, 89, 56}
f_set = frozenset(my_set)
Note: If we try to perform operations like add, remove on frozenset, you will get an error.

x = 25; y = 20 ;z = x > y

Bool data type to represent boolean values (True and False) we use the bool data type.
Python Introduction

Python Data Types

data type represents a group of byte numbers just like an array.


1. returns a bytes object
Bytes data type immutable
2. handle binary data like images, videos, and audio files

In bytes, allowed values are 0 to 256. If we are trying to use any other values, then we will get a ValueError.

a = [9, 14, 17, 11, 78]


b = bytes(a)
print(type(b))
# class 'bytes'
print(b[0]) # 9
print(b[-1]) # 78
Python Introduction

Python Data Types

data type represents a group of byte numbers just like an array.

bytearray mutable returns a bytearray object

# modifying bytearray
list1 = [9, 17, 11, 78] b_array[1] = 99
b_array = bytearray(list1) print(b_array[1]) # 99
print(b_array)
# iterate bytearray
print(type(b_array))# class 'bytearray'
for i in b_array:
print(i, end=" ") # 9 99 11 78
Python Introduction

Python Data Types

is used to create a view of the internal data of an object without copying it.
memoryview
we can see the same data in a different view.

we need a buffer protocol. The buffer protocol provides a way to access the internal data of an object.

Syntax to create a memoryview


memoryview(obj)
Example 1: Creating memoryview of an object
b_array = b'PYnative'
b_array_view = memoryview(b_array) # creating memory view for bytes objects
print("view object: ", b_array_view)
View object: <memory at 0x0000003396DC6F48
Python Introduction

Python Data Types

is used to create a view of the internal data of an object without copying it.
memoryview we can see the same data in a different view.

we need a buffer protocol. The buffer protocol provides a way to access the internal data of an object.

Syntax to create a memoryview


memoryview(obj)
Example 2: Creating and storing in a container
byte_array = b'PYnative' # creating bytes array object
byte_array_view = memoryview(byte_array) # creating memory view for bytes array objects
container = tuple(byte_array_view) # Storing it in container of iterating
for char in container:
print(char, end=" ") 80 89 110 97 116 105 118 101
Python Introduction

Python Operators

What is
Operators in Operators are special symbols that perform specific operations on one or more operands (values) and
Python? then return a result.

The following image shows operator and operands:


Python Introduction

Python Operators
What is
Operators in Operators are special symbols that perform specific operations on one or more operands (values) and
Python? then return a result.

Python has seven types of operators

• Arithmetic operator
• Relational operators
• Assignment operators
• Logical operators
• Membership operators
• Identity operators
• Bitwise operators
Python Introduction

Python Operators
• Arithmetic operator
There are seven arithmetic operators we can use to perform different mathematical operations, such as:

1.+ (Addition)

• It adds two or more operands and gives their sum as a result x = 10; y = 40 ;print(x + y)

• addition operator with strings, and it will become string concatenation.


name = "Kelly“; surname = "Ault“; print(surname + " " + name)

2. - (Subtraction)
• Use to subtracts the second value from the first value and gives the difference between them.

x = 10 ;y = 40 ;print(y - x)
Python Introduction

Python Operators
• Arithmetic operator
There are seven arithmetic operators we can use to perform different mathematical operations, such as:

3. * (Multiplication)
• Multiply two operands. In simple terms, it is used to multiplies two or more values and gives their product
as a result.
x = 2 ;y = 4 ;z = 5 ;print(x * y) # Output 8 (2*4); print(x * y * z)

• multiplication operator with string

name = "Jessa" ;print(name * 3) # Output JessaJessaJessa


Python Introduction

Python Operators
• Arithmetic operator
There are seven arithmetic operators we can use to perform different mathematical operations, such as:

4. / (Division)
• Divide the left operand (dividend) by the right one (divisor) and provide the result (quotient ) in a float
value. x = 2 ;y = 4; z = 8 ;print(y / x)

5. // Floor division)

• Floor division returns the quotient (the result of division) in which the digits after the decimal point are removed.
x = 2
y = 4 # normal division
z = 2.2 print(y / z)
# normal division print(y / x) # 1.81
# Output 2.0 # floor division. # Result as float because one argument is float
# floor division to get result as integer print(y // z) # 1.0
print(y // x) # Output 2
Python Introduction
Python Operators
• Relational operators
Relational operators are also called comparison operators. It performs a comparison between two values. It returns a
boolean True or False depending upon the result of the comparison x=6;y=4
Operator Description Example
It returns True if the left operand is greater x > y
> (Greater than)
than the right result is True
It returns True if the left operand is less x<y
< (Less than)
than the right result is False
x == y
== (Equal to) It returns True if both operands are equal
result is False
x != y
!= (Not equal to) It returns True if both operands are equal
result is True
It returns True if the left operand is greater x >= y
>= (Greater than or equal to)
than or equal to the right result is True
It returns True if the left operand is less x <= y
<= (Less than or equal to)
than or equal to the right result is False
Python Introduction
Python Operators
• Relational operators
Relational operators are also called comparison operators. It performs a comparison between two values. It returns a
boolean True or False depending upon the result of the comparison

• compare more than two values

x = 10
y = 5
z = 2
# > Greater than
print(x > y) # True
print(x > y > z) # True
Python Introduction
Python Operators
• Assignment operators
In Python, Assignment operators are used to assigning value to the variable

Operator Meaning Equivalent


= (Assign) a=5Assign 5 to variable a a=5
+= (Add and assign) a+=5 Add 5 to a and assign it as a new value to a a = a+5
-= (Subtract and assign) a-=5 Subtract 5 from variable a and assign it as a new value to a a = a-5
*= (Multiply and assign) a*=5 Multiply variable a by 5 and assign it as a new value to a a = a*5
/= (Divide and assign) a/=5 Divide variable a by 5 and assign a new value to a a = a/5

%= (Modulus and assign) a%=5 Performs modulus on two values and assigns it as a new value to a a = a%5

**= (Exponentiation and assign) a**=5 Multiply a five times and assigns the result to a a = a**5
//= (Floor-divide and assign) a//=5 Floor-divide a by 5 and assigns the result to a a = a//5
Python Introduction
Python Operators
• Logical operators
Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator
returns a boolean value True or False depending on the condition in which it is used.

Operator Description Example

and (Logical and) True if both the operands are True a and b

or (Logical or) True if either of the operands is True a or b

not (Logical not) True if the operand is False not a


Python Introduction
Python Operators
• Logical operators
Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator
returns a boolean value True or False depending on the condition in which it is used.

and (Logical and)


• The logical and operator returns True if both expressions are True. Otherwise, it will return. False.

print(True and False)

• In the case of arithmetic values, Logical and always returns the second value; as a
result, see the following example. print(10 and 20) # 20
Python Introduction
Python Operators
• Logical operators
Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator
returns a boolean value True or False depending on the condition in which it is used.

or (Logical or)
The logical or the operator returns a boolean True if one expression is true, and it returns False if both
values are false.
print(True or False) # True print(True or True) # True
print(False or False) # false print(False or True) # True

• In the case of arithmetic values, Logical or it always returns the first value; as a result, see the following code.
print(10 or 20) # 10 print(10 or 5) # 10
Python Introduction
Python Operators
• Logical operators
Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator
returns a boolean value True or False depending on the condition in which it is used.

not (Logical not)


The logical not operator returns boolean True if the expression is false
rint(not False) # True return complements result
print(not True) # True return complements result

• In the case of arithmetic values, Logical not always return False for nonzero value.
print(not 10) # False
print(not 0) # True. zero value
Python Introduction
Python Operators
• Membership operators
Check for membership of objects in sequence, such as string, list, tuple.

In Python, there are two membership operator in and not in

In operator
• It returns a result as True if it finds a given object in the sequence. Otherwise, it returns False.
my_list = [11, 15, 21, 29, 50, 70];
number = 15
if number in my_list:
print("number is present") else:
print("number is not present")

Not in operator
It returns True if the object is not present in a given sequence. Otherwise, it returns False
my_tuple = (11, 15, 21, 29, 50, 70)
number = 35
if number not in my_tuple:
print("number is not present")
else:
print("number is present")
Python Introduction
Python Operators
• Identity operators
Use the Identity operator to check whether the value of two variables is the same or not

Python has 2 identity operators is and is not.


is operator
The is operator returns Boolean True or False. It Return True if the memory address first value is
equal to the second value. Otherwise, it returns False.

is not operator
The is not the operator returns boolean values either True or False. It Return True if the first value is not
equal to the second value. Otherwise, it returns False.
x = 10
y = 11
z = 10
print(x is not y) # it campare memory address of x and y
print(x is not z) # it campare memory address of x and z
Python Introduction
Python Operators
• Bitwise operators
In Python, bitwise operators are used to performing bitwise operations on integers.

a = 7
first need to convert integer value to binary (0 and 1) value. b = 4
c = 5
Python has 6 bitwise operators listed below. print(a & b)
print(a & c)
1. & Bitwise and print(b & c)

It performs logical AND operation on the integer value after converting an


integer to a binary value and gives the result as a decimal value. It
returns True only if both operands are True. Otherwise, it returns False.
Python Introduction
Python Operators
• Bitwise operators
a = 7
In Python, bitwise operators are used to performing bitwise operations on integers. b = 4
c = 5
print(a | b)
print(a | c)
first need to convert integer value to binary (0 and 1) value. print(b | c)

Python has 6 bitwise operators listed below.


2. | Bitwise or

It performs logical OR operation on the integer value after


converting integer value to binary value and gives the result a
decimal value. It returns False only if both operands are True.
Otherwise, it returns True
Python Introduction
Python Control Flow Statements and Loops

In Python programming, flow control is the order in which statements or blocks of code are executed at runtime
based on a condition.

Control Flow Statements

The flow control statements are divided into three categories

1. Conditional statements

2. Iterative statements.

3. Transfer statements
Python Introduction
Python Control Flow Statements and Loops

In Python programming, flow control is the order in which statements or blocks of code are executed at runtime
based on a condition.

Control Flow Statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.

There are three types of conditional statements.


1. if statement
2. if-else
3. if-elif-else
4. nested if-else
Python Introduction
Python Control Flow Statements and Loops
Control Flow Statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.

If statement in Python
In control statements, The if statement is the simplest form. It takes a condition
and evaluates to either True or False.

Syntax of the if statement


if condition:
statement 1 number = 6
statement 2 if number > 5:
statement n # Calculate square
print(number * number)
print('Next lines of code')
Python Introduction
Python Control Flow Statements and Loops
Control Flow Statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.

Chain multiple if statement in Pytho


Syntax of the if-elif-else statement
def user_check(choice):
if choice == 1:
if condition-1: print("Admin")
statement 1 elif choice == 2:
elif condition-2: print("Editor")
stetement 2 elif choice == 3:
elif condition-3: print("Guest")
stetement 3 else:
... print("Wrong entry")
else:
statement user_check(1)
user_check(2)
user_check(3)
user_check(4)
Python Introduction
Python Control Flow Statements and Loops
Control Flow Statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.

Nested if-else statement


Syntax of the if-else statement num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
if conditon_outer:
if condition_inner: if num1 >= num2:
statement of inner if if num1 == num2:
else: print(num1, 'and', num2, 'are equal')
statement of inner else: else:
statement ot outer if print(num1, 'is greater than', num2)
else: else:
Outer else print(num1, 'is smaller than', num2)
statement outside if block
Python Introduction
Python Control Flow Statements and Loops
Control Flow Statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.

Single statement suites

number = 56
if number > 0: print("positive")
else: print("negative")

You might also like