SlideShare uma empresa Scribd logo
1 de 61
Introduction To Python
Python is a widely used general-purpose, high level programming language. It
was created by Guido van Rossum in 1991 and further developed by the Python
Software Foundation. It was designed with an emphasis on code readability, and
its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite
different.
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret
and run our programs.
Windows: There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) that comes bundled with the
Python software downloaded from http://python.org/.
Linux: Python comes preinstalled with popular Linux distros such as Ubuntu
and Fedora. To check which version of Python you’re running, type “python”
in the terminal emulator. The interpreter should start and print the version
number.
macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to
manually install Python 3 from http://python.org/.
Reason for increasing popularity
1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in
comparison to languages such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented,
imperative and functional programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
5. Philosophy is “Simplicity is the best”.
PYTHON FEATURES
 Interpreted
 There are no separate compilation and execution steps like C and
C++.
 Directly run the program from the source code.
 Internally, Python converts the source code into an intermediate
form called bytecodes which is then translated into native language
of specific computer to run it.
 No need to worry about linking and loading with libraries, etc.
 Platform Independent
 Python programs can be developed and executed on multiple
operating system platforms.
 Python can be used on Linux, Windows, Macintosh, Solaris and
many more.
 Free and Open Source; Redistributable
 High-level Language
 In Python, no need to take care about low-level details such as
managing the memory used by the program.
 Simple
 Closer to English language;Easy to Learn
 More emphasis on the solution to the problem rather than the syntax
 Embeddable
 Python can be used within C/C++ program to give scripting
capabilities for the program’s users.
 Robust:
 Exceptional handling features
 Memory management techniques in built
 Rich Library Support
 The Python Standard Library is very vast.
 Known as the “batteries included” philosophy of Python ;It can
help do various things involving regular expressions,
documentation generation, unit testing, threading, databases, web
browsers, CGI, email, XML, HTML, WAV files, cryptography,
GUI and many more.
 Besides the standard library, there are various other high-quality
libraries such as the Python Imaging Library which is an amazingly
simple image manipulation library
Softwares making use of Python
Python has been successfully embedded in a number of software products as a
scripting language.
1. GNU Debugger uses Python as a pretty printer to show complex structures
such as C++ containers.
2. Python has also been used in artificial intelligence
3. Python is often used for natural language processing tasks.
Current Applications of Python
1. A number of Linux distributions use installers written in Python example in
Ubuntu we have the Ubiquity
2. Python has seen extensive use in the information security industry,
including in exploit development.
3. Raspberry Pi– single board computer uses Python as its principal user-
programming language.
4. Python is now being used Game Development areas also.
Pros:
1. Ease of use
2. Multi-paradigm Approach
Cons:
1. Slow speed of execution compared to C,C++
2. Absence from mobile computing and browsers
3. For the C,C++ programmers switching to python can be irritating as the
language requires proper indentation of code. Certain variable names
commonly used like sum are functions in python. So C, C++ programmers
have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python
Programming. Those having the knowledge of python may have more chances
of impressing the interviewing panel. So I would suggest that beginners should
start learning python and excel in it.
Python is a high-level, interpreted, and general-purpose dynamic programming
language that focuses on code readability. It has fewer steps when compared to
Java and C. It was founded in 1991 by developer Guido Van Rossum. Python
ranks among the most popular and fastest-growing languages in the world.
Python is a powerful, flexible, and easy-to-use language. In addition, the
community is very active there. It is used in many organizations as it supports
multiple programming paradigms. It also performs automatic memory
management.
Advantages :
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas for
data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the
value assigned, it takes data type)
8. Object-oriented language
9. Portable and Interactive
10.Ideal for prototypes – provide more functionality with less coding
11.Highly Efficient(Python’s clean object-oriented design provides enhanced
process control, and the language is equipped with excellent text processing
and integration capabilities, as well as its own unit testing framework, which
makes it more efficient.)
12.(IoT)Internet of Things Opportunities
13.Interpreted Language
14.Portable across Operating systems
Applications :
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/
computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10.Software Development
Organizations using Python :
1. Google(Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora
Python Installation on Windows
The installation requires downloading the official Python .exe installer and
running it on your system. The sections below will explain several options and
details during the installation process.
Step 1: Select Python Version
Deciding on a version depends on what you want to do in Python. The two major
versions are Python 2 and Python 3. Choosing one over the other might be better
depending on your project details. If there are no constraints, choose whichever
one you prefer.
We recommend Python 3, as Python 2 reached its end of life in 2020. Download
Python 2 only if you work with legacy scripts and older projects. Also, choose a
stable release over the newest since the newest release may have bugs and issues.
Step 2: Download Python Executable Installer
Start by downloading the Python executable installer for Windows:
1. Open a web browser and navigate to the Downloads for Windows section of
the official Python website.
2. Locate the desired Python version.
3. Click the link to download the file. Choose either the Windows 32-bit or 64-
bit installer.
The download is approximately 25MB.
Step 3: Run Executable Installer
The steps below guide you through the installation process:
1. Run the downloaded Python Installer.
2. The installation window shows two checkboxes:
 Admin privileges. The parameter controls whether to install Python for
the current or all system users. This option allows you to change the
installation folder for Python.
 Add Python to PATH. The second option places the executable in the
PATH variable after installation. You can also add Python to the PATH
environment variable manually later.
For the most straightforward installation, we recommend ticking both
checkboxes.
3. Select the Install Now option for the recommended installation (in that case,
skip the next two steps).
To adjust the default installation options, choose Customize installation instead
and proceed to the following step.
The default installation installs Python
to C:Users[user]AppDataLocalProgramsPythonPython[version] for the
current user. It includes IDLE (the default Python editor), the PIP package
manager, and additional documentation. The installer also creates necessary
shortcuts and file associations.
Customizing the installation allows changing these installation options and
parameters.
4. Choose the optional installation features. Python works without these features,
but adding them improves the program's usability.
Click Next to proceed to the Advanced Options screen.
5. The second part of customizing the installation includes advanced options.
Choose whether to install Python for all users. The option changes the install
location to C:Program FilesPython[version]. If selecting the location manually,
a common choice is C:Python[version] because it avoids spaces in the path, and
all users can access it. Due to administrative rights, both paths may cause issues
during package installation.
Other advanced options include creating shortcuts, file associations, and adding
Python to PATH.
After picking the appropriate options, click Install to start the installation.
6. Select whether to disable the path length limit. Choosing this option will allow
Python to bypass the 260-character MAX_PATH limit.
The option will not affect any other system settings, and disabling it resolves
potential name-length issues. We recommend selecting the option and closing the
setup.
Step 4: Add Python to Path (Optional)
If the Python installer does not include the Add Python to PATH checkbox or
you have not selected that option, continue in this step. Otherwise, skip to the
next step.
Adding the Python path to the PATH variable alleviates the need to use the full
path to access the Python program in the command line. It instructs Windows to
review all the folders added to the PATH environment variable and to look for
the python.exe program in those folders.
To add Python to PATH, do the following:
1. In the Start menu, search for Environment Variables and press Enter.
2. Click Environment Variables to open the overview screen.
3. Double-click Path on the list to edit it.
Alternatively, select the variable and click the Edit button.
4. Double-click the first empty field and paste the Python installation folder path.
Alternatively, click the New button instead and paste the path.
5. Click OK to save the changes. If the command prompt is open, restart it for the
following step.
Step 5: Verify Python Was Installed on Windows
The first way to verify that Python was installed successfully is through the
command line. Open the command prompt and run the following command:
python --version
The output shows the installed Python version.
The second way is to use the GUI to verify the Python installation. Follow the
steps below to run the Python interpreter or IDLE:
1. Navigate to the directory where Python was installed on the system.
2. Double-click python.exe (the Python interpreter) or IDLE.
3. The interpreter opens the command prompt and shows the following window:
Running IDLE opens Python's built-in IDE:
In both cases, the installed Python version shows on the screen, and the editor is
ready for use.
Step 6: Verify PIP Was Installed
To verify whether PIP was installed, enter the following command in the
command prompt:
pip --version
If it was installed successfully, you should see the PIP version number, the
executable path, and the Python version:
PIP has not been installed yet if you get the following output:
'pip' is not recognized as an internal or external command,
Operable program or batch file.
If an older version of Python is installed or the PIP installation option is disabled
during installation, PIP will not be available. To install PIP, see our article How
to Install PIP on Windows.
Step 7: Install virtualenv (Optional)
Python software packages install system-wide by default. Consequently,
whenever a single project-specific package is changed, it changes for all your
Python projects.
The virtualenv package enables making isolated local virtual environments for
Python projects. Virtual environments help avoid package conflicts and enable
choosing specific package versions per project.
To install virtualenv, run the following command in the command prompt:
pip install virtualenv
Wait for the installation to complete. Once done, it is installed on the system and
available for use.
Installation Of Anaconda
Using Anaconda:
Install Python and Jupyter using the Anaconda Distribution, which includes
Python, the Jupyter Notebook, and other commonly used packages for scientific
computing and data science. To install Anaconda, go through How to install
Anaconda on windows? and follow the instructions provided.
Using PIP:
Install Jupyter using the PIP package manager used to install and manage
software packages/libraries written in Python. To install pip, go through How to
install PIP on Windows? and follow the instructions provided.
Installing Jupyter Notebook using Anaconda
Anaconda is an open-source software that contains Jupyter, spyder, etc that are
used for large data processing, data analytics, heavy scientific computing.
Anaconda works for R and python programming language. Spyder(sub-
application of Anaconda) is used for python. Opencv for python will work in
spyder. Package versions are managed by the package management system
called conda. To install Jupyter using Anaconda, just go through the following
instructions:
Step 1: First, Launch the Anaconda Navigator
Step 2: Click on the Install Jupyter Notebook Button
The installation process is begin to Start!
Loading Packages:
Finished Installation:
Step 3: Now, click on Launch button to Launch the Jupyter.
Installing Jupyter Notebook using pip
PIP is a package management system used to install and manage software
packages/libraries written in Python. These files are stored in a large “on-line
repository” termed as Python Package Index (PyPI). pip uses PyPI as the default
source for packages and their dependencies.
Step 1: To install Jupyter using pip, we need to first check if pip is updated in
our system. Use the following command to update pip:
python -m pip install --upgrade pip
Step 2: After updating the pip version, follow the instructions provided below
to install Jupyter:
Command to install Jupyter:
python -m pip install jupyter
Beginning Installation:
Downloading Files and Data:
Installing Packages:
Finished Installation:
Launching Jupyter:
Use the following command to launch Jupyter using command-line:
jupyter notebook
Pyhton Program Syntax:
# Python code for "Hello World"
# nothing else to type...see how simple is the syntax.
print("Hello World")
# Python program to declare variables
myNumber = 3
print(myNumber)
myNumber2 = 4.5
print(myNumber2)
myNumber ="helloworld"
print(myNumber)
Input and Output
In this section, we will learn how to take input from the user and hence
manipulate it or simply display it. input() function is used to take input from the
user.
# Python program to illustrate
# getting input from user
name = input("Enter your name: ")
# user entered the name 'harssh'
print("hello", name)
# Python3 program to get input from user
# accepting integer from the user
# the return type of input() function is string ,
# so we need to convert the input to integer
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
num3 = num1 * num2
print("Product is: ", num3)
Python Variables
Python Variable is containers that store values. Python is not “statically typed”.
We do not need to declare variables before using them or declare their type. A
variable is created the moment we first assign a value to it. A Python variable is
a name given to a memory location. It is the basic unit of storage in a program.
In this article, we will see how to define a variable in Python.
Example of Variable in Python
An Example of a Variable in Python is a representational name that serves as a
pointer to an object. Once an object is assigned to a variable, it can be referred
to by that name. In layman’s terms, we can say that Variable in Python is
containers that store values.
Here we have stored “RKREDDY ” in a variable var, and when we call its
name the stored information will get printed.
Var = " RKREDDY "
print(Var)
Notes:
 The value stored in a variable can be changed during program execution.
 A Variables in Python is only a name given to a memory location, all the
operations done on the variable effects that memory location.
Rules for Python variables
 A Python variable name must start with a letter or the underscore character.
 A Python variable name cannot start with a number.
 A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variable in Python names are case-sensitive (name, Name, and NAME are
three different variables).
 The reserved words(keywords) in Python cannot be used to name the
variable in Python.
# valid variable name
hi = 1
hel_lo = 2
h_e_l_l_o = 5
_hello = 6
helo_ = 7
_HELLO_ = 8
print(hi, hel_lo, h_e_l_l_o)
print(__hello, helo_,_HELLO_)
Variables Assignment in Python
Here, we will define a variable in python. Here, clearly we have assigned a
number, a floating point number, and a string to a variable such as age, salary,
and name.
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Declaration and Initialization of Variables
Let’s see how to declare a variable and how to define a variable and print the
variable.
# declaring the var
Number = 100
# display
print( Number)
Redeclaring variables in Python
We can re-declare the Python variable once we have declared the variable and
define variable in python already.
# declaring the var
Number = 100
# display
print("Before declare: ", Number)
# re-declare the var
Number = 120.3
print("After re-declare:", Number)
Python Assign Values to Multiple Variables
Also, Python allows assigning a single value to several variables simultaneously
with “=” operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)
Assigning different values to multiple variables
Python allows adding different values in a single line with “,” operators.
a, b, c = 1, 20.2, "rkreddy"
print(a)
print(b) ,print(c)
Global and Local Python Variables
Local variables in Python are the ones that are defined and declared inside a
function. We can not call this variable outside the function.
# This function uses global variable s
def f():
s = "Welcome Avanthi"
print(s)
f()
Global variables in Python are the ones that are defined and declared outside a
function, and we need to use them inside a function.
# This function has a variable with
# name same as s
def f():
print(s)
# Global scope
s = "I love Avanthi college"
f()
Rules of global keyword
 If a variable is assigned a value anywhere within the function’s body, it’s
assumed to be local unless explicitly declared as global.
 Variables that are only referenced inside a function are implicitly global.
 We use a global in Python to use a global variable inside a function.
 There is no need to use a global keyword in Python outside a function.
Variable Types in Python
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instances (object) of these classes.
Built-in Python Data types are:
 Numeric
 Text Type
 Sequence Type (Python list, Python tuple, Python range)
 Boolean
 Set and Dictionary
# numberic
var = 123
print("Numeric data : ", var)
# Sequence Type
String1 = 'Welcome to the Avanthi World'
print("String with the use of Single Quotes: ")
print(String1)
# Boolean
print(type(True))
print(type(False))
# Creating a Set with
# the use of a String
set1 = set("Avanthi pg college")
print("nSet with the use of String: ")
print(set1)
# Creating a Dictionary
# with Integer Keys
Dict = {1: avanthi, 2: 'For', 3: MCA}
print("nDictionary with the use of Integer Keys: ")
print(Dict)
Operators in Python
In Python programming, Operators in general are used to perform operations on
values and variables. These are standard symbols used for logical and arithmetic
operations. In this article, we will look into different types of Python operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Operators in Python
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Assignment Operators
Identity Operators and Membership Operators
Operator Description Syntax
+ Addition: adds two operands x + y
– Subtraction: subtracts two operands x – y
* Multiplication: multiplies two operands x * y
/ Division (float): divides the first operand by the second x / y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided
by the second x % y
** Power: Returns first raised to power second x ** y
Example of Arithmetic Operators in Python
Division Operators
In Python programming language Division Operators allow you to divide two
numbers and return a quotient, i.e., the first number or number at the left is
divided by the second number or number at the right and returns the quotient.
There are two types of division operators:
Float division
Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two
numbers are integers. For example:
Example: The code performs division operations and prints the results. It
demonstrates that both integer and floating-point divisions return accurate
results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’.
Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being
passed. If any of the numbers is float, it returns output in float. It is also known
as Floor division because, if any number is negative, then the output will be
floored. For example:
Example: The code demonstrates integer (floor) division operations using the //
in Python operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’
equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division
returns the largest integer less than or equal to the division result.
Pythons
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Example:
a = 9
b = 4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x > y
< Less than: True if the left operand is less than the right x < y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or equal to
the right x >= y
<= Less than or equal to True if the left operand is less than or equal to the
right x <= y
= is an assignment operator and == comparison operator.
Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than the arithmetic
operators. All the operators within comparison operators have the same
precedence order.
Example of Comparison Operators in Python
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using various comparison
Python operators and prints the results. It checks if ‘a’ is greater than, less than,
equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’.
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR, and Logical NOT
operations. It is used to combine conditional statements.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x
Precedence of Logical Operators in Python
The precedence of Logical Operators in Python is as follows:
Logical not
logical and
logical or
Example of Logical Operators in Python
The following code shows how to implement Logical Operators in Python:
Example: The code performs logical operations with Boolean values. It checks
if both ‘a’ and ‘b’ are true (‘and’), if at least one of them is true (‘or’), and
negates the value of ‘a’ using ‘not’. The results are printed accordingly.
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Bitwise Operators in Python
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in Python is as follows:
Bitwise NOT
Bitwise Shift
Bitwise AND
Bitwise XOR
Bitwise OR
Bitwise Operators in Python
Here is an example showing how Bitwise Operators in Python work:
Example: The code demonstrates various bitwise operations with the values of
‘a’ and ‘b’. It performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift
(>>), and left shift (<<) operations and prints the results. These operations
manipulate the binary representations of the numbers.
Python
a = 10
b = 4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Assignment Operators in Python
Python Assignment operators are used to assign values to the variables.
Operator Description Syntax
= Assign the value of the right side of the expression to the left side
operand x = y + z
+= Add AND: Add right-side operand with left-side operand and then assign
to left operand a+=b a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign
to left operand a-=b a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign
to left operand a*=b a=a*b
/= Divide AND: Divide left operand with right operand and then assign to
left operand a/=b a=a/b
%= Modulus AND: Takes modulus using left and right operands and assign
the result to left operand a%=b a=a%b
//= Divide(floor) AND: Divide left operand with right operand and then
assign the value(floor) to left operanda//=b a=a//b
**= Exponent AND: Calculate exponent(raise power) value using operands
and assign value to left operand a**=b a=a**b
&= Performs Bitwise AND on operands and assign value to left operand
a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand
a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand
a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand
a>>=b a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand
a <<= b a= a << b
Assignment Operators in Python
Let’s see an example of Assignment Operators in Python.
Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then
performs a series of operations: addition, subtraction, multiplication, and a left
shift operation on ‘b’. The results of each operation are printed, showing the
impact of these operations on the value of ‘b’.
Python
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal
do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example Identity Operators in Python
Let’s see an example of Identity Operators in Python.
Example: The code uses identity operators to compare variables in Python. It
checks if ‘a’ is not the same object as ‘b’ (which is true because they have
different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’
was assigned the value of ‘a’).
Python
a = 10
b = 20
c = a
print(a is not b)
print(a is c)
Membership Operators in Python
In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Code to implement basic arithmetic operations on integers
num1 = 5
num2 = 2
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)
Code to implement Comparison operations on integers
num1 = 30
num2 = 35
if num1 > num2:
print("The first number is greater.")
elif num1 < num2:
print("The second number is greater.")
else:
print("The numbers are equal.")
Python If Else Statements – Conditional Statements
In both real life and programming, decision-making is crucial. We often face
situations where we need to make choices, and based on those choices, we
determine our next actions. Similarly, in programming, we encounter scenarios
where we must make decisions to control the flow of our code.
Conditional statements in Python play a key role in determining the direction of
program execution. Among these, If-Else statements are fundamental, providing
a way to execute different blocks of code based on specific conditions. As the
name suggests, If-Else statements offer two paths, allowing for different
outcomes depending on the condition evaluated.
Types of Control Flow in Python
Python If Statement
Python If Else Statement
Python Nested If Statement
Python Elif
Python If Statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not.
Flowchart of If Statement
Let’s look at the flow of code in the Python If statements.
Syntax of If Statement in Python
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
Syntax of If Statement in Python
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
#if syntax Python
if condition:
# Statements to execute if
# condition is true
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Python If Else Statement
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But if we want to do
something else if the condition is false, we can use the else statement with the
if statement Python to execute a block of code when the Python if condition is
false.
Flowchart of If Else Statement
Let’s look at the flow of code in an if else Python statement.
if condition:
# Statements to execute if
# condition is true
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Python If Else Statement
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But if we want to do
something else if the condition is false, we can use the else statement with the
if statement Python to execute a block of code when the Python if condition is
false.
Flowchart of If Else Statement
Let’s look at the flow of code in an if else Python statement.
Syntax of If Else in Python
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
# python program to illustrate else if in Python statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
If Else in Python using List Comprehension
In this example, we are using an Python else if statement in a list comprehension
with the condition that if the element of the list is odd then its digit sum will be
stored else not.
# Explicit function
def digitSum(n):
dsum = 0
for ele in str(n):
dsum += int(ele)
return dsum
# Initializing list
List = [367, 111, 562, 945, 6726, 873]
# Using the function on odd elements of the list
newList = [digitSum(i) for i in List if i & 1]
# Displaying new list
print(newList)
Python Nested If Statement
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
Yes, Python allows us to nest if statements within if statements. i.e., we can
place an if statement inside another if statement.
Flowchart of Python Nested if Statement
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Python Elif
Here, a user can decide among multiple options. The if statements are executed
from the top down.
As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final “else” statement will be executed.
Flowchart of Elif Statement in Python
Let’s look at the flow of control in if-elif-else ladder:
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a
given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax of while loop in Python
while expression:
statement(s)
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.
Statements represent all the statements indented by the same number of
character spaces after a programming construct are considered to be part of a
single block of code. Python uses indentation as its method of grouping
statements. When a while loop is executed, expr is first evaluated in a Boolean
context and if it is true, the loop body is executed. Then the expr is checked
again, if it is still true then the body is executed again and this continues until
the expression becomes false.
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello RKREDDY")
age = 28
# the test condition is always True
while age > 19:
print('Infinite Loop')
Python while loop with continue statement
Python Continue Statement returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
i = 0
a ="RKREDDY"
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
continue
print('Current Letter :', a[i])
i += 1
Python while loop with a break statement
Python Break Statement brings control out of the loop.
# break the loop as soon it sees 'e'
# or 's'
i = 0
a = RKREDDY
while i < len(a):
if a[i] == 'e' or a[i] == 's':
i += 1
break
print('Current Letter :', a[i])
i += 1
Python while loop with a pass statement
The Python pass statement to write empty loops. Pass is also used for empty
control statements, functions, and classes.
# An empty loop
a ="RKREDDY"
i = 0
while i < len(a):
i += 1
pass
print('Value of i :', i)
While loop with else
As discussed above, while loop executes the block until a condition is satisfied.
When the condition becomes false, the statement immediately after the loop is
executed. The else clause is only executed when your while condition becomes
false. If you break out of the loop, or if an exception is raised, it won’t be
executed.
Note: The else block just after for/while is executed only when the loop is NOT
terminated by a break statement.
# Python program to demonstrate
# while-else loop
i = 0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Breakn")
i = 0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
Python Functions
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Some Python Functions
ython Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
Types of Functions in Python
Below are the different types of functions in Python:
Built-in library function: These are Standard functions in Python that are
available to use.
User-defined function: We can create our own functions based on our
requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any
type of functionalities and properties to it as we require. By the following
example, we can understand how to write a function in Python. In this way we
can create Python function definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to GFG")
fun()
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the
return type of the function and data type of arguments. That is possible in Python
as well (specifically for Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later
in this article so you can come back to it again if not understood.
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the
number passed as an argument to the function is even or odd.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following function argument types in
Python:
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example
illustrates Default arguments to write functions in Python.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that
the caller does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname=’Avanthi’, lastname='Practice')
student(lastname='Practice', firstname=’Avanthi’)
Positional Arguments
We used the Position argument during the function call so that the first argument
(or value) is assigned to name and the second argument (or value) is assigned to
age. By changing the position, or if you forget the order of the positions, the
values can be used in the wrong places, as shown in the Case-2 example below,
where 27 is assigned to the name and Suraj is assigned to the age.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("nCase-2:")
nameAge(27, "Suraj")
Arbitrary Keyword Arguments
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a
variable number of arguments to a function using special symbols. There are
two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', ‘Avanthicollege’)
Example 2: Variable length keyword arguments
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first=’Avanthi’, mid='for', last=’Education’)
Docstring
The first string after the function is called the Document string or Docstring in
short. This is used to describe the functionality of the function. The use of
docstring in functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
print(evenOdd.__doc__)
Function to check if the number is even or odd
Python Function within Functions
A function that is defined inside another function is known as the inner function
or nested function. Nested functions can access variables of the enclosing scope.
Inner functions are used so that they can be protected from everything happening
outside the function.
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1():
s = 'I love Avanthicollege'
def f2():
print(s)
f2()
f1()
Recursive Functions in Python
Recursion in Python refers to when a function calls itself. There are many
instances when you have to build a recursive function to solve Mathematical
and Recursive Problems.
Using a recursive function should be done with caution, as a recursive function
can become like a non-terminating loop. It is better to check your exit statement
while creating a recursive function.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
Square of a number
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Python String
A String is a data structure in Python Programming that represents a sequence
of characters. It is an immutable data type, meaning that once you have created
a string, you cannot change it. Python String are used widely in many different
applications, such as storing and manipulating text data, representing names,
addresses, and other types of data that can be represented as text.
What is a String in Python?
Python Programming does not have a character data type, a single character is
simply a string with a length of 1. Let’s see the Python string syntax:
Syntax of String Data Type in Python
string_variable = 'Hello, world!'
string_0 = "A Computer Science portal for avanthi"
print(string_0)
print(type(string_0))
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even
triple quotes. Let us see how we can define a string in Python or how to write
string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String.
We will create a string using single quotes (‘ ‘), double quotes (” “), and triple
double quotes (“”” “””). The triple quotes can be used to declare multiline
strings in Python.
# Creating a String
# with single Quotes
String1 = 'Welcome to the rk mania'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a rk"
print("nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a person and I live in a world of 'avanthi'
print("nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple
# Quotes allows multiple lines
String1 = rk
For
Enjoyment'
print("nCreating a multiline String: ")
print(String1)Accessing characters in Python String
In Python Programming tutorials, individual characters of a String can be
accessed by using the method of Indexing. Indexing allows negative address
references to access characters from the back of the String, e.g. -1 refers to the
last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will cause
a TypeError.
# Python Program to Access
# characters of String
String1 = "RKREDDY"
print("Initial String: ")
print(String1)
# Printing First character
print("nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("nLast character of String is: ")
print(String1[-1])
String Slicing
In Python Programming tutorials, the String Slicing method is used to access a
range of characters in the String. Slicing in a String is done by using a Slicing
operator, i.e., a colon (:). One thing to keep in mind while using this method is
that the string returned after slicing includes the character at the start index but
not the character at the last index.
# Python Program to
# demonstrate String slicing
# Creating a String
String1 = 'RKREDDY'
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between
# 3rd and 2nd last character
print("nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Reversing a Python String
In Python Programming tutorials, By accessing characters from a string, we can
also reverse strings in Python Programming. We can Reverse a string by using
String slicing method.
#Program to reverse a string
avnt= 'avanthipgcollege'
print(avnt[::-1])
Deleting/Updating from a String
# Python Program to Update
# character of a String
String1 = "Hello, I'm a RK"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("nUpdating character at 2nd Index: ")
print(String2)
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Deleting a character
Python strings are immutable, that means we cannot delete a character from it.
When we try to delete thecharacter using the del keyword, it will generate an
error.
# Python Program to delete
# character of a String
String1 = "Hello, I'm a RK"
print("Initial String: ")
print(String1)
print("Deleting character at 2nd Index: ")
del String1[2]
print(String1)
# Python Program to Delete
# characters from a String
String1 = "Hello, I'm a RK"
print("Initial String: ")
print(String1)
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("nDeleting character at 2nd Index: ")
print(String2)
Deleting Entire String
# Python Program to Delete
# entire String
String1 = "Hello, I'm a RKREDDY"
print("Initial String: ")
print(String1)
# Deleting a String
# with the use of del
del String1
print("nDeleting entire String: ")
print(String1)
Formatting of Strings
Strings in Python or string data type in Python can be formatted with the use of
format() method which is a very versatile and powerful tool for formatting
Strings. Format method in String contains curly braces {} as placeholders which
can hold arguments according to position or keyword to specify the order.
# Python Program for Formatting of Strings
# Default order
String1 = "{} {} {}".format('RK', 'For', 'Education')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format(‘rk’, 'For', 'Life')
print("nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='rks', f='For', l='Life')
print("nPrint String in order of Keywords: ")
print(String1)
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('RK',
'for',
'rkonly')
print("nLeft, center and right alignment with Formatting: ")
print(String1)
# To demonstrate aligning of spaces
String1 = "n{0:^16} was founded in {1:<4}!".format("avanthiforeducation",
2009)
print(String1)
Python String constants
Built-In Function Description
string.ascii_letters Concatenation of the ascii_lowercase and
ascii_uppercase constants.
string.ascii_lowercase Concatenation of lowercase letters
string.ascii_uppercase Concatenation of uppercase letters
string.digits Digit in strings
string.hexdigits Hexadigit in strings
string.letters
concatenation of the strings lowercase and
uppercase
string.lowercase A string must contain lowercase letters.
string.octdigits Octadigit in a string
string.punctuation ASCII characters having punctuation characters.
string.printable String of characters which are printable
String.endswith() Returns True if a string ends with the given suffix
otherwise returns False
String.startswith() Returns True if a string starts with the given prefix
otherwise returns False
String.isdigit() Returns “True” if all characters in the string are
digits, Otherwise, It returns “False”.
Built-In Function Description
String.isalpha() Returns “True” if all characters in the string are
alphabets, Otherwise, It returns “False”.
string.isdecimal() Returns true if all characters in a string are decimal.
str.format()
one of the string formatting methods in Python3,
which allows multiple substitutions and value
formatting.
String.index Returns the position of the first occurrence of
substring in a string
string.uppercase A string must contain uppercase letters.
string.whitespace A string containing all characters that are considered
whitespace.
string.swapcase()
Method converts all uppercase characters to
lowercase and vice versa of the given string, and
returns it
replace() returns a copy of the string where all occurrences of
a substring is replaced with another substring.
Deprecated string functions
Built-In Function Description
string.Isdecimal Returns true if all characters in a string are decimal
String.Isalnum Returns true if all the characters in a given string are
alphanumeric.
string.Istitle Returns True if the string is a title cased string
Built-In Function Description
String.partition splits the string at the first occurrence of the separator
and returns a tuple.
String.Isidentifier Check whether a string is a valid identifier or not.
String.len Returns the length of the string.
String.rindex Returns the highest index of the substring inside the
string if substring is found.
String.Max Returns the highest alphabetical character in a string.
String.min Returns the minimum alphabetical character in a string.
String.splitlines Returns a list of lines in the string.
string.capitalize Return a word with its first character capitalized.
string.expandtabs Expand tabs in a string replacing them by one or more
spaces
string.find Return the lowest indexing a sub string.
string.rfind find the highest index.
string.count Return the number of (non-overlapping) occurrences of
substring sub in string
string.lower Return a copy of s, but with upper case, letters converted
to lower case.
Built-In Function Description
string.split Return a list of the words of the string, If the optional
second argument sep is absent or None
string.rsplit() Return a list of the words of the string s, scanning s from
the end.
rpartition() Method splits the given string into three parts
string.splitfields
Return a list of the words of the string when only used
with two arguments.
string.join Concatenate a list or tuple of words with intervening
occurrences of sep.
string.strip() It returns a copy of the string with both leading and
trailing white spaces removed
string.lstrip Return a copy of the string with leading white spaces
removed.
string.rstrip Return a copy of the string with trailing white spaces
removed.
string.swapcase Converts lower case letters to upper case and vice versa.
string.translate Translate the characters using table
string.upper lower case letters converted to upper case.
string.ljust left-justify in a field of given width.
string.rjust Right-justify in a field of given width.
Built-In Function Description
string.center() Center-justify in a field of given width.
string-zfill Pad a numeric string on the left with zero digits until the
given width is reached.
string.replace Return a copy of string s with all occurrences of
substring old replaced by new.
string.casefold() Returns the string in lowercase which can be used for
caseless comparisons.
string.encode Encodes the string into any encoding supported by
Python. The default encoding is utf-8.
string.maketrans Returns a translation table usable for str.translate()
Use of String in Python
 Strings are extensively used for text processing tasks such as searching,
extracting, modifying, and formatting text data.
 Strings are used to read input from users via the standard input (stdin) or
command-line arguments and to display output using print statements.
 Strings are used to represent data in various formats, including JSON, XML,
CSV, and more. They are often manipulated to extract specific information
or transform data structures.
 Strings are used to read from and write to text files. They facilitate operations
such as reading the contents of a file, writing data to a file, and manipulating
file paths.
 Strings support a wide range of operations such as concatenation, slicing,
indexing, searching, replacing, and splitting. These operations enable
developers to manipulate and transform text efficiently.
Advantages of String in Python:
 Strings are used at a larger scale i.e. for a wide areas of operations such as
storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
 Python has a rich set of string methods that allow you to manipulate and work
with strings in a variety of ways. These methods make it easy to perform
common tasks such as converting strings to uppercase or lowercase,
replacing substrings, and splitting strings into lists.
 Strings are immutable, meaning that once you have created a string, you
cannot change it. This can be beneficial in certain situations because it means
that you can be confident that the value of a string will not change
unexpectedly.
 Python has built-in support for strings, which means that you do not need to
import any additional libraries or modules to work with strings. This makes
it easy to get started with strings and reduces the complexity of your code.
 Python has a concise syntax for creating and manipulating strings, which
makes it easy to write and read code that works with strings.
Drawbacks of String in Python:
 When we are dealing with large text data, strings can be inefficient. For
instance, if you need to perform a large number of operations on a string,
such as replacing substrings or splitting the string into multiple substrings, it
can be slow and consume a lot resources.
 Strings can be difficult to work with when you need to represent complex
data structures, such as lists or dictionaries. In these cases, it may be more
efficient to use a different data type, such as a list or a dictionary, to represent
the data.

Mais conteúdo relacionado

Semelhante a Python Notes for mca i year students osmania university.docx

Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
Aditya Patel
 
session5-Getting stated with Python.pdf
session5-Getting stated with Python.pdfsession5-Getting stated with Python.pdf
session5-Getting stated with Python.pdf
AyushDutta32
 

Semelhante a Python Notes for mca i year students osmania university.docx (20)

Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Basic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptxBasic Python Introduction Lecture 1.pptx
Basic Python Introduction Lecture 1.pptx
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
 
session5-Getting stated with Python.pdf
session5-Getting stated with Python.pdfsession5-Getting stated with Python.pdf
session5-Getting stated with Python.pdf
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
Summer Training Project.pdf
Summer Training Project.pdfSummer Training Project.pdf
Summer Training Project.pdf
 
Python basic
Python basicPython basic
Python basic
 
python-handbook.pdf
python-handbook.pdfpython-handbook.pdf
python-handbook.pdf
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
 
Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Language
 
python unit2.pptx
python unit2.pptxpython unit2.pptx
python unit2.pptx
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)
 
Python for Beginners.docx
Python for Beginners.docxPython for Beginners.docx
Python for Beginners.docx
 
PYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptxPYTHON TUTORIALS.pptx
PYTHON TUTORIALS.pptx
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction python
Introduction pythonIntroduction python
Introduction python
 
Type of apps that can be developed using python
Type of apps that can be developed using pythonType of apps that can be developed using python
Type of apps that can be developed using python
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
 

Mais de Ramakrishna Reddy Bijjam

Mais de Ramakrishna Reddy Bijjam (20)

Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
 
Auxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptxAuxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptx
 
Python With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxPython With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptx
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptx
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
 
Random Forest Decision Tree.pptx
Random Forest Decision Tree.pptxRandom Forest Decision Tree.pptx
Random Forest Decision Tree.pptx
 
K Means Clustering in ML.pptx
K Means Clustering in ML.pptxK Means Clustering in ML.pptx
K Means Clustering in ML.pptx
 
Pandas.pptx
Pandas.pptxPandas.pptx
Pandas.pptx
 
Python With MongoDB.pptx
Python With MongoDB.pptxPython With MongoDB.pptx
Python With MongoDB.pptx
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
BInary file Operations.pptx
BInary file Operations.pptxBInary file Operations.pptx
BInary file Operations.pptx
 
Data Science in Python.pptx
Data Science in Python.pptxData Science in Python.pptx
Data Science in Python.pptx
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
 
HTML files in python.pptx
HTML files in python.pptxHTML files in python.pptx
HTML files in python.pptx
 
Regular Expressions in Python.pptx
Regular Expressions in Python.pptxRegular Expressions in Python.pptx
Regular Expressions in Python.pptx
 
datareprersentation 1.pptx
datareprersentation 1.pptxdatareprersentation 1.pptx
datareprersentation 1.pptx
 
Apriori.pptx
Apriori.pptxApriori.pptx
Apriori.pptx
 
Eclat.pptx
Eclat.pptxEclat.pptx
Eclat.pptx
 

Último

Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Último (20)

Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 

Python Notes for mca i year students osmania university.docx

  • 1. Introduction To Python Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions: Python 2 and Python 3. Both are quite different. Beginning with Python programming: 1) Finding an Interpreter: Before we start Python programming, we need to have an interpreter to interpret and run our programs. Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/. Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number. macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/. Reason for increasing popularity 1. Emphasis on code readability, shorter codes, ease of writing 2. Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java. 3. Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural. 4. There exists inbuilt functions for almost all of the frequently used concepts. 5. Philosophy is “Simplicity is the best”. PYTHON FEATURES  Interpreted  There are no separate compilation and execution steps like C and C++.
  • 2.  Directly run the program from the source code.  Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.  No need to worry about linking and loading with libraries, etc.  Platform Independent  Python programs can be developed and executed on multiple operating system platforms.  Python can be used on Linux, Windows, Macintosh, Solaris and many more.  Free and Open Source; Redistributable  High-level Language  In Python, no need to take care about low-level details such as managing the memory used by the program.  Simple  Closer to English language;Easy to Learn  More emphasis on the solution to the problem rather than the syntax  Embeddable  Python can be used within C/C++ program to give scripting capabilities for the program’s users.  Robust:  Exceptional handling features  Memory management techniques in built  Rich Library Support  The Python Standard Library is very vast.  Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.  Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library Softwares making use of Python Python has been successfully embedded in a number of software products as a scripting language. 1. GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers. 2. Python has also been used in artificial intelligence 3. Python is often used for natural language processing tasks.
  • 3. Current Applications of Python 1. A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity 2. Python has seen extensive use in the information security industry, including in exploit development. 3. Raspberry Pi– single board computer uses Python as its principal user- programming language. 4. Python is now being used Game Development areas also. Pros: 1. Ease of use 2. Multi-paradigm Approach Cons: 1. Slow speed of execution compared to C,C++ 2. Absence from mobile computing and browsers 3. For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these. Industrial Importance Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it. Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management. Advantages : 1. Presence of third-party modules 2. Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) 3. Open source and community development 4. Versatile, Easy to read, learn and write 5. User-friendly data structures 6. High-level language 7. Dynamically typed language(No need to mention data type based on the value assigned, it takes data type)
  • 4. 8. Object-oriented language 9. Portable and Interactive 10.Ideal for prototypes – provide more functionality with less coding 11.Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.) 12.(IoT)Internet of Things Opportunities 13.Interpreted Language 14.Portable across Operating systems Applications : 1. GUI based desktop applications 2. Graphic design, image processing applications, Games, and Scientific/ computational Applications 3. Web frameworks and applications 4. Enterprise and Business applications 5. Operating Systems 6. Education 7. Database Access 8. Language Development 9. Prototyping 10.Software Development Organizations using Python : 1. Google(Components of Google spider and Search Engine) 2. Yahoo(Maps) 3. YouTube 4. Mozilla 5. Dropbox 6. Microsoft 7. Cisco 8. Spotify 9. Quora Python Installation on Windows The installation requires downloading the official Python .exe installer and running it on your system. The sections below will explain several options and details during the installation process.
  • 5. Step 1: Select Python Version Deciding on a version depends on what you want to do in Python. The two major versions are Python 2 and Python 3. Choosing one over the other might be better depending on your project details. If there are no constraints, choose whichever one you prefer. We recommend Python 3, as Python 2 reached its end of life in 2020. Download Python 2 only if you work with legacy scripts and older projects. Also, choose a stable release over the newest since the newest release may have bugs and issues. Step 2: Download Python Executable Installer Start by downloading the Python executable installer for Windows: 1. Open a web browser and navigate to the Downloads for Windows section of the official Python website. 2. Locate the desired Python version. 3. Click the link to download the file. Choose either the Windows 32-bit or 64- bit installer. The download is approximately 25MB. Step 3: Run Executable Installer The steps below guide you through the installation process:
  • 6. 1. Run the downloaded Python Installer. 2. The installation window shows two checkboxes:  Admin privileges. The parameter controls whether to install Python for the current or all system users. This option allows you to change the installation folder for Python.  Add Python to PATH. The second option places the executable in the PATH variable after installation. You can also add Python to the PATH environment variable manually later. For the most straightforward installation, we recommend ticking both checkboxes. 3. Select the Install Now option for the recommended installation (in that case, skip the next two steps). To adjust the default installation options, choose Customize installation instead and proceed to the following step.
  • 7. The default installation installs Python to C:Users[user]AppDataLocalProgramsPythonPython[version] for the current user. It includes IDLE (the default Python editor), the PIP package manager, and additional documentation. The installer also creates necessary shortcuts and file associations. Customizing the installation allows changing these installation options and parameters. 4. Choose the optional installation features. Python works without these features, but adding them improves the program's usability.
  • 8. Click Next to proceed to the Advanced Options screen. 5. The second part of customizing the installation includes advanced options. Choose whether to install Python for all users. The option changes the install location to C:Program FilesPython[version]. If selecting the location manually, a common choice is C:Python[version] because it avoids spaces in the path, and all users can access it. Due to administrative rights, both paths may cause issues during package installation. Other advanced options include creating shortcuts, file associations, and adding Python to PATH.
  • 9. After picking the appropriate options, click Install to start the installation. 6. Select whether to disable the path length limit. Choosing this option will allow Python to bypass the 260-character MAX_PATH limit.
  • 10. The option will not affect any other system settings, and disabling it resolves potential name-length issues. We recommend selecting the option and closing the setup. Step 4: Add Python to Path (Optional) If the Python installer does not include the Add Python to PATH checkbox or you have not selected that option, continue in this step. Otherwise, skip to the next step. Adding the Python path to the PATH variable alleviates the need to use the full path to access the Python program in the command line. It instructs Windows to review all the folders added to the PATH environment variable and to look for the python.exe program in those folders. To add Python to PATH, do the following: 1. In the Start menu, search for Environment Variables and press Enter. 2. Click Environment Variables to open the overview screen.
  • 11. 3. Double-click Path on the list to edit it. Alternatively, select the variable and click the Edit button.
  • 12. 4. Double-click the first empty field and paste the Python installation folder path. Alternatively, click the New button instead and paste the path. 5. Click OK to save the changes. If the command prompt is open, restart it for the following step. Step 5: Verify Python Was Installed on Windows The first way to verify that Python was installed successfully is through the command line. Open the command prompt and run the following command: python --version The output shows the installed Python version. The second way is to use the GUI to verify the Python installation. Follow the steps below to run the Python interpreter or IDLE:
  • 13. 1. Navigate to the directory where Python was installed on the system. 2. Double-click python.exe (the Python interpreter) or IDLE. 3. The interpreter opens the command prompt and shows the following window: Running IDLE opens Python's built-in IDE: In both cases, the installed Python version shows on the screen, and the editor is ready for use. Step 6: Verify PIP Was Installed To verify whether PIP was installed, enter the following command in the command prompt: pip --version
  • 14. If it was installed successfully, you should see the PIP version number, the executable path, and the Python version: PIP has not been installed yet if you get the following output: 'pip' is not recognized as an internal or external command, Operable program or batch file. If an older version of Python is installed or the PIP installation option is disabled during installation, PIP will not be available. To install PIP, see our article How to Install PIP on Windows. Step 7: Install virtualenv (Optional) Python software packages install system-wide by default. Consequently, whenever a single project-specific package is changed, it changes for all your Python projects. The virtualenv package enables making isolated local virtual environments for Python projects. Virtual environments help avoid package conflicts and enable choosing specific package versions per project. To install virtualenv, run the following command in the command prompt: pip install virtualenv
  • 15. Wait for the installation to complete. Once done, it is installed on the system and available for use. Installation Of Anaconda Using Anaconda: Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. To install Anaconda, go through How to install Anaconda on windows? and follow the instructions provided. Using PIP: Install Jupyter using the PIP package manager used to install and manage software packages/libraries written in Python. To install pip, go through How to install PIP on Windows? and follow the instructions provided. Installing Jupyter Notebook using Anaconda Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming language. Spyder(sub- application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda. To install Jupyter using Anaconda, just go through the following instructions:
  • 16. Step 1: First, Launch the Anaconda Navigator Step 2: Click on the Install Jupyter Notebook Button
  • 17. The installation process is begin to Start! Loading Packages:
  • 18. Finished Installation: Step 3: Now, click on Launch button to Launch the Jupyter.
  • 19. Installing Jupyter Notebook using pip PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. Step 1: To install Jupyter using pip, we need to first check if pip is updated in our system. Use the following command to update pip: python -m pip install --upgrade pip Step 2: After updating the pip version, follow the instructions provided below to install Jupyter: Command to install Jupyter: python -m pip install jupyter Beginning Installation: Downloading Files and Data:
  • 21. Finished Installation: Launching Jupyter: Use the following command to launch Jupyter using command-line: jupyter notebook
  • 22. Pyhton Program Syntax: # Python code for "Hello World" # nothing else to type...see how simple is the syntax. print("Hello World") # Python program to declare variables myNumber = 3 print(myNumber) myNumber2 = 4.5 print(myNumber2) myNumber ="helloworld" print(myNumber) Input and Output In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user. # Python program to illustrate # getting input from user name = input("Enter your name: ") # user entered the name 'harssh' print("hello", name) # Python3 program to get input from user # accepting integer from the user # the return type of input() function is string , # so we need to convert the input to integer num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) num3 = num1 * num2 print("Product is: ", num3)
  • 23. Python Variables Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. In this article, we will see how to define a variable in Python. Example of Variable in Python An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s terms, we can say that Variable in Python is containers that store values. Here we have stored “RKREDDY ” in a variable var, and when we call its name the stored information will get printed. Var = " RKREDDY " print(Var) Notes:  The value stored in a variable can be changed during program execution.  A Variables in Python is only a name given to a memory location, all the operations done on the variable effects that memory location. Rules for Python variables  A Python variable name must start with a letter or the underscore character.  A Python variable name cannot start with a number.  A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).  Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).  The reserved words(keywords) in Python cannot be used to name the variable in Python. # valid variable name hi = 1 hel_lo = 2 h_e_l_l_o = 5 _hello = 6
  • 24. helo_ = 7 _HELLO_ = 8 print(hi, hel_lo, h_e_l_l_o) print(__hello, helo_,_HELLO_) Variables Assignment in Python Here, we will define a variable in python. Here, clearly we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name. # An integer assignment age = 45 # A floating point salary = 1456.8 # A string name = "John" print(age) print(salary) print(name) Declaration and Initialization of Variables Let’s see how to declare a variable and how to define a variable and print the variable. # declaring the var Number = 100 # display print( Number)
  • 25. Redeclaring variables in Python We can re-declare the Python variable once we have declared the variable and define variable in python already. # declaring the var Number = 100 # display print("Before declare: ", Number) # re-declare the var Number = 120.3 print("After re-declare:", Number) Python Assign Values to Multiple Variables Also, Python allows assigning a single value to several variables simultaneously with “=” operators. For example: a = b = c = 10 print(a) print(b) print(c) Assigning different values to multiple variables Python allows adding different values in a single line with “,” operators. a, b, c = 1, 20.2, "rkreddy" print(a) print(b) ,print(c)
  • 26. Global and Local Python Variables Local variables in Python are the ones that are defined and declared inside a function. We can not call this variable outside the function. # This function uses global variable s def f(): s = "Welcome Avanthi" print(s) f() Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function. # This function has a variable with # name same as s def f(): print(s) # Global scope s = "I love Avanthi college" f() Rules of global keyword  If a variable is assigned a value anywhere within the function’s body, it’s assumed to be local unless explicitly declared as global.  Variables that are only referenced inside a function are implicitly global.  We use a global in Python to use a global variable inside a function.  There is no need to use a global keyword in Python outside a function. Variable Types in Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (object) of these classes. Built-in Python Data types are:  Numeric  Text Type  Sequence Type (Python list, Python tuple, Python range)  Boolean  Set and Dictionary
  • 27. # numberic var = 123 print("Numeric data : ", var) # Sequence Type String1 = 'Welcome to the Avanthi World' print("String with the use of Single Quotes: ") print(String1) # Boolean print(type(True)) print(type(False)) # Creating a Set with # the use of a String set1 = set("Avanthi pg college") print("nSet with the use of String: ") print(set1) # Creating a Dictionary # with Integer Keys Dict = {1: avanthi, 2: 'For', 3: MCA} print("nDictionary with the use of Integer Keys: ") print(Dict) Operators in Python In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /, etc. OPERAND: It is the value on which the operator is applied. Types of Operators in Python Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Assignment Operators
  • 28. Identity Operators and Membership Operators Operator Description Syntax + Addition: adds two operands x + y – Subtraction: subtracts two operands x – y * Multiplication: multiplies two operands x * y / Division (float): divides the first operand by the second x / y // Division (floor): divides the first operand by the second x // y % Modulus: returns the remainder when the first operand is divided by the second x % y ** Power: Returns first raised to power second x ** y Example of Arithmetic Operators in Python Division Operators In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. There are two types of division operators: Float division Floor division Float division The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:
  • 29. Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’. Python print(5/5) print(10/2) print(-10/2) print(20.0/2) Integer division( Floor division) The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example: Example: The code demonstrates integer (floor) division operations using the // in Python operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less than or equal to the division result. Pythons print(10//3) print (-5//2) print (5.0//2) print (-5.0//2) Example: a = 9 b = 4 add = a + b sub = a - b mul = a * b mod = a % b p = a ** b print(add) print(sub) print(mul) print(mod) print(p)
  • 30. Comparison of Python Operators In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition. Operator Description Syntax > Greater than: True if the left operand is greater than the right x > y < Less than: True if the left operand is less than the right x < y == Equal to: True if both operands are equal x == y != Not equal to – True if operands are not equal x != y >= Greater than or equal to True if the left operand is greater than or equal to the right x >= y <= Less than or equal to True if the left operand is less than or equal to the right x <= y = is an assignment operator and == comparison operator. Precedence of Comparison Operators in Python In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order. Example of Comparison Operators in Python Let’s see an example of Comparison Operators in Python. Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’. a = 13 b = 33 print(a > b) print(a < b) print(a == b) print(a != b) print(a >= b) print(a <= b) Logical Operators in Python Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements. Operator Description Syntax
  • 31. and Logical AND: True if both the operands are true x and y or Logical OR: True if either of the operands is true x or y not Logical NOT: True if the operand is false not x Precedence of Logical Operators in Python The precedence of Logical Operators in Python is as follows: Logical not logical and logical or Example of Logical Operators in Python The following code shows how to implement Logical Operators in Python: Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true (‘and’), if at least one of them is true (‘or’), and negates the value of ‘a’ using ‘not’. The results are printed accordingly. a = True b = False print(a and b) print(a or b) print(not a) Bitwise Operators in Python Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers. Operator Description Syntax & Bitwise AND x & y | Bitwise OR x | y ~ Bitwise NOT ~x ^ Bitwise XOR x ^ y >> Bitwise right shift x>> << Bitwise left shift x<< Precedence of Bitwise Operators in Python The precedence of Bitwise Operators in Python is as follows: Bitwise NOT Bitwise Shift Bitwise AND Bitwise XOR Bitwise OR Bitwise Operators in Python
  • 32. Here is an example showing how Bitwise Operators in Python work: Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’. It performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers. Python a = 10 b = 4 print(a & b) print(a | b) print(~a) print(a ^ b) print(a >> 2) print(a << 2) Assignment Operators in Python Python Assignment operators are used to assign values to the variables. Operator Description Syntax = Assign the value of the right side of the expression to the left side operand x = y + z += Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b a=a+b -= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b *= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b a=a*b /= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b %= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b a=a%b //= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operanda//=b a=a//b **= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b a=a**b &= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b |= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
  • 33. ^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b >>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b <<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b Assignment Operators in Python Let’s see an example of Assignment Operators in Python. Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’. The results of each operation are printed, showing the impact of these operations on the value of ‘b’. Python a = 10 b = a print(b) b += a print(b) b -= a print(b) b *= a print(b) b <<= a print(b) Identity Operators in Python In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. is True if the operands are identical is not True if the operands are not identical Example Identity Operators in Python Let’s see an example of Identity Operators in Python. Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).
  • 34. Python a = 10 b = 20 c = a print(a is not b) print(a is c) Membership Operators in Python In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence. in True if value is found in the sequence not in True if value is not found in the sequence x = 24 y = 20 list = [10, 20, 30, 40, 50] if (x not in list): print("x is NOT present in given list") else: print("x is present in given list") if (y in list): print("y is present in given list") else: print("y is NOT present in given list") Code to implement basic arithmetic operations on integers num1 = 5 num2 = 2 sum = num1 + num2 difference = num1 - num2 product = num1 * num2 quotient = num1 / num2 remainder = num1 % num2 print("Sum:", sum) print("Difference:", difference)
  • 35. print("Product:", product) print("Quotient:", quotient) print("Remainder:", remainder) Code to implement Comparison operations on integers num1 = 30 num2 = 35 if num1 > num2: print("The first number is greater.") elif num1 < num2: print("The second number is greater.") else: print("The numbers are equal.") Python If Else Statements – Conditional Statements In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determining the direction of program execution. Among these, If-Else statements are fundamental, providing a way to execute different blocks of code based on specific conditions. As the name suggests, If-Else statements offer two paths, allowing for different outcomes depending on the condition evaluated. Types of Control Flow in Python Python If Statement Python If Else Statement Python Nested If Statement Python Elif Python If Statement The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not. Flowchart of If Statement Let’s look at the flow of code in the Python If statements.
  • 36. Syntax of If Statement in Python Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. Syntax of If Statement in Python Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. #if syntax Python if condition: # Statements to execute if # condition is true if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. # python program to illustrate If statement i = 10 if (i > 15): print("10 is less than 15") print("I am Not in if") Python If Else Statement
  • 37. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the if statement Python to execute a block of code when the Python if condition is false. Flowchart of If Else Statement Let’s look at the flow of code in an if else Python statement. if condition: # Statements to execute if # condition is true if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. # python program to illustrate If statement i = 10 if (i > 15): print("10 is less than 15") print("I am Not in if") Python If Else Statement The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the if statement Python to execute a block of code when the Python if condition is false. Flowchart of If Else Statement Let’s look at the flow of code in an if else Python statement.
  • 38. Syntax of If Else in Python if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false # python program to illustrate else if in Python statement i = 20 if (i < 15): print("i is smaller than 15") print("i'm in if Block") else: print("i is greater than 15") print("i'm in else Block") print("i'm not in if and not in else Block") If Else in Python using List Comprehension In this example, we are using an Python else if statement in a list comprehension with the condition that if the element of the list is odd then its digit sum will be stored else not. # Explicit function def digitSum(n): dsum = 0 for ele in str(n): dsum += int(ele) return dsum # Initializing list List = [367, 111, 562, 945, 6726, 873] # Using the function on odd elements of the list newList = [digitSum(i) for i in List if i & 1] # Displaying new list print(newList) Python Nested If Statement A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement.
  • 39. Yes, Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement. Flowchart of Python Nested if Statement if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here # python program to illustrate nested If statement i = 10 if (i == 10): # First if statement if (i < 15): print("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12):
  • 40. print("i is smaller than 12 too") else: print("i is greater than 15") Python Elif Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed. Flowchart of Elif Statement in Python Let’s look at the flow of control in if-elif-else ladder: Syntax: if (condition): statement elif (condition): statement .
  • 41. . else: statement Example i = 20 if (i == 10): print("i is 10") elif (i == 15): print("i is 15") elif (i == 20): print("i is 20") else: print("i is not present") Python While Loop Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Python while expression: statement(s)
  • 42. 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. Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then the body is executed again and this continues until the expression becomes false. # Python program to illustrate # while loop count = 0 while (count < 3): count = count + 1 print("Hello RKREDDY") age = 28 # the test condition is always True while age > 19: print('Infinite Loop') Python while loop with continue statement Python Continue Statement returns the control to the beginning of the loop. # Prints all letters except 'e' and 's' i = 0 a ="RKREDDY" while i < len(a): if a[i] == 'e' or a[i] == 's': i += 1 continue print('Current Letter :', a[i]) i += 1 Python while loop with a break statement Python Break Statement brings control out of the loop. # break the loop as soon it sees 'e'
  • 43. # or 's' i = 0 a = RKREDDY while i < len(a): if a[i] == 'e' or a[i] == 's': i += 1 break print('Current Letter :', a[i]) i += 1 Python while loop with a pass statement The Python pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes. # An empty loop a ="RKREDDY" i = 0 while i < len(a): i += 1 pass print('Value of i :', i) While loop with else As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. Note: The else block just after for/while is executed only when the loop is NOT terminated by a break statement. # Python program to demonstrate # while-else loop i = 0 while i < 4: i += 1
  • 44. print(i) else: # Executed because no break in for print("No Breakn") i = 0 while i < 4: i += 1 print(i) break else: # Not executed as there is a break print("No Break") Python Functions Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again. Some Python Functions ython Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again. Some Benefits of Using Functions Increase Code Readability Increase Code Reusability Python Function Declaration The syntax to declare a function is: Types of Functions in Python Below are the different types of functions in Python:
  • 45. Built-in library function: These are Standard functions in Python that are available to use. User-defined function: We can create our own functions based on our requirements. Creating a Function in Python We can define a function in Python, using the def keyword. We can add any type of functionalities and properties to it as we require. By the following example, we can understand how to write a function in Python. In this way we can create Python function definition by using def keyword. # A simple Python function def fun(): print("Welcome to GFG") fun() Python Function with Parameters If you have experience in C/C++ or Java then you must be thinking about the return type of the function and data type of arguments. That is possible in Python as well (specifically for Python 3.5 and above). Python Function Syntax with Parameters def function_name(parameter: data_type) -> return_type: """Docstring""" # body of the function return expression The following example uses arguments and parameters that you will learn later in this article so you can come back to it again if not understood. def add(num1: int, num2: int) -> int: """Add two numbers""" num3 = num1 + num2 return num3 num1, num2 = 5, 15 ans = add(num1, num2) print(f"The addition of {num1} and {num2} results {ans}.") # some more functions def is_prime(n):
  • 46. if n in [2, 3]: return True if (n == 1) or (n % 2 == 0): return False r = 3 while r * r <= n: if n % r == 0: return False r += 2 return True print(is_prime(78), is_prime(79)) Python Function Arguments Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma. In this example, we will create a simple function in Python to check whether the number passed as an argument to the function is even or odd. # A simple Python function to check # whether x is even or odd def evenOdd(x): if (x % 2 == 0): print("even") else: print("odd") evenOdd(2) evenOdd(3) Types of Python Function Arguments Python supports various types of arguments that can be passed at the time of the function call. In Python, we have the following function argument types in Python: Default argument Keyword arguments (named arguments) Positional arguments Arbitrary arguments (variable-length arguments *args and **kwargs) Let’s discuss each type in detail. Default Arguments
  • 47. A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument. The following example illustrates Default arguments to write functions in Python. # Python program to demonstrate # default arguments def myFun(x, y=50): print("x: ", x) print("y: ", y) myFun(10) Keyword Arguments The idea is to allow the caller to specify the argument name with values so that the caller does not need to remember the order of parameters. # Python program to demonstrate Keyword Arguments def student(firstname, lastname): print(firstname, lastname) # Keyword arguments student(firstname=’Avanthi’, lastname='Practice') student(lastname='Practice', firstname=’Avanthi’) Positional Arguments We used the Position argument during the function call so that the first argument (or value) is assigned to name and the second argument (or value) is assigned to age. By changing the position, or if you forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to the age. def nameAge(name, age): print("Hi, I am", name) print("My age is ", age) # You will get correct output because # argument is given in order print("Case-1:") nameAge("Suraj", 27) # You will get incorrect output because # argument is not in order print("nCase-2:")
  • 48. nameAge(27, "Suraj") Arbitrary Keyword Arguments In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args in Python (Non-Keyword Arguments) **kwargs in Python (Keyword Arguments) Example 1: Variable length non-keywords argument # Python program to illustrate # *args for variable number of arguments def myFun(*argv): for arg in argv: print(arg) myFun('Hello', 'Welcome', 'to', ‘Avanthicollege’) Example 2: Variable length keyword arguments # Python program to illustrate # *kwargs for variable number of keyword arguments def myFun(**kwargs): for key, value in kwargs.items(): print("%s == %s" % (key, value)) # Driver code myFun(first=’Avanthi’, mid='for', last=’Education’) Docstring The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice. The below syntax can be used to print out the docstring of a function. Syntax: print(function_name.__doc__)
  • 49. Example: Adding Docstring to the function # A simple Python function to check # whether x is even or odd def evenOdd(x): """Function to check if the number is even or odd""" if (x % 2 == 0): print("even") else: print("odd") # Driver code to call the function print(evenOdd.__doc__) Function to check if the number is even or odd Python Function within Functions A function that is defined inside another function is known as the inner function or nested function. Nested functions can access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. # Python program to # demonstrate accessing of # variables of nested functions def f1(): s = 'I love Avanthicollege' def f2(): print(s) f2() f1() Recursive Functions in Python
  • 50. Recursion in Python refers to when a function calls itself. There are many instances when you have to build a recursive function to solve Mathematical and Recursive Problems. Using a recursive function should be done with caution, as a recursive function can become like a non-terminating loop. It is better to check your exit statement while creating a recursive function. def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(4)) Square of a number def square_value(num): """This function returns the square value of the entered number""" return num**2 print(square_value(2)) print(square_value(-4)) Python String A String is a data structure in Python Programming that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Python String are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text. What is a String in Python? Python Programming does not have a character data type, a single character is simply a string with a length of 1. Let’s see the Python string syntax: Syntax of String Data Type in Python string_variable = 'Hello, world!' string_0 = "A Computer Science portal for avanthi" print(string_0) print(type(string_0))
  • 51. Creating a String in Python Strings in Python can be created using single quotes or double quotes or even triple quotes. Let us see how we can define a string in Python or how to write string in Python. Example: In this example, we will demonstrate different ways to create a Python String. We will create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can be used to declare multiline strings in Python. # Creating a String # with single Quotes String1 = 'Welcome to the rk mania' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a rk" print("nString with the use of Double Quotes: ") print(String1) # Creating a String # with triple Quotes String1 = '''I'm a person and I live in a world of 'avanthi' print("nString with the use of Triple Quotes: ") print(String1) # Creating String with triple # Quotes allows multiple lines String1 = rk For Enjoyment' print("nCreating a multiline String: ") print(String1)Accessing characters in Python String In Python Programming tutorials, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
  • 52. While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError. # Python Program to Access # characters of String String1 = "RKREDDY" print("Initial String: ") print(String1) # Printing First character print("nFirst character of String is: ") print(String1[0]) # Printing Last character print("nLast character of String is: ") print(String1[-1]) String Slicing In Python Programming tutorials, the String Slicing method is used to access a range of characters in the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One thing to keep in mind while using this method is that the string returned after slicing includes the character at the start index but not the character at the last index. # Python Program to # demonstrate String slicing # Creating a String
  • 53. String1 = 'RKREDDY' print("Initial String: ") print(String1) # Printing 3rd to 12th character print("nSlicing characters from 3-12: ") print(String1[3:12]) # Printing characters between # 3rd and 2nd last character print("nSlicing characters between " + "3rd and 2nd last character: ") print(String1[3:-2]) Reversing a Python String In Python Programming tutorials, By accessing characters from a string, we can also reverse strings in Python Programming. We can Reverse a string by using String slicing method. #Program to reverse a string avnt= 'avanthipgcollege' print(avnt[::-1]) Deleting/Updating from a String # Python Program to Update # character of a String String1 = "Hello, I'm a RK" print("Initial String: ") print(String1) # Updating a character of the String ## As python strings are immutable, they don't support item updation directly ### there are following two ways #1 list1 = list(String1) list1[2] = 'p' String2 = ''.join(list1) print("nUpdating character at 2nd Index: ") print(String2)
  • 54. String3 = String1[0:2] + 'p' + String1[3:] print(String3) Deleting a character Python strings are immutable, that means we cannot delete a character from it. When we try to delete thecharacter using the del keyword, it will generate an error. # Python Program to delete # character of a String String1 = "Hello, I'm a RK" print("Initial String: ") print(String1) print("Deleting character at 2nd Index: ") del String1[2] print(String1) # Python Program to Delete # characters from a String String1 = "Hello, I'm a RK" print("Initial String: ") print(String1) # Deleting a character # of the String String2 = String1[0:2] + String1[3:] print("nDeleting character at 2nd Index: ") print(String2) Deleting Entire String # Python Program to Delete # entire String String1 = "Hello, I'm a RKREDDY" print("Initial String: ") print(String1) # Deleting a String
  • 55. # with the use of del del String1 print("nDeleting entire String: ") print(String1) Formatting of Strings Strings in Python or string data type in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order. # Python Program for Formatting of Strings # Default order String1 = "{} {} {}".format('RK', 'For', 'Education') print("Print String in default order: ") print(String1) # Positional Formatting String1 = "{1} {0} {2}".format(‘rk’, 'For', 'Life') print("nPrint String in Positional order: ") print(String1) # Keyword Formatting String1 = "{l} {f} {g}".format(g='rks', f='For', l='Life') print("nPrint String in order of Keywords: ") print(String1) # String alignment String1 = "|{:<10}|{:^10}|{:>10}|".format('RK', 'for', 'rkonly') print("nLeft, center and right alignment with Formatting: ") print(String1) # To demonstrate aligning of spaces String1 = "n{0:^16} was founded in {1:<4}!".format("avanthiforeducation", 2009) print(String1)
  • 56. Python String constants Built-In Function Description string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants. string.ascii_lowercase Concatenation of lowercase letters string.ascii_uppercase Concatenation of uppercase letters string.digits Digit in strings string.hexdigits Hexadigit in strings string.letters concatenation of the strings lowercase and uppercase string.lowercase A string must contain lowercase letters. string.octdigits Octadigit in a string string.punctuation ASCII characters having punctuation characters. string.printable String of characters which are printable String.endswith() Returns True if a string ends with the given suffix otherwise returns False String.startswith() Returns True if a string starts with the given prefix otherwise returns False String.isdigit() Returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
  • 57. Built-In Function Description String.isalpha() Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. string.isdecimal() Returns true if all characters in a string are decimal. str.format() one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. String.index Returns the position of the first occurrence of substring in a string string.uppercase A string must contain uppercase letters. string.whitespace A string containing all characters that are considered whitespace. string.swapcase() Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it replace() returns a copy of the string where all occurrences of a substring is replaced with another substring. Deprecated string functions Built-In Function Description string.Isdecimal Returns true if all characters in a string are decimal String.Isalnum Returns true if all the characters in a given string are alphanumeric. string.Istitle Returns True if the string is a title cased string
  • 58. Built-In Function Description String.partition splits the string at the first occurrence of the separator and returns a tuple. String.Isidentifier Check whether a string is a valid identifier or not. String.len Returns the length of the string. String.rindex Returns the highest index of the substring inside the string if substring is found. String.Max Returns the highest alphabetical character in a string. String.min Returns the minimum alphabetical character in a string. String.splitlines Returns a list of lines in the string. string.capitalize Return a word with its first character capitalized. string.expandtabs Expand tabs in a string replacing them by one or more spaces string.find Return the lowest indexing a sub string. string.rfind find the highest index. string.count Return the number of (non-overlapping) occurrences of substring sub in string string.lower Return a copy of s, but with upper case, letters converted to lower case.
  • 59. Built-In Function Description string.split Return a list of the words of the string, If the optional second argument sep is absent or None string.rsplit() Return a list of the words of the string s, scanning s from the end. rpartition() Method splits the given string into three parts string.splitfields Return a list of the words of the string when only used with two arguments. string.join Concatenate a list or tuple of words with intervening occurrences of sep. string.strip() It returns a copy of the string with both leading and trailing white spaces removed string.lstrip Return a copy of the string with leading white spaces removed. string.rstrip Return a copy of the string with trailing white spaces removed. string.swapcase Converts lower case letters to upper case and vice versa. string.translate Translate the characters using table string.upper lower case letters converted to upper case. string.ljust left-justify in a field of given width. string.rjust Right-justify in a field of given width.
  • 60. Built-In Function Description string.center() Center-justify in a field of given width. string-zfill Pad a numeric string on the left with zero digits until the given width is reached. string.replace Return a copy of string s with all occurrences of substring old replaced by new. string.casefold() Returns the string in lowercase which can be used for caseless comparisons. string.encode Encodes the string into any encoding supported by Python. The default encoding is utf-8. string.maketrans Returns a translation table usable for str.translate() Use of String in Python  Strings are extensively used for text processing tasks such as searching, extracting, modifying, and formatting text data.  Strings are used to read input from users via the standard input (stdin) or command-line arguments and to display output using print statements.  Strings are used to represent data in various formats, including JSON, XML, CSV, and more. They are often manipulated to extract specific information or transform data structures.  Strings are used to read from and write to text files. They facilitate operations such as reading the contents of a file, writing data to a file, and manipulating file paths.  Strings support a wide range of operations such as concatenation, slicing, indexing, searching, replacing, and splitting. These operations enable developers to manipulate and transform text efficiently. Advantages of String in Python:  Strings are used at a larger scale i.e. for a wide areas of operations such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.  Python has a rich set of string methods that allow you to manipulate and work with strings in a variety of ways. These methods make it easy to perform common tasks such as converting strings to uppercase or lowercase, replacing substrings, and splitting strings into lists.
  • 61.  Strings are immutable, meaning that once you have created a string, you cannot change it. This can be beneficial in certain situations because it means that you can be confident that the value of a string will not change unexpectedly.  Python has built-in support for strings, which means that you do not need to import any additional libraries or modules to work with strings. This makes it easy to get started with strings and reduces the complexity of your code.  Python has a concise syntax for creating and manipulating strings, which makes it easy to write and read code that works with strings. Drawbacks of String in Python:  When we are dealing with large text data, strings can be inefficient. For instance, if you need to perform a large number of operations on a string, such as replacing substrings or splitting the string into multiple substrings, it can be slow and consume a lot resources.  Strings can be difficult to work with when you need to represent complex data structures, such as lists or dictionaries. In these cases, it may be more efficient to use a different data type, such as a list or a dictionary, to represent the data.