You are on page 1of 45

Basics of Python

Topics Covered:
● Introduction to Python
○ What is Python
○ Why Learn Python
○ Features of Python
○ Python in Industries
○ Projections Of Future Traffic For Major Programming Languages
○ Python Career Opportunities – Which one will you choose?
○ Python 2 Vs. Python 3

● Anaconda Installation
○ How is Anaconda related to Python?
○ What is an IDE?
○ Different IDE’s for Python
○ How to Install Anaconda
○ How to Open Jupyter

● Introduction to Jupyter Notebook


○ What is a Jupyter Notebook ?
○ Features of Jupyter Notebook
○ Overview of Jupyter Environment

● Variables and Data Types


○ What are Python Variables?
○ Rules for creating variables in Python
○ Assigning Values to Variables
○ Reassigning Values to Variables
○ Python Comments
○ Python Data Types

● Operators in Python
○ Arithmetic Operators
○ Assignment operators

● Print() and Input() Functions


○ The input () function
○ The print () function
○ Uses and Examples of print() function in Python
○ Parameters of print()
● String Slicing
○ Python’s Len() Function
○ Python Strings
○ String Indexing In Python
○ Rules of Indexing
○ String Slicing In Python
○ Left to Right slicing
○ Right to Left slicing

● String Methods
○ Properties Of String
○ Python string operations
○ String Functions/Methods

● Conditional Statements
○ Indentation & its usage in conditional statements
○ Indentation Errors
○ If statement
○ If else statement
○ If-elif-else statement
○ Nested-if statement

● For Loop and While Loop


○ Syntax of for loop
○ The Range() Function
○ Syntax of While Loop

● Break and Continue Keywords


Introduction To Python
What Is Python?

Python is a simple, general purpose, high level, and object-oriented programming language.
Guido Van Rossum is known as the founder of Python programming and it was released in
1991. It is a free, open-source, interpreted scripting programming language.

It is used for:
web development (server-side),
software development,
Mathematics,
system scripting.

Why Learn Python?

● Python is also a cross-platform compatible language.i.e, you can install and run Python
on several operating systems. Whether you have a Windows, Mac, or Linux, you can
rest assured that Python will work on all these operating systems.

● Python is also great for visualization. It provides libraries such as Matplotlib, Seaborn,
and many more for visualization purposes.

● Python is the most popular language for Machine learning and Deep Learning. Today, all
top organizations are investing in Python to implement Machine Learning in the
back-end.

● Suppose we want to print “Welcome to the world of programming” on our screen.


Python Syntax:
print(“Welcome to the world of programming”)

Features Of Python

● Easy and simple to learn and understand.


● Python enables object-oriented programming and concepts such as classes,
encapsulation, and so on.
● Python is a dynamically typed language
● It turns the code into bytecode, which can be run on any platform.
● It is an extensible programming language which means we can write and compile code
like any other programming language.
● Python is also an integrated language since it can easily be used with other
programming languages such as C, C++, Java, and others.
● Large Open Source Community: Suppose you are working on a python project and you
get stuck somewhere, you don’t have to worry because python has a huge community
for help. So, if you have any queries, you can directly seek help from millions of python
community members.

Python In Industries

Python is a general-purpose, popular programming language and it is used in almost every


technical field.

● Meta uses Python to tag friends in images


● Google uses Python in Language Translation and to improvise search results
● E-commerce giants like Amazon, Flipkart uses Recommendation system
● Dropbox server and client application uses Python
● 3D CAD Applications
● Computer Vision or Image Processing Applications.
● Speech Recognitions
Projections Of Future Traffic For Major Programming Languages

The above graph shows following results:

● Analytics programming languages(Python & R) will continue gaining popularity


● Java will gain a little and then keep a constant popularity
● JavaScript, C# & C++ will lose significant popularity
● PHP & Ruby could lose almost all their popularity and become obsolete in the next 5
years

Python Career Opportunities – Which one will you choose?


While there’s a high demand for Python developers in India, the supply is really, really low.

With Python on your resume, you may end up with one of the following positions in a reputed
company:

● Software Engineer - Analyze user requirements


○ Write and test code
○ Write operational documentation
○ Consult clients and work closely with other staff
○ Develop existing programs

● Senior Software Engineer - Develop high-quality software architecture


○ Automate tasks via scripting and other tools
○ Review and debug code
○ Perform validation and verification testing
○ Implement version control and design patterns

● DevOps Engineer - Deploy updates and fixes


○ Analyze and resolve technical issues
○ Design procedures for maintenance and troubleshooting
○ Develop scripts to automate visualization
○ Deliver Level 2 technical support

● Data Scientist - Identify data sources and automate the collection


○ Preprocess data & analyze it to discover trends
○ Design predictive models and ML algorithms
○ Perform data visualization
○ Propose solutions to business challenges

● Senior Data Scientist - Supervise junior data analysts


○ Build analytical tools to generate insight, discover patterns, and predict behavior
○ Implement ML and statistics-based algorithms
○ Propose ideas for leveraging possessed data
○ Communicate findings to business partners

● And Many More Such as: Web application development


○ Machine Learning
○ Deep Learning
○ Big data analysis
○ Smart IOT Devices
Python 2 Vs. Python 3

The two versions of Python - Python 2 and Python 3 are the most widely used Python versions

and there are many differences between these versions which are as follows:

Python 2 Python 3

The release year of Python 2 is 2000 The release year of Python 3 is 2008

The syntax is more complex in this version The syntax is easy and simple
than in Python 3

By default, strings are saved in ASCII format By default, strings are saved in UNICODE
in version 2 of Python format in this version.

In Python 2, Print is a statement. So, the In Python 3, Print is a function. So, the syntax
syntax is print “hello” is print (“hello”).

Exceptions should be enclosed in notations in Exceptions should be enclosed in


Python 2. parentheses in Python 3.

In python 2, while using variables inside a In Python 3, the value of variables stays
for-loop, their values do change. constant.

Python 2 is not that popular after 2020 Python 3 is a more popular version of Python
compared to Python 3 and is being used for many purposes

To perform iterations in Python 2, xrange() is To perform iterations in Python 3, Range() is


used used
Anaconda Installation
How is Anaconda related to Python?

● Anaconda is a python and R distribution. It aims to provide everything we need


(Python-wise) for data science, machine learning applications, large-scale data
processing, and predictive analytics.
● It includes:
○ The core Python language
○ Python "packages" (libraries)

What is an IDE?

● An integrated development environment (IDE) is software for building applications that


combines common developer tools into a single GUI.
● An IDE enables programmers to combine the different aspects of writing a computer
program.
● IDEs increase programmer productivity by introducing features like editing source code,
building executables, and debugging.

Different IDE’s for Python


● Jupyter
○ Jupyter is widely used in the field of data science
○ It is easy to use, interactive and allows live code sharing and visualization
○ Price: Free

● VS Code
○ Visual Studio Code is an open-source (and free) IDE created by Microsoft. It
finds great use for Python development
○ VS Code is lightweight and comes with powerful features that only some of the
paid IDEs offer
○ Price: Free

● Google Colab
○ “Colab” is a product from Google Research.
○ Colab allows anybody to write and execute arbitrary python code through the
browser, and is especially well suited to machine learning, data analysis and
education.
How to Install Anaconda

● Go to the link
● https://www.anaconda.com/products/distribution

● Download the anaconda Installer


● Double Click on the installer to launch it

● For Windows Click - 64 - Bit Graphical Installer(510 MB)


● Click on Next
● Click on “I agree”

● Click on just me (recommended)

● Choose the destination folder


● Recommended Path : C:\Users\hp\anaconda3
● Add Anaconda to your PATH environment variable and then click Install

● Click on Next
● Click on Finish and you are good to go.

● Go to Start menu and Search for Anaconda3


How to Open Jupyter

● Click on Jupyter Notebook(anaconda3)


● This will open Jupyter server

● It will open your default web browser and open Jupyter on the path -
http://127.0.0.1:8888

You have successfully installed and configured the Anaconda environment and you are
ready to start writing your first python code.
Introduction to Jupyter Notebook

What is a Jupyter Notebook ?

● The Jupyter Notebook is the original web application for creating and sharing
computational documents. It offers a simple, streamlined, document-centric experience.
● The Jupyter Notebook is an open-source web application that allows you to create and
share documents that contain live code, equations, visualizations, and narrative text. Its
uses include data cleaning and transformation, numerical simulation, statistical
modeling, data visualization, machine learning, and much more.

Features of Jupyter Notebook

● One major feature of the Jupyter notebook is the ability to display plots that are the
output of running code cells. The IPython kernel is designed to work seamlessly with the
matplotlib plotting library to provide this functionality. Specific plotting library integration is
a feature of the kernel.
● Language of choice - Jupyter supports over 40 programming languages, including
Python, R, Julia, and Scala.
● Share notebooks - Notebooks can be shared with others using email, Dropbox, GitHub
and the Jupyter Notebook Viewer.
● Interactive output - Your code can produce rich, interactive output: HTML, images,
videos, LaTeX, and custom MIME types.
● Big data integration - Leverage big data tools, such as Apache Spark, from Python, R,
and Scala. Explore that same data with pandas, scikit-learn, ggplot2, and TensorFlow.

Overview of Jupyter Environment


Jupyter Environment – Menu Bar

1. Fil Menu facilitates :


● Creating a new notebook
● Opening other files
● Saving the notebooks
● Renaming the notebook
● Download file as
HTML
.py files

2. Edit Menu mainly facilitates:


● Cut/copy/paste cells
● Delete cells
● Split cells
● Merging cells
● Find and replace
● Move cell up or down

3. View Menu mainly facilitates :


● Toggling Header
● Toggling Tool Bar
● Toggling Line Numbers

4. Cell Menu mainly facilitates :


● Cell Execution
● Customized cell execution
5. Kernel Menu :
● A notebook kernel is a “computational engine” that executes the
code contained in a Notebook document. The ipython kernel,
referenced in this guide, executes python code
● Kernels are programming language specific processes that run
independently and interact with the Jupyter Applications and their
user interfaces.
● Depending on the type of computations, the kernel may consume
significant CPU and RAM. Note that the RAM is not released until
the kernel is shut-down.
● Kernel Menu mainly facilitates :
○ Interrupt a cell
○ Restart the kernel
○ Toggling Line Numbers

Details of Jupyter Environment – ToolBar

Jupyter Environment – Code and Markdown cell


Variables And Data Types

What are Python Variables?

A variable is a container for a value. It can be assigned a name, you can use it to refer to it later
in the program.Based on the value assigned, the interpreter decides its data type. You can
always store a different type in a variable.

Every variable in Python is considered as an object. Variables in Python follow the standard
nomenclature of an alphanumeric name beginning in a letter or underscore.You do not need to
declare variables before using them, or declare their type. Variable names are case sensitive .
The value stored in a variable can be changed during program execution. A variable is only a
name given to a memory location, all the operations done on the variable affects that memory
location.

Syntax
var_name = value

Example:
a = 10
print(a)

Rules for creating variables in Python:

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

Valid variable names

Example:
prof_2022 = 8.5
_course = "Skill Academy"
Invalid variable names
Example:

7name = "Kartik"

File "<ipython-input-6-79c0033c1983>", line 1


7name = "Kartik"
^
SyntaxError: invalid syntax

Assigning Values to Variables

The declaration happens automatically when you assign a value to a variable. The equal sign
(=) is used to assign values to variables.The operand to the left of the = operator is the name of
the variable and the operand to the right of the = operator is the value stored in the variable.

Example:

x = "Welcome to Python" ( ‘x’ = variable name , “Welcome to Python”= Value assigned to the
variable “X”.)

Reassigning Values to Variables


A variable can be reinitialized, reassigned and redeclared.

Example:

p = 20
print(p)
p = "Python"
print(p)

Output:

20
Python

Python allows you to assign a single value to several variables simultaneously.

Example:

a=b=c=1
Python also assigns multiple objects to multiple variables.

Example:

a,b,c = 1,2,"john"

Python Comments

● Meant for internal documentation


● Written after #
● Comments don't get executed
● Used to explain the code to ourselves or other programmers
● Comments can be placed at the end of a line, and Python will ignore the rest of the line.

Example:

#This is a comment
print("Hello, World!")

print("Hello, World!")#This is a comment

Python Data Types

A Data type provides a set of values from which an expression may take its values. The type
defines the operations that can be done on the data, the meaning of the data, and the way
values of that type can be stored. Python supports the following data types:

● String - A string is an array of characters.


- A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. In python there is no character data type, a
character is a string of length one. It is represented by the str class.

Example:

v5 = "Welcome to Python"
print(v5)
print(type(v5))

Output:

Welcome to Python
<class 'str'>
● Integer - Integers or int are positive or negative whole numbers with no decimal point .
- Long integers have unlimited precision.

Example:

v1 = 10
print(v1)
print(type(v1))

Output:

10
<class 'int'>

● Float - floats represent real numbers and are written with a decimal point dividing the
integer and fractional parts.

Example:

v2 = 23.45
print(v2)
print(type(v2))

Output:

23.45
<class 'float'>

● Boolean - Data type with one of the two built-in values, True or False. Boolean objects
that are equal to True are truthy (true), and those equal to False are falsy (false).
Example:

v3 = False
print(v3)
print(type(v3))

Output:

False
<class 'bool'>

● None - None is used to define a null value. It is not the same as an empty string, False,
or a zero. It is a data type of the class NoneType object. Assigning a value of None to a
variable is one way to reset it to its original, empty state.
Example:

v4 = None
print(v4)
print(type(v4)

Output:

None
<class 'NoneType'>

Operators In Python
The operator can be defined as a symbol which is responsible for a particular operation
between two operands.The value that the operator operates on is called the operand.Operators
are the constructs which can manipulate the value of operands.These are the pillars of a
program on which the logic is built in a specific programming language.

For Example:

>>> 2+3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of
the operation.

Python provides a variety of operators:


● Arithmetic Operators
● Comparison Operators/ Relational Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators

Arithmetic Operators

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

+ Add two operands or unary x + y+ 2


plus

- Subtract right operand from x - y- 2


the left or unary minus

* Multiply two operands x*y

/ Divide left operand by the x/y


right one (always results into
float)

% Modulus - remainder of the x % y (remainder of x/y)


division of left operand by the
right

// Floor division - division that x // y


results into whole number
adjusted to the left in the
number line

** Exponent - left operand x**y (x to the power y)


raised to the power of right

Example:

x = 15
y=4

print('x + y =',x+y)
# Output: x + y = 19

print('x - y =',x-y)
# Output: x - y = 11

print('x * y =',x*y)
# Output: x * y = 60

print('x / y =',x/y)
# Output: x / y = 3.75

print('x // y =',x//y)
# Output: x // y = 3

print('x ** y =',x**y)
# Output: x ** y = 50625
Assignment operators

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


a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on
the left. There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.
The assignment operators are described in the following table:

Operator Description

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and
assigns the modified value back to the left operand.

-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to the left operand.

*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to the left operand.

%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3
= 1 to a.

Example:

a,b = 5, 2
print(a,b)
a += b # a = a + b
print(a,b)
a -= b # a = a - b
print(a,b)
b *= a
print(a,b) # b = b * a
a /= b
print(a,b) # a = a / b

Output

52
72
52
5 10
0.5 10
Print() And Input() Functions
The input () function:

Python has an input function which lets you ask a user for some text input. We call this function
to tell the program to stop and wait for the user to key in the data. In Python 2, we have a built-in
function raw_input(), whereas in Python 3, we have input(). The program will resume once the
user presses the ENTER or RETURN key.

The input () function:


● The purpose of input() function is to read input from the standard input (the keyboard, by
default).
● It accepts all user input as a string.
● The user may enter a number or a string but the input() function treats them as strings
only.
● Whatever you enter as input, the input function converts it into a string. if you enter an
integer value, the input() function converts it into a string. You need to explicitly convert it
into an integer in your code using typecasting.

The general format is:


input([prompt])

Here,
• The prompt is an optional parameter and where prompt is the string you wish to display on the
screen.

For example,
1. Accepting an Integer input from User, we need to convert an input string value into an
integer using an int() function.
num1 = int (input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print ('The sum of ', num1, ' and ', num2, ' is ',sum)

Output:

Enter the first number: 10


Enter second number: 30
The sum of 10 and 30 is 40

1. Accepting a float input from User, we need to convert an input string value into a float
using a float() function.

num1 = float (input("Enter first number: "))


num2 = float(input("Enter second number: "))
sum = num1 + num2
print ('The sum of ', num1, ' and ', num2, ' is ',sum)

Output:

Enter the first number: 10.5


Enter second number: 30.5
The sum of 10 and 30 is 41.0

The print () function:

To output your data to the screen, use the print() function. You can write print(argument) and this
will print the argument in the next line when you press the ENTER key.

How Print() Function works:


● The print ( ) function allows you to print out the value of a variable and strings in
parenthesis.
● The print() function will print as strings everything in a comma-separated sequence of
expressions, and it will separate the results with single blanks by default.
● The print() function prints strings in between quotes (either single or double). If a print
statement has quotes around text, the computer will print it out just as it is written.
● To print multiple items, separate them with commas. The print() function inserts a blank
between objects.
● The print() function automatically appends a newline to output. To print without a
newline, use the end separator after the last object.
Uses and Examples of print() function in Python
1. The print ( ) function can be used to print a blank line.
For example:

print('Learn data science from testbook')

Output:

Learn data science from testbook

2. The print() function prints the value of a variable.


For example:

N1 = 20
N2 = 30
Sum = N1 + N2
print(Sum) # prints a value​

Output:

50 #The above print statement receives a variable Sum

Parameters of print()

a) end - The end keyword is used to specify the content that is to be printed at the end of the
execution of the print() function.
● Value passed in the end parameter is displayed after all the variables are printed.
● The end parameter only takes a string.
● The default value of end is ‘\n’ (newline character).

Example:

print("Hello World") # end = '\n'


print('Learning Python') # end = '\n'

Output:

Hello World
Learning Python

b) sep(Separator) - The print() function can accept any number of positional arguments. These
arguments can be separated from each other using a “,” separator.
● Value passed in the sep parameter is used to separate different values which we wish
to print.
● The sep parameter only takes a string.
● The default value of sep is ‘ ’ (empty space).

Example:

x = "Delhi"
y = "Mumbai"
print(x,y)
print(x,y,sep=" and ")
print(x,y,sep="---")
print(x,y,sep=" and ",end=" are metro cities")

Output:

Delhi Mumbai
Delhi and Mumbai
Delhi---Mumbai
Delhi and Mumbai are metro cities

String Slicing
Python’s Len() Function:

The function len() is one of Python’s built-in functions.In programming, you may encounter a
situation where you want to know the length of a particular iterable object. That’s where the len()
method in Python comes in.
For example, you have a list of orders made by customers at your car dealership, which you
want to use to calculate the average car price. In order to do so, you’ll first need to know how
many cars were sold.So, by using the Python built-in-function i.e. len() Function you can get the
number of cars sold.

len() Syntax:

len(s)

len() Parameters

The len() function takes a single argument s, which can be:


● sequence - string, bytes, tuple, list, range OR,
● collection - dictionary, set, frozen set
len() Return Value

● len() function returns the number of elements or chars of an object.


● It throws the TypeError if the specified value is bool or int.

Example:

a = "India"
print(a)
print(len(a))

Output:

India
5

print("Total Elements in list: ", len([1,2,3,4,5]))


print("Total Elements in tuple: ",len((1,2,3,4,5)))
print("Total Elements in set: ",len({1,2,3,4,5}))
print(len(True))
print(len(100))

Output:

Total Elements in list: 5


Total Elements in tuple: 5
Total Elements in set: 5
TypeError: object of type 'bool' has no len()
TypeError: object of type 'int' has no len()

Python Strings:

Python has a built-in string class named "str" .Like many other popular programming languages,
strings in Python are arrays of bytes representing sequence of unicode characters.Python
strings are "immutable" which means they cannot be changed after they are created.

Syntax :

Variable_name = ‘string_name’
print(string_name)
How to create a string in Python?

● Strings can be created by enclosing characters inside a single quote or double-quotes.


● Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.

Example:

my_string = 'Hello'
print(my_string)

Output: Hello

my_string = "Hello"
print(my_string)

Output: Hello

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python"""
print(my_string)

Output: Hello, welcome to the world of Python.

Escape Sequence In String

● If you want to print a text like ``Hi there, "What's up?", you can neither use single quotes
nor double quotes. This will result in a SyntaxError as the text itself contains both single
and double quotes.

Examples:

print( " Hi there, "What's up? " " )

Output: SyntaxError: invalid syntax

print( ' Hi there, "What's up? " ' )

Output: SyntaxError: invalid syntax

● An escape sequence starts with a backslash and is interpreted differently.


● If you use a single quote to represent a string, all the single quotes inside the string must
be escaped. Similar is the case with double quotes.So, the correct syntax is:
Examples:

# using triple quotes


print(' ' ' Hi there, "What's up?" ' ' ' )

Output: Hi there, “what’s up?”

# escaping single quotes


print( 'Hi there, "What\'s up?" ' )

Output: Hi there, “what’s up?”

# escaping double quotes


print ( " Hi there, \"What's up?\" " )

Output: Hi there, “what’s up?”

String Indexing In Python

● Since a string is a sequence of characters, you can access its elements using an index
and a range of characters using slicing.
● Indexing means fetching a character at a particular index.
● A character at a particular index can be fetched by writing its corresponding index in
square brackets [] after the variable name in which the string is stored and Index starts
from 0.
● If you access a character out of index range will raise an IndexError.
● The index must be an integer and you can't use floats or other types, this will result in
TypeError.
● Python also allows negative indexing for its sequences i.e.The index of -1 refers to the
last item, -2 to the second last item and so on.

Rules of Indexing
● Indexing starts from left to right from 0 towards positive. The indexes range from 0 to
len(str)-1 from left to right.
● Indexing starts from right to left from -1 towards negative. The indexes range from -1 to
-len(str) from right to left

Examples:

Sammy Shark

#Positive Indexing
I.e.. s-0, a-1, m-2, m-3, y-4, space(_)- 5, s-6, h-7, a-8, r-9, k-10.
#Negative Indexing
I.e.. s-(-11), a-(-10), m-(-9), m-(-8), y-(-7), space(_)- (-6), s-(-5), h-(-4), a-(-3), r-(-2), k-(-1).

#Accessing string characters in Python


str = 'Hello Python'
print('str = ', str)

Output:Hello Python

#first character # Positive Indexing


print('str[0] = ', str[0])

Output: H

#last character # Negative Indexing


print('str[-1] = ', str[-1])

Output: n

# index must be in range


my_string[15]

Output: IndexError: string index out of range

String Slicing In Python

● We can access a range of items in a string by using the slicing operator :(colon).
● Slicing refers to extracting a particular part or portion of the string as per its own
requirements.i.e.allows you to get a substring from a string.

#Slicing Syntax

s = "Hello World"
S[start:end:step]
String Parameters:

● start: - Index from where slicing starts


● end: - Index where slicing ends.
● step: - Number of characters to jump while slicing. Default value is +1
○ All parameters are optional
○ Slicing can be performed
■ i) from left to right or
■ ii) from right to left
Left to Right slicing

● Step size has to be a positive number.


● Slicing is performed till index end-1 if end is mentioned, otherwise till right end.
● If start is not mentioned, then its default value is 0 (if slicing direction is from left to right).

s = "Skill Academy Testbook"


print(s)
print(len(s)) # Skill - 5, Academy - 7, Testbook - 8, space characters - 2

Output:

Skill Academy Testbook


22

Example:

s = "Skill Academy Testbook"

#positive Indexing

print(s[2:7]) # start = 2, end = 7, step = 1


print(s[10:18]) # start = 10, end = 18, step = 1
print(s[5:14]) # start = 5, end = 14, step = 1

Output: ill A
emy Test
Academy

#Negative Indexing

print(s[-14:-8]) # start = -14, end = -8, step = 1

Output: ademy

#Positive and negative Indexing

print(s[-15:-4:4]) # start = -15, end = -4, step = 4

Output: cme

Right to Left slicing

● Step size has to be a negative number.


● Slicing is performed till index end+1 if end is mentioned, otherwise till left end.
● If the combined direction of start:end and step are opposite, there is no output
Example:

s = "Skill Academy Testbook"

print(s[16:8:-1]) # start=16, end=8, step=-1


print(s[12:2:-1]) # start=12, end=2, step=-1
print(s[-5:8:-2]) # start=-5, end=8, step=-2
print(s[11:-1:-3]) # start=11,end=-1,step=-3 # No output.

Output: seT ymed


ymedacA ll
te md

String Methods
Properties Of String
● Strings are enclosed in single double or triple quotes
● Triple quotes is used for writing multiline strings
● String is immutable
● Python string operations:
● String supports concatenation(+).
● * (multiply) operator can be used with string

Python string operations:

We can perform many operations with strings which makes it one of the most used data types in
Python.

a) Concatenation of Strings In Python-


● Concatenation implies placing strings adjacent to each other.
● It can be implemented using + operator

Example:

a,b = "Happy", "Sunday"


print(a+b)
print(a+" "+b) # String concatenation proper method
print(a,b)

Output: HappySunday
Happy Sunday
Happy Sunday
b) * (multiply) operator In Python-
● We can multiply a string (using * operator) with an int value n.
● The resultant string would be replicated n number of times

Example:

s = "Nice "
print(s*4) # n = 4

Output: Nice Nice Nice Nice

String Functions/Methods

There are a lot of built-in functions in python to manipulate strings. But we can’t change any
existing strings since strings are immutable. Thus, these built-in-functions return a new string
and the original string remains unchanged.

Different Types of String Functions are:

1. upper() - It converts string into upper case. Numbers, special characters, space characters
cannot be converted to uppercase.

Example :
s1 = "Hello"
s2 = "Python"

print(s1.upper())
print(s2.upper())
print('data science'.upper())

Output:HELLO
PYTHON
DATA SCIENCE

2. lower() - It converts the string into lower case. Numbers, special characters, space
characters cannot be converted to lowercase.

Example:
s1 = "Hello"
s2 = "WELCOME"
print(s1.lower())
print(s2.lower())
Output:hello
welcome

3. capitalize() - Capitalizes, the first alphabet of the entire string

Example:
s = "learning python"

print(s.capitalize())

Output: Learning python

4. title() - Capitalizes, the first alphabet of the each word in the string

Example:
s = "learning python"

print(s.title())

Output: Learning Python

6. swapcase() - Converts uppercase characters to lowercase and vice-versa. It has no effect on


numbers, special characters and space characters.

Example:
s3 = "PytHoN 3.0"

print(s3.swapcase())

Output: pYThOn 3.0

7.isupper() - Returns True, if the string contains at least 1 uppercase and no lowercase
characters,otherwise False.

Example:
s5 = "INDIA %*& 1N23"

print(s5.isupper())

Output: True
8. islower() - Returns True, if the string contains at least 1 lowercase and no uppercase
characters,otherwise False.
Example:
print("google %*& 123".islower())

Output: True

9. islapha() - Returns True if the string contains only alphabets, otherwise False
Example:
s1,s2 = "tom and jerry" ,"hello587"
print(s1.isalpha())
print(s2.isalpha())

Output: False
False

10. isspace() - Returns True, if the string contains only space characters, otherwise False.
Example:
s1 = " @ "
print(s1.isspace())

Output: False

11. isalnum() - Returns True, if string contains only alphabet or numbers or a combination of
them, otherwise False
Example :
s1,s2 = "24","laptop"
print(s1.isalnum())
print(s2.isalnum())
Output: True
True

12. isdigit() - Returns True if the string contains only digit (0-9), otherwise False

Example:
s1 = "96@67!%52&80"
s2 = "34 45"

print(s1.isdigit())
print(s2.isdigit())

Output: False
False
Conditional Statements
In our everyday life, we take decisions and based on those decisions we take further actions.
Hence all our daily life activities depend on the decisions we make.The same goes with the
programming languages as well where we have to make some decisions and based on that the
program will execute.
Conditional Statements are also known as decision-making statements, involving
keywords such as if, elif, and else, provide Python programs with the ability to perform different
actions depending on a boolean condition: True or False. In Python we can define a series of
conditionals using ‘if’ for the first one, ‘elif’ for the rest, up until the final 'else’ for anything not
caught by the other conditionals.

For Example:

number = 5

if number > 2:
print("Number is bigger than 2.")
elif number < 2: # Optional clause (you can have multiple elifs)
print("Number is smaller than 2.")
else: # Optional clause (you can only have one else)
print("Number is 2.")

Outputs: Number is bigger than 2

Note: Using else if instead of elif will trigger a syntax error and is not allowed.

We use these conditional statements to execute specific blocks of code or set of arguments with
certain given conditions and only if the given condition is satisfied the program is run as needed.
If the condition is found to be false, then the optional else statement runs which contains some
code for the else condition.
If statements are used to implement conditional statements.There are 4 commonly used
if statements variants. They are as follows: a) If
b) If-else
c) If-elif-else
d) Nested-if

Indentation & its usage in conditional statements

Indentation refers to the spaces at the beginning of a code line. Python uses indentation to
indicate a block of code. It is necessary to indent the content after the ‘if statement’ has been
declared.
For Example:
Indentation using if-else Syntax

Indentation Errors
The spacing should be even and uniform throughout. Improper indentation can cause an
IndentationError .The below example raises an IndentationError:
If Statement
● The if statements checks the condition i.e. if statement is used to determine whether or
not a specific statement or set of statements will be performed.

● It comprises a piece of code if it evaluates to True, it executes the body of the if


statement. If it evaluates to False, then the condition will not be executed.
If Syntax

If statement Flowchart : It shows how the If statement executes its codes.


Example:

Note: In the above example since the given condition is satisfied


the program is run as needed.

If else statement

● The if-else statement comprises 2 blocks of statements out of which the first set of code
executes only when the if statement condition is true.

● If the condition is false, then the statements in the body of the else section will be
executed.

If-else Syntax

If else statement Flowchart : It shows how the If else statement executes its codes.

Example:

Note : Since the condition is found to be false, the optional


else statement runs which contains some code for the else
condition.
If-elif-else statement

● If-elif-else statement allows a user to choose from a variety of alternatives here. There
are many else if conditions declared.

● If the first condition is not true, then the next condition is executed, if this condition is also
not true then the next condition is executed and so on.

If-elif-else Syntax

If-elif-else statement Flowchart: It shows how the If-elif-else statement executes its codes.

Example:

Note : Here the first condition ‘If’ is not true, but the second ‘elif’ condition satisfies the given
condition so it gets executed.
Nested-if statement

● We can have an if…else statement inside another if…else statement. This is called
nested-if. Python provides us with the nesting method.

● These statements can be nested inside each other in any order. Indentation helps
identify the depth of nesting.

Nested-if Syntax

Nested-if statement Flowchart: It shows how the Nested-If statement executes its codes.

Example:
For Loop
Loop

● A loop is defined as a segment of code that executes multiple times


● A loop helps avoid code repetition.

For Loops

For loops, iterate over a collection of items, such as list or dict, and run a block of code with
each element from the collection.

Syntax of for loop to iterate over sequence:

Iteration

Iteration means traversing through each and every value in a sequence

Iterable or Iterator

Iterable or iterator is a sequence that can be iterated (traversed) upon.


Examples of Iterators in python: list, tuple, set, dictionary, strings, range()

Flowchart of forLoop

Example:
for i in [0, 1, 2, 3, 4]:
print(i)
The above for loop iterates over a list of numbers.
Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2,
etc. The output will be as follow:

0
1
2
3
4

Loop continues until we reach the last item in the sequence. The body of the for loop is
separated from the rest of the code using indentation.

The Range() Function : For loop syntax using range()

● Range is a function that returns a series of numbers under an iterable form, thus it can
be used in for loops:
● Range() function takes 3 parameters – start, end, step

○ start: Defines the starting value/index to begin iteration


○ end: Defines the end value/index to stop iteration
○ step: Defines the number of values/index to jump or skip while
○ iteration. Default value of step is +1

● If only one value is passed in range(), it is considered an end.


● If start is not mentioned, its default value is 0
● Iteration rule in ascending order:
○ Step has to be a positive number
○ Iteration proceeds till end-1
● Iteration rule in descending order:
○ Step has to be a negative number
○ Iteration proceeds till end+1

Syntax of for loop to iterate over index of a sequence


Example:

for i in range(4): # start=0, end=4, step=1 => ascending order => iterate till end-1
print(i)

Output:

0
1
2
3

While Loop
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true. And when the condition becomes false, the line immediately after the loop in
the program is executed.While loop falls under the category of indefinite iteration. Indefinite
iteration means that the number of times the loop is executed isn’t specified explicitly in
advance.i.e.We generally use this loop when we don't know the number of times to iterate
beforehand.

While Loop Flow Chart


In the while loop, the condition is checked first. The body of the loop is entered only if the
condition evaluates to True. After one iteration, the condition is checked again. This process
continues till the condition becomes False.

While loop can iterate over a block of code as long as the test expression (condition) is true.
In the while loop, the condition is checked first. The body of the loop is entered only if the
condition evaluates to True. After one iteration, the condition is checked again. This process
continues till the condition becomes False.

For eg -

Break and Continue Keywords


Break:
It is used to terminate the loop or statement in which it is present.
for val in "python":
if val == "t":
break
print(val)

Continue:
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.

for val in "python":


if val == "t":
continue
print(val)

You might also like