0% found this document useful (0 votes)
79 views83 pages

Introduction to Python Programming

Python is a high-level, interpreted, and object-oriented programming language known for its readability and ease of use. It features dynamic typing, a large standard library, and supports both object-oriented and procedural programming paradigms. Python also allows for easy debugging, portability across platforms, and includes a variety of built-in functions for input, output, and importing modules.

Uploaded by

babysmitha14
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)
79 views83 pages

Introduction to Python Programming

Python is a high-level, interpreted, and object-oriented programming language known for its readability and ease of use. It features dynamic typing, a large standard library, and supports both object-oriented and procedural programming paradigms. Python also allows for easy debugging, portability across platforms, and includes a variety of built-in functions for input, output, and importing modules.

Uploaded by

babysmitha14
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

Python

• Python is a widely-used general-purpose, high-level, Interpreted, Object oriented


programming language.

• It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.

• In Python, we don’t need to declare the type of variable because it is a


dynamically typed language. For example, x = 10 Here, x can be anything such
as String, int, etc.

 Why name python ?

GUIDO VAN ROSSUM was a fan of the popular comedy show “Monty
Pythons Flying circus” broadcasted by BBC(1969 – 74). So he decides to choose
that name for his language as python.
Features in Python
1. Free and Open Source :

• Python language is freely available at the official website and you can download it
freely.
• Open-source means that source code is also available to the public. So you can
download it, use it as well as share it.

2. Easy to code:

• Python is a high-level programming language.


• Python is very easy to learn the language as compared to other languages like C,
C#, JavaScript, Java, etc.
• It is very easy to code in the Python language and anybody can learn Python
basics in a few hours or days.
• It is also a developer-friendly language.
3. Easy to Read:

• Python’s syntax is really straightforward.


• Python code looks like simple English words.
• The code block is defined by the indentations (space at the beginning of a code
line) rather than by semicolons or brackets.

4. Object-Oriented Language:

• Python supports object-oriented language and concepts of classes, object


encapsulation, etc.
• A programming language is object-oriented if it focuses design around data and
objects, rather than functions and logic.
• If a programming language is procedure-oriented if it focuses more on functions
(code that can be reused).
• One of the critical Python features is that it supports both object-oriented and
procedure-oriented programming.
5. Support for GUI :

• One of the key aspects of any programming language is support for GUI or
Graphical User Interface.
• A user can easily interact with the software using a GUI.
• Python offers various toolkits, such as Tkinter, wxPython and JPython, which
allows for GUI's easy and fast development.

6. High-level Language :

• Python is a high-level programming language because programmers don’t need to


remember the system architecture, nor do they have to manage the memory.
• This makes it super programmer-friendly and is one of the key features of Python.

7. Extensible feature :

Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.
8. Easy to Debug :

• Python is designed as a interpreter language, which means the whole code


would be executed line by line directly.
• If there is an error in between the block of code, that single error will get
encountered right away causing the further program to stop, which assist the
debugging code fast.

9. Python is a Portable language :

• Python is portable in the sense that the same code can be used on different
machines.
• For example, if we have Python code for windows and if we want to run this code
on other platforms such as Linux, Unix, and Mac then we do not need to change
it, we can run this code on any platform.
• As such, there is no need to write a program multiple times for several platforms.
10. Interpreted Language:

• When a programming language is interpreted, it means that the source code is


executed line by line, and not all at once.
• Programming languages such as C++ or Java are not interpreted, and hence need
to be compiled first to run them.
• There is no need to compile Python because it is processed at runtime by the
interpreter.
• The source code of Python is converted into an immediate form called bytecode.

11. Large Standard Library :

• Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing.
• There are many libraries present in Python such as regular expressions, unit-
testing, web browsers, etc.
12. Allocating Memory Dynamically :

• In Python, the variable data type does not need to be specified.


• The memory is automatically allocated to a variable at runtime when it is given a
value.
• Developers do not need to write int y = 18 if the integer value 15 is set to y. You
may just type y=18.

13. Expressive :

• Python needs to use only a few lines of code to perform complex tasks.
• For example, to display Hello World, you simply need to type one line -
print(“Hello World”). Other languages like Java or C would take up multiple lines
to execute this.
IDENTIFIERS

• Identifier is nothing but name in python program.


• It can be class_name, Function_name, Variable_name (eg. a=10) or
module_name.

Class a (here a is the identifier)


{
………..
}

Rules to define identifiers in python.

 Identifier names in Python can contain numbers (0-9), uppercase letters (A-Z),
lowercase letters (a-z), and underscore (_).

 The name should always start with a non-numeric character. Eg: 5a =10
 An identifier name should not contain numeric characters only.

 Identifier names in Python are case-sensitive like most other languages.


(‘Ash’ is different from ‘ASH’).

 Users can begin identifiers with an underscore; it will not display an error.
Eg _a= 5
Valid Python Identifiers

• _anu : identifier names can start with an underscore.

• _ : this may look odd, but a single underscore can be used as an identifier name.

• alpha123 : identifier names can begin with alphabets in lowercase.

• TeXt : identifier names can contain uppercase and lowercase alphabets in any
pattern.
• DRE, dre and Dre : will be considered three different identifier names due to the
difference in the case.
Invalid Python Identifiers
999: Identifier names that cannot contain only digits or numeric values.

x+iy: identifier names cannot contain any other special character except
underscore.

123alpha: identifier names cannot begin with numbers.

Keyword and Reserved Keywords in python.

• Keywords are reserved words whose meaning is already defined in the python
interpreter.
• Python has a set of keywords that cannot be used as variable names, function
names, or any other identifiers.
• Python contains a total of 33 keywords.
Keyword Description
and A logical operator
as To create an alias (we can give another
name of the function)
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as
else if
else Used in conditional statements
except Used with exceptions, what to do when
an exception occurs
False Boolean value, result of comparison
operations
finally Used with exceptions, a block of code that
will be executed no matter if there is an
exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple,
etc
is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator


or A logical operator
pass A null statement, a statement that will do
nothing
return To exit a function and return a value
True Boolean value, result of comparison
operations
try It defines a block of code test if it contains
any errors.
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
Python Variables

• Variables are containers for storing data values.


• A variable is created the moment we first assign a value to it.
• This means that when you create a variable you reserve some space in
memory.

Creating Variables

• Python has no command for declaring a variable.


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

Example:
et
x=5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type, and can even change
type after they have been set.

Example

x=4 # x is of type int


x = “anu" # x is now of type str
print(x)

Casting

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

Example

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type

• You can get the data type of a variable with the type() function.

Example

x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes:

String variables can be declared either by using single or double quotes:

Example:

x = "John“ # is the same as


x = 'John'
Case-Sensitive

• Variable names are case-sensitive.

Example :

a=4
A = "Sally"
#A will not overwrite a

Python - Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

 Rules for Python variables:

• 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 (age, Age and AGE are three different
variables)
• A variable name cannot be any of the Python keywords.

Example

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Comments in Python

• Comments in Python is the inclusion of short descriptions along with the code to
increase its readability.
• A developer uses them to write his or her thought process while writing the code.
• It explains the basic logic behind why a particular line of code was written.
• Python interpreter completely ignores comments in Python.
• Comments in Python are identified with a hash symbol, #, and extend to the end of
the line.
• There are multiple uses of writing comments in Python:

1. Increasing readability
2. Explaining the code to others
3. Understanding the code easily after a long-term
4. Including resources
5. Re-using the existing code
What Are the Advantages of Using Comments in Python?

• Makes the code easily understandable by other programmers.


• The code becomes self-explanatory.
• Helps remember why we used a specific command, method, or function in the
code.
• Enables the interpreter to ignore some part of the code while testing.

What Are the Different Types of Comments in Python?


 There are three types of comments:
• Single-line comments.
• Multi-line comments.
• Docstring comments.

Single-Line Comments :
• Single-line comments begin with the “#” character.
• Anything that is written in a single line after ‘#’ is considered as a comment.
The syntax for writing single-line comments is:

# comments here

There are two ways of using single-line comments in Python. You can use it before
the code or next to the code.

Eg: # initializing 2 variables


A =5
B=6
S = A + B #adding A and B
print(s)

Python Style Guide, recommends using less than 79 characters in a single-line


comment to make it easier to read. If your comment is exceeding the
recommended length, you can use the next type: multi-line comments.
Multi-Line Comments

• Python does not support multi-line comments.


• However, there are multiple ways to overcome this issue. None of these ways
are technically multi-line comments, but you can use them as one.
• The first way is by using # at the beginning of each line of the comment.

Eg : #you can
#create the comment
#using multiline
• The next way is by using string literals but not assigning them to any variables.
• If you do not assign a string literal to a variable, the Python interpreter ignores it.
• Use this to your advantage to write multi-line comments.
• You can either use a single (‘’) quotation or double (“”) quotation.
Python Docstrings :

• Python provides an in-built feature called docstrings for commenting on


modules, methods, functions, objects, and classes.
• They are written in the first line after defining a module, function, method, etc.,
using three quotation marks (‘’ or “”).
• If you do not use it in the first line, the interpreter will not take it as a docstring.
• You can also access docstrings using the __doc__ attribute.

Python Input, Output and Import functions

Python input:

• Until now our program was static, the values were defined to the variables. In
some cases user might want to input values to variables, which allows flexibility.
• Python has input() function to perform this.
Syntax:

Input([string to be displayed on screen])

Example: Python User Input :

# using input() to take user input


Output :
num = input('Enter a number: ')
Enter a number: 10
print('You Entered : ', num) You Entered: 10
Data type of num: <class 'str'>
print('Data type of num : ', type(num))
• Here we can clearly see that python habitually takes the input value given by the
user as a string.
• To convert this we can use int() or float() functions.

Example:

num = int(input('Enter a number: ')) Output :

print('You Entered : ', num) Enter a number: 4


You Entered : 4
print('Data type of num : ', type(num)) Data type of num : <class 'int'>
Python Output:

• To output data on the screen we use print() function.

Syntax of print(): print(object= separator= end= file= flush=)

Example:

print(' hello Python’) # Output: hello Python

Output formatting using format():

• To make your output look easy on the eye, you have to format the actual
appearance of the output.

• This can be done using .format()


• This can be used for any string object.
• The curly braces {} are used as place holders.

Example:

x=5
y = 10

print('The value of x is {} and y is {}'.format(x , y)) # Output: The value of x is 5 and y is 10

Python Import:

• When your program grows deeper, we cannot keep writing codes for each and
every action we need to perform. So in real time, we break the program into
different modules.
• Python has various modules and libraries. These modules contain python
definitions and statements.
• Definitions inside a module can be imported into another module or interactive
interpreter in python.
• We use import keyword do perform this.

import math
pie = [Link]
print("The value of pi is : ",pie)

Python Operators

Operators are special symbols that perform operations on variables and values.
For example,

print(5 + 6) # 11

Here, + is an operator that adds two numbers: 5 and 6. 5 and 6 are called operands.
Types of Python Operators :

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

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication, etc. For example,

sub = 10 - 5 # 5
Here, - is an arithmetic operator that subtracts two values or variables.
a=7 Example
Operator Operation Example b=2

# addition
+ Addition 5+2=7 print ('Sum: ', a + b)

# subtraction
- Subtraction 4-2=2 print ('Subtraction: ', a - b)

# multiplication
* Multiplication 2*3=6 print ('Multiplication: ', a * b)

# division
/ Division 4/2=2
print ('Division: ', a / b)
Output
// Floor Division 10 // 3 = 3 # floor division
print ('Floor Division: ', a // b) Sum: 9
Subtraction: 5
% Modulo 5%2=1 # modulo Multiplication: 14
print ('Modulo: ', a % b) Division: 3.5
Floor Division: 3
** Power 4 ** 2 = 16 # a to the power b Modulo: 1
print ('Power: ', a ** b) Power: 49
2. Python Assignment Operators:

Assignment operators are used to assign values to variables. For example,

# assign 5 to x
var x = 5
Here, = is an assignment operator that assigns 5 to x.
Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

*= Multiplication Assignment a *= 4 # a = a * 4

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


Example : Assignment operator

# assign 10 to a
a = 10

# assign 5 to b
b=5

# assign the sum of a and b to a # Output: 15


a += b #a=a+b :10
print(a) :2

# assign the sub of a and b to a


a-=b #a=a-b
print(a)

# assign the div of a and b to a


a/=b #a=a/b
print(a)
3. Python Comparison Operators:
Operator Meaning Example
Comparison operators compare two
values/variables and return a Boolean 3 == 5 gives us
== Is Equal To
False
result: True or False.
For example, != Not Equal To
3 != 5 gives us
True
a=5 3 > 5 gives us
> Greater Than
b =2 False

3 < 5 gives us
print (a > b) # True < Less Than
True

Here, the > comparison operator is >=


Greater Than or Equal 3 >= 5 give us
To False
used to compare whether a is greater
than b or not. 3 <= 5 gives us
<= Less Than or Equal To
True
Example 3: Comparison Operators
a=5
b=2

# equal to operator
print('a == b =', a == b)

# not equal to operator Output


print('a != b =', a != b)
a == b = False
# greater than operator a != b = True
print('a > b =', a > b)
a > b = True
# less than operator a < b = False
print('a < b =', a < b) a >= b = True
a <= b = False
# greater than or equal to operator
print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)
4. Python Logical Operators

• Logical operators are used to check whether an expression is True or False.

Operator Example Meaning

and a and b Logical AND: True only if both the operands are True

or a or b Logical OR: True if at least one of the operands is True

not not a Logical NOT: True if the operand is False and vice-versa

For example,
Here, and is the logical operator AND.
a=5
b=6 Since both a > 2 and b >= 6 are True, the
result is True.
print((a > 2) and (b >= 6)) # True
5. Python Bitwise operators

Bitwise operators are used to compare (binary) numbers:

For example: 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


6. Identity operators

• In Python, is and is not are used to check if two values are located on the same
part of the memory.
• Two variables that are equal does not imply that they are identical.

Operator Meaning Example

True if the operands are identical (refer to the same


is x is True
object)

True if the operands are not identical (do not refer to the
is not x is not True
same object)
x = 200
y = 100
For example, z=y

print(z is y) # prints True

print(x is not y) # prints True


7. Membership operators

• In Python, in and not in are the membership operators.

• They are used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary).

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x


Example :

x = 'Hello world'
y = {1:'a', 2:'b'}

# check if 'H' is present in x string


print('H' in x) # prints True Here, 'H' is in x but 'hello' is not present in x
# check if 'hello' is present in x string (remember, Python is case sensitive).
print('hello' not in x) # prints True
Similarly, 1 is key and 'a' is the value in
# check if '1' key is present in y dictionary y. Hence, 'a' in y returns False.
print(1 in y) # prints True

# check if 'a' key is present in y


print('a' in y) # prints False
DATA TYPES
• Every value belongs to a specific data type in Python.
• Data type identifies the type of data values a variable can hold and the
operations that can be performed on that data.
1. Number:

• Number data type stores numerical values only.


• It is further classified into three different types: int, float and complex.

• Boolean data type (bool) is a subtype of integer.


• It is a unique data type, consisting of two constants, True and
False.
• Boolean True value is one(1)-non-zero, non-null and non-empty.
• Boolean False is the value zero(0).
program to determine the data type of the variable using built-in function
type().
num1 = 10
print(type(num1)) output : < class 'int’ >

num2 = -12
print(type(num2)) output : < class 'int’ >

var1 = True
print(type(var1)) output : < class ‘bool’ >

float1 = -121.9
print(type(float1)) output : < class ‘float’ >

float2 = -9.8*10**2
print(float2, type(float2)) output : 980.0000000000001 < class ‘float’ >

var2 = -3+7.2j
print(type(var2)) output:< class ‘complex’ >
 Variables of simple data types like integers, float, Boolean, etc., hold
single values.

 But such variables are not useful to hold a long list of information, for
example, names of the months in a year, names of students in a class,
names and numbers in a phone book or the list of artefacts in a museum.

 For this, Python provides data types like tuples, lists, dictionaries and
sets. 2. Sequence

• A Python sequence is an ordered collection of items, where each item is


indexed by an integer.

• The three types of sequence data types available in Python are Strings,
Lists and Tuples.
String :

 String is a group of characters.


 These characters may be alphabets, digits or special characters including
spaces.
 String values are enclosed either in single quotation marks (e.g., ‘Hello’) or in
double quotation marks (e.g., “Hello”).
 The quotes are not a part of the string, they are used to mark the beginning and
end of the string for the interpreter.

Syntax:
str = "Hi Python !"
For example,
str1 = 'Hello Friend’
str2 = "452"
 We cannot perform numerical operations on strings, even when the string
contains a numeric value, as in str2.
 The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
 Each character is encoded in the ASCII or Unicode character.
 So we can say that Python strings are also called the collection of Unicode
characters.

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0.
For example, str = ‘ HELLO ’
EXAMPLE:

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[6]) # It returns the Index
Error because 6th index
Output:doesn't exist
H
E
L
L
O
IndexError: string index out of range
 In Python, the slice operator [ ] is used to access the individual characters of
the string.
 However, we can use the : (colon) operator in Python to access the substring
from the given string.
Example:

str = “FRIENDSHIP" # Given String

print(str[0:]) # Start 0th index to end Output:

print(str[1:5]) # Starts 1th index to 4th index FRIENDSHIP


RIEN
print(str[2:4]) # Starts 2nd index to 3rd index IE
FRI
print(str[:3]) # Starts 0th to 2nd index NDS

print(str[4:7]) # Starts 4th to 6th index


List :

• List is a sequence of items of different types separated by commas and


the items are enclosed in square brackets [ ].

• A list in Python is used to store the sequence of various types of data.

• A list can be defined as a collection of values or items of different types.

• Python lists are mutable type which implies that we may modify its
element after it has been formed.

Characteristics of Lists

• The lists are ordered.


• The element of the list can access by index.
• The lists are the mutable type.
• A list can store the number of various elements.
List Declaration :

# a simple list

list1 =[1,2,"Python", "Program", 15.9]


list2 =[“Arjun", “Alan", "Harry", “Hema"] Output:

# printing the list [1, 2, 'Python', 'Program', 15.9]


['Arjun', 'Alan', 'Harry', 'Hema']
print(list1) <class 'list'>
print(list2) <class 'list'>

# printing the type of list

print(type(list1))
print(type(list2))
Ordered List Checking

a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]


b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6] Output:Y (True)
a == b

List Indexing and Splitting

• The indexing is processed in the same way as it happens with the strings.

• The elements of the list can be accessed by using the slice operator [].

• The index starts from 0.

• The first element of the list is stored at the 0th index, the second element of
the list is stored at the 1st index, and so on.
Negative indexing :

• In contrast to other languages, Python gives you the option to employ negative
indexing as well.

• From the right, the negative indices are counted.

• The final element on the right-hand side of the list is represented by the index -1,
followed by the next member on the left at the index -2, and so on until the last
element on the left is reached.

list = [1,2,3,4,5]
Output:
print(list[-1])
5
print(list[-3:])
[3, 4, 5]
print(list[:-1])
[1, 2, 3, 4]
print(list[-3:-1])
[3, 4]
List Indexing

list = [1,2,3,4,5,6,7]

print(list[0])
print(list[1]) Output:
1
# Slicing the elements 2
print(list[0:6]) [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
# By default, the index value is 0 [3, 4, 5]
#so its starts from the 0th element and go for index -1. [2, 4, 6]
print(list[:])
print(list[2:5])
print(list[Link])
Updating List Values

• Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.

• Python also provides append() and insert() methods, which can be


used to add values to the list.

• The list elements can also be deleted by using the del keyword.
Python also provides us the remove() method if we do not know
which element is to be deleted from the list.
# updating list values

list = [1, 2, 3, 4, 5, 6]
print(list)

# It will assign value to the value to the second index

list[2] = 10 Output:
print(list) [1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
# Adding multiple-element [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
list[1:3] = [89, 78]
print(list)

# It will add value at the end of the list


list[-1] = 25
print(list)
Python Tuples

• Python tuple is a group of items that are separated by commas.


• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets or parenthesis ( ).

Example :
Create a Tuple:

mytuple = ("apple", "banana", "cherry")


print(mytuple)
Features of Python Tuple

• Tuples are an immutable data type, which means that once they have been
generated, their elements cannot be changed.

• Since tuples are ordered sequences, each element has a specific order that
will never change.
Creating of Tuple:

• To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma.

• A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).

Code:
# Python program to show how to create a tuple
# Creating tuple having integers

int_tuple = (4, 6, 8, 10, 12, 14)


print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types

mixed_tuple = (4, "Python", 9.3)


print("Tuple with different data types: ", mixed_tuple)
• Tuples can be constructed without using parentheses. This is known as triple
packing.

Code

# Python program to create a tuple without using parentheses


# Creating a tuple

tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]


print(tuple_)
Accessing Tuple Elements

We can access the objects of a tuple in a variety of ways.

1. Indexing
• To access an object of a tuple, we can use the index operator [], where indexing
in the tuple starts from 0.
• A tuple with 5 items will have indices ranging from 0 to 4.
Slice Operator

tuple = [1, 2, 3, 4] , [5, 6,7,8] , "Python"


print(tuple[0])
print(tuple[2])

print(tuple[0][3])
print(tuple[1][1])
print(tuple[2][0])

# Negative indexing
tuple = ("P " "y ", "t ", "h“, "o " , " n")
print(tuple[-1])
print(tuple[-4 : -1])

#column operator
print(tuple[0 : 3])
print(tuple[ : 5])
Python Set

• A Python set is the collection of the unordered items.


• Each element in the set must be unique, immutable, and the sets remove the
duplicate elements.
• Sets are mutable which means we can modify it after its creation.
• Unlike other collections in Python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index.
• However, we can print them all together, or we can get the list of elements by
looping through the set.

Creating a set

• The set can be created by enclosing the comma-separated immutable items


with the curly braces {}.
• Python also provides the set() method, which can be used to create the set by
the passed sequence.
Example 1: Using curly braces:

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

print(Days)
print(type(Days))
print("looping through the set elements ... ")

for i in Days:
print(i)

Example 2: Using set() method :

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])

print(Days)
print(type(Days))
print("looping through the set elements ... ")

for i in Days:
print(i)
Adding items to the set

• Python provides the add() method and update() method which can be used to
add some particular item to the set.
• The add() method is used to add a single element whereas the update()
method is used to add multiple elements to the set.

Example: - Using add() and update() method

Months = set(["January","February", "March", "April", "May", "June"])


print(months)
print("Adding other months to the set");
[Link]("July");
[Link] ("August");
print("Printing the modified set...");
print(Months)
[Link](["September","October","November","December"]);
print("printing the modified set ... ")
print(Months);
Removing items from the set

• Python provides the discard() method and remove() method which can be used
to remove the items from the set.
• The difference between these function, using discard() function if the item does
not exist in the set then the set remain unchanged whereas remove() method will
through an error.
Example : Using discard() and remove() function

months = set(["January","February", "March", "April", "May", "June"])


print(months)
print("Removing some months from the set");
[Link]("January");
[Link]("May");
print(months)
print("Removing some months from the set");
[Link]("June");
[Link]("March");
print("Printing the modified set");
print(months)
• We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped from set.

• Python provides the clear() method to remove all the items from the set.
Example:

Months = set(["January","February", "March", "April", "May", "June"])


print("printing the original set ... ")
print(Months)

[Link]()
print("Printing the modified set...")
print(Months)

print("Removing all the items from the set...");


[Link]()
print("Printing the modified set...")
print(Months)
Python Dictionary

• An effective data structure for storing data in Python is dictionaries


• Python Dictionary is used to store the data in a key-value pair format.
• It is the mutable data-structure.
• The elements Keys and values is employed to create the dictionary.
• Keys must consist of just one element.
• Value can be any type such as list, tuple, integer, etc.
• Dictionaries are generally unordered.
Creating the Dictionary

• The simplest approach to create a Python dictionary is by using curly brackets {},
but there are other methods as well.
• The dictionary can be created by using multiple key-value pairs enclosed with the
curly brackets {}, and each key is separated from its value by the colon (:).
Syntax:
Dict = {"Name": "Anu", "Age": 20}
• Python provides the built-in function dict() method which is also used to create
the dictionary.
• The empty curly braces {} is used to create empty dictionary.
Example:

Student = {"Name": "Anu", "Age": 20, "Fees":25000}


print(type(Student))
print("printing Student data ")
print(Student)

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method

Dict = dict({1: 'anu', 2: 'anju', 3:'ammu'})


print("\nCreate Dictionary by using dict(): ")
print(Dict)
Accessing the dictionary values :

 We can access values using keys ,but we can't access keys using values.

#Accessing all keys and values


student = {"Name": "Anu", "Age": 20, "Fees":25000}
print([Link]())
print([Link]())

#Accessing single value using indexing method


print(student["Fees"])
print(student["Name"])

 Another method for access the dictionary values called get() .

#Accessing value using get method


print([Link]("Fees"))
print([Link]("Name"))
Adding Dictionary Values

• The dictionary is a mutable data type, and its values can be updated by using the
specific keys.
• The value can be updated along with key Dict[key] = value.
• The update() method is also used to update an existing value.

Example : Output :

student = {"Name": "Anu", "Age": 20, "Fees":25000} {'Name': 'Anu', 'Age': 20, 'Fees': 25000}
{'Name': 'Ammu', 'Age': 20, 'Fees': 30000}
print(student)
student["Fees"]=30000
student["Name"]="Ammu"
print(student)
Deleting Elements using del Keyword

• The items of the dictionary can be deleted by using the del keyword
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.

There are two types of Type Conversion in Python:

1. Implicit Type Conversion


2. 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.

x = 10 Output:
print("x is of type:",type(x))
y = 10.6 x is of type: <class 'int'>
print("y is of type:",type(y)) y is of type: <class 'float'>
z=x+y 20.6
print(z) z is of type: <class 'float'>
print("z is of type:",type(z))
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 :

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.
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.
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.
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.
12. chr(number) : This function converts number to its corresponding ASCII
character.

Python Control Flow Statements and Loops

flow control is the order in which statement or block of code are executed at runtime
based on a condition.

The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements
1. CONDITIONAL STATEMENTS

• In Python, condition statements act


depending on whether a given
condition is true or false.
• You can execute different blocks of
codes depending on the outcome of a
condition.
• Condition statements always evaluate
to either True or False.

There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else
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.
• If the condition is True, then the True block of code will be executed.
• If the condition is False, then the block of code is skipped, and The controller
moves to the next line

Syntax of the if statement calculate the square of a number if it greater than 5

if condition: Example:
statement 1
statement 2 number = 6
statement n if number > 5:
# Calculate square
print(number * number)
If – else statement

The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.

Syntax of the if-else statement

if condition:
statement 1
else:
statement 2
if-elif-else condition statement

• In Python, the if-elif-else condition statement has an elif blocks to chain multiple
conditions one after another. This is useful when you need to check multiple
conditions.
• The elif statement checks multiple conditions one by one and if the condition fulfills,
then executes that code.
Syntax of the if-elif-else statement: Syntax of the nested-if-else:

if condition-1: if conditon_outer:
statement 1 if condition_inner:
elif condition-2: statement of inner if
stetement 2 else:
elif condition-3: statement of inner else:
stetement 3 statement ot outer if
... else:
else: Outer else
statement statement outside if block

Nested if-else statement

In Python, the nested if-else statement is an if statement inside another if-else


statement. It is allowed in Python to put any number of if statements in another if
statement.
2. ITERATIVE STATEMENTS

• In Python, iterative statements allow us to execute a block of code repeatedly as


long as the condition is True. We also call it a loop statements.
• Python provides us the following two loop statement to perform some actions
repeatedly

1. for loop
2. while loop
Python for loop

• We use a for loop when we want to repeat a code block a fixed number of times.
• In Python, the for loop is used to iterate over a sequence such as a list, string,
tuple, other iterable objects such as range.
• With the help of for loop, we can iterate over each item present in the sequence
and executes the same set of operations for each item.
• Using a for loops in Python we can automate and repeat tasks in an efficient
manner.
As opposed to while loops that execute until a condition is true, for loops are
executed a fixed number of times
Syntax of for loop

for i in range/sequencee:
statement 1
statement 2
statement n

• In the syntax, i is the iterating variable, and the range specifies how many times
the loop should run. For example, if a list contains 10 numbers then for loop will
execute 10 times to print each number.
• In each iteration of the loop, the variable i get the current value.

 Example: Print first 10 numbers using a for loop

• Here we used the range() function to generate integers from 0 to 9


• Next, we used the for loop to iterate over the numbers produced by the range()
function
• In the body of a loop, we printed the current number.

for num in range(10):


print(num)

for loop with range()

The range() function returns a sequence of numbers starting from 0 (by default) if
the initial limit is not specified and it increments by 1 (by default) until a final limit is
reached.

The range() function is used with a loop to specify the range (how many times) the
code block will be executed.
Syntax :

range(start, stop[, step])

Start : (Lower limit) It is the starting position of the sequence. The default value is 0
if not specified. For example, range(0, 10). Here, start=0 and stop = 10

Stop : (Upper limit) generate numbers up to this number.

Step : Specify the increment value. Each next number in the sequence is generated
by adding the step value to a preceding number. The default value is 1 if not
specified. It is nothing but a difference between each number in the result. For
example, range(0, 6, 1). Here, step = 1.

Python while loop

• The while loop statement repeatedly executes a code block while a particular
condition is true.
• In simple words, The while loop enables the Python program to repeat a set of
operations while a particular condition is true. When the condition becomes
false, execution comes out of the loop immediately, and the first statement after
the while loop is executed.

Syntax for while loop

while condition:
# Block of statement(s)

• The while statement checks the condition. The condition must return a Boolean
value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the
statements present inside its block.
• The while statement continues checking the condition in each iteration and
keeps executing its block until the condition becomes false.
2. TRANSFER STATEMENTS

• In Python, transfer statements are used to alter the program’s way of execution in a
certain manner.
• For this purpose, we use three types of transfer statements.

1. break statement
2. continue statement
3. pass statements

1. Break Statement in Python

• The break statement is used inside the loop to exit out of the loop.
• It is useful when we want to terminate the loop as soon as the condition is fulfilled
instead of doing the remaining iterations.
• It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately
Output
Example of using a break statement
0
for num in range(10): 1
if num > 5: 2
print("stop processing.") 3
break 4
print(num) 5
stop processing.
2. Continue statement in python

The continue statement is used to skip the current iteration and continue with the
next iteration.
Example of a continue statement Output

for num in range(3, 8): 3


if num == 5: 4
continue 6
else: 7
print(num)
3. Pass statement in Python

• The pass is the keyword In Python, which won’t do anything.


• Sometimes there is a situation in programming where we need to define a
syntactically empty block.
• We can define that block with the pass keyword.
• A pass statement is a Python null statement.
• When the interpreter finds a pass statement in the program, it returns no operation.
Nothing happens when the pass statement is executed.

Example Output

months = ['January', 'June', 'March', 'April'] ['January', 'June', 'March', 'April']


for mon in months:
pass
print(months)

You might also like