0% found this document useful (0 votes)
22 views58 pages

IPP Unit-1 Material

This document provides an introduction to Python programming, covering its features, history, and basic syntax. It highlights Python's readability, ease of use for beginners, and its applications in various fields such as data science and web development. Additionally, it includes installation instructions, verification of installation, and examples of Python programming in both interactive and script modes.

Uploaded by

vaishnavbhavna17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views58 pages

IPP Unit-1 Material

This document provides an introduction to Python programming, covering its features, history, and basic syntax. It highlights Python's readability, ease of use for beginners, and its applications in various fields such as data science and web development. Additionally, it includes installation instructions, verification of installation, and examples of Python programming in both interactive and script modes.

Uploaded by

vaishnavbhavna17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

RNGPIT Introduction to Python Programming

Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English words frequently whereas other languages use punctuation, and it has
fewer syntactic constructions than other languages.
● Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
● Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
● Python is Object-Oriented − Python supports the Object-Oriented style or technique of
programming that encapsulates code within objects.
● Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.

History of Python
● Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
● Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
● Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
● Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.

Python Basic Syntax


There is no use of curly braces or semicolon in Python programming language. It is English-like language.
But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace
before the statement when it is needed.
For example –

In the above example, the statements that are the same level to the right belong to the function. Generally,
we can use four whitespaces to define indentation.

Python Features
Python's features include −
● Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
● Easy-to-read − Python code is more clearly defined and visible to the eyes.
● Easy-to-maintain − Python's source code is fairly easy-to-maintain.
1
RNGPIT Introduction to Python Programming

● A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
● Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
● Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
● Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
● Databases − Python provides interfaces to all major commercial databases.
● GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
● Scalable − Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
● It supports functional and structured programming methods as well as OOP.
● It can be used as a scripting language or can be compiled to byte-code for building large applications.
● It provides very high-level dynamic data types and supports dynamic type checking.
● It supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Pre-installation check for Python:


● Operating system details in your computer/laptop such as Windows, Linux or Mac
● Operating system type whether it is 32 bit or 64 bit
● Python version to be installed
● Methods to get Python interpreter from the official website
● How to verify Python installation
● How to run Python code – Script mode or shell mode
● Tools to develop Python code
● How to install modules and third-party libraries.

Checking Python version in Windows:


In some of the operating systems, Python is pre-installed. In Windows, chances are remote that you have
Python by default. Let us quickly check whether we have got Python installed in our system.

Go to the command line prompt and type “python” then press enter key. If there is a response from a Python
interpreter we can understand that Python is already installed and it would show a version number in its
display. If there is no response about Python and it’s version number then we need to follow the guidelines
below to install Python. These steps are applicable if you may want to install a new version as well.

2
RNGPIT Introduction to Python Programming

How to get Python interpreter from the official website


The Python installation process will vary depending on the operating system that you use. Each operating
system follows a different approach to install software from their official websites. We will show a few
methods below starting from Windows.

Installing Python on Windows


We need to download a Windows installer for Python from Python’s official website. Open the browser and
go to the Python Windows download page. At the top of the page, you will see the text – Python Releases
for Windows.
Below that you will see the link which says Latest Python 3 release Python 3.x.x(At present it says Python
3.8.1 Dec 18, 2019).
You need to scroll down and go to the stable releases section. In the stable releases section, you will find the
latest stable release Python 3.x.x subsection. There are multiple files are listed for download including

● Download Windows x86-64 executable installer (this is for 64-bit operating system) and
● Download Windows x86 executable installer (this is for 32-bit operating system).

3
RNGPIT Introduction to Python Programming

Click the link that corresponds to your operating system and download the installer onto your computer.

Once the download is complete, run it by double-clicking the installer file. In the installation process,
select Install now option. It will show the default location where Python is going to be installed. Please make
sure that Add to path checkbox is selected. This will add Python in the system Path variable. Operating
systems check the contents of the path variable to see the installation directory of a software application or
language.

Once Python is included in the path variable, we can run Python from any directory. By default, we can run
Python only from the directory where it’s installed.

4
RNGPIT Introduction to Python Programming

Python will be installed successfully within a few minutes.

That’s great. We’re done with setting up the environment.

5
RNGPIT Introduction to Python Programming

How to verify Python installation – Windows


Now we can go to the command line console and type “python.” You will see python with the installed
version number. If you want to come out of interactive Python, then type quit() then press the enter key.

Now as mentioned earlier let us create a hello.py and run python program using the command python
hello.py. You will see the output “Hello Python” on the screen.

Python Interpreter online

If you want to try Python online without installing Python on your computer, there are many online
interpreters available on the internet with limited features.

Try it out on Python shell from Python’s official website.

Why learn Python?


Python provides many useful features to the programmer. These features make it most popular and widely
used language. We have listed below few-essential feature of Python.

6
RNGPIT Introduction to Python Programming

● Easy to use and Learn


● Expressive Language
● Interpreted Language
● Object-Oriented Language
● Open Source Language
● Extensible
● Learn Standard Library
● GUI Programming Support
● Integrated
● Embeddable
● Dynamic Memory Allocation
● Wide Range of Libraries and Frameworks

Where is Python used?


Python is a general-purpose, popular programming language and it is used in almost every technical field.
The various areas of Python use are given below.

● Data Science
● Date Mining
● Desktop Applications
● Console-based Applications
● Mobile Applications
● Software Development
● Artificial Intelligence
● Web Applications
● Enterprise Applications
● 3D CAD Applications
● Machine Learning
● Computer Vision or Image Processing Applications.
● Speech Recognitions

Python Popular Frameworks and Libraries

Python has wide range of libraries and frameworks widely used in various fields such as machine learning,
artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as
follows.

● Web development (Server-side) - Django Flask, Pyramid, CherryPy


● GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
● Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
● Mathematics - Numpy, Pandas, etc.

First Python Program


Let us execute programs in different modes of programming.

Interactive Mode Programming

Invoking the interpreter without passing a script file as a parameter brings up the following prompt −

7
RNGPIT Introduction to Python Programming

Type the following text at the Python prompt and press the Enter –

If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!"); However in Python version 2.4.3, this produces the following result −

Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and continues until the script
is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source
code in a test.py file –

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows –

This produces the following result –

Let us try another way to execute a Python script. Here is the modified test.py file

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows –

This produces the following result –

8
RNGPIT Introduction to Python Programming

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
● Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
● Starting an identifier with a single leading underscore indicates that the identifier is private.
● Starting an identifier with two leading underscores indicates a strongly private identifier.
● If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.

Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example –

9
RNGPIT Introduction to Python Programming

However, the following block generates an error –

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks
even if they are without braces.

10
RNGPIT Introduction to Python Programming

Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example –

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example –

Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal –

Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.

This produces the following result –

You can type a comment on the same line after a statement or expression –

You can comment multiple lines as follows –

11
RNGPIT Introduction to Python Programming

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments:

Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence
we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value
with its type.

The variable a holds integer value five and we did not define its type. Python interpreter will automatically
interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type()
function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.

Output:

12
RNGPIT Introduction to Python Programming

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as a string
whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python Numbers
data-type. Python provides the type() function to know the data-type of the variable. Similarly, the
isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;

13
RNGPIT Introduction to Python Programming

Output:

Python supports three types of numeric data.


1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15
decimal points.
3. Complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In Python, we
can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and operators to
perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
The following example illustrates the string in Python.
Example - 1

Output:

14
RNGPIT Introduction to Python Programming

Example – 2

Output:

List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored
in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they were working with the strings.
Consider the following example.

15
RNGPIT Introduction to Python Programming

Output:

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.

Output:

16
RNGPIT Introduction to Python Programming

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table
where each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary
Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Consider the following example.

Output:

Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the given
statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F'. Consider the following example.

Output:

17
RNGPIT Introduction to Python Programming

Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and
has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of
the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the
curly braces and separated by the comma. It can contain various types of values. Consider the following
example.

Output:

Python Keywords
Every scripting language has designated words or keywords, with particular definitions and usage
guidelines. Python is no exception. The fundamental constituent elements of any Python program are Python
keywords.
This topic will give you a basic overview of all Python keywords and a detailed discussion of some
important keywords that are frequently used.

18
RNGPIT Introduction to Python Programming

Introducing Python Keywords


Python keywords are unique words reserved with defined meanings and functions that we can only apply for
those functions. You'll never need to import any keywords into your program because they're permanently
present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are
constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes in our
code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to assign anything to
a built-in method or type, you will not receive a SyntaxError message; however, it is still not a smart idea.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have shown a
complete list of Python keywords for the reader's reference.

In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced,
while others may be deleted. By writing the following statement into the coding window, you can anytime
retrieve the collection of keywords in the version you are working on.

Python Operators
Python Operators in general are used to perform operations on values and variables. These are standard
symbols used for the purpose of logical and arithmetic operations. In this unit, we will look into different
types of Python operators.
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.

Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition, subtraction,
multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers is an integer
and to obtain an integer result in Python 3.x floored (// integer) is used.

19
RNGPIT Introduction to Python Programming

Example: Arithmetic operators in Python

20
RNGPIT Introduction to Python Programming

Output:

Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False according to the
condition.

21
RNGPIT Introduction to Python Programming

Example: Comparison Operators in Python

Output:

22
RNGPIT Introduction to Python Programming

Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine
conditional statements.

Example: Logical Operators in Python

Output:

23
RNGPIT Introduction to Python Programming

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary
numbers.

Example: Bitwise Operators in Python

Output:

24
RNGPIT Introduction to Python Programming

Assignment Operators
Assignment operators are used to assign values to the variables.

Example: Assignment Operators in Python

Output:

25
RNGPIT Introduction to Python Programming

Identity Operators
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.

Example: Identity Operator

Output:

Membership Operators:
in and not in are the membership operators used to test whether a value or variable is in a sequence.

Example: Membership Operator

Output:

26
RNGPIT Introduction to Python Programming

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

The following table lists all operators from highest precedence to lowest.

27
RNGPIT Introduction to Python Programming

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first multiplies 3*2 and then add into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom.
Example:

28
RNGPIT Introduction to Python Programming

Output:
When you execute the above program, it produces the following result −

Python Variables:
● Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
● In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
● Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
● It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Variable Declaration Rule:


Variables are the example of identifiers. An Identifier is used to identify the literals used in the program.
● The first character of the variable must be an alphabet or underscore ( _ ).
● All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z),
underscore, or digit (0-9).
● Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
● Identifier name must not be similar to any keyword defined in the language.
● Identifier names are case sensitive; for example, my name, and MyName is not the same.
● Examples of valid identifiers: a123, _n, n_9, etc.
● Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values:


Python does not bind us to declare a variable before using it in the application. It allows us to create a
variable at the required time.
We don't need to explicitly declare variables in Python. When we assign any value to the variable, that
variable is declared automatically.
The equal (=) operator is used to assign value to a variable.

the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.

29
RNGPIT Introduction to Python Programming

The variable b refers to the same object that a points to because Python does not create another object.
Let's assign the new value to b. Now both variables will refer to the different objects.

Python manages memory efficiently if we assign the same variable to two different values.

Python Variable Names:


Variable names of any length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore
characters(_).
Consider the following,
name = "Durva"
age = 17
marks = 80.00
print(name)
print(age)
print(marks)

30
RNGPIT Introduction to Python Programming

Valid variables name

The multi-word keywords can be created by the following method,


Camel Case:
In the camel case, each word or abbreviation in the middle of begins with a capital letter. There is no
intervention of whitespace. For example - nameOfStudent, valueOfVaraible, etc.

Pascal Case:
It is the same as the Camel Case, but here the first word is also capital. For example - NameOfStudent, etc.

Snake Case:
In the snake case, Words are separated by the underscore. For example - name_of_student, etc.

Multiple Assignment:
Python allows us to assign a value to multiple variables in a single statement, which is also known as
multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or
assigning multiple values to multiple variables.
Consider the following example.
Assigning single value to multiple variables

31
RNGPIT Introduction to Python Programming

Assigning multiple values to multiple variables:

Variable Types:
There are two types of variables in Python - Local variable and Global variable.
● Local Variable
● Global Variables
Local Variable:
Local variables are the variables that are declared inside the function and have scope within the function.
------------
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
32
RNGPIT Introduction to Python Programming

c=a+b
print("The sum is:", c)

# Calling a function
add()
#print(a)
------------
In the above code, we declared a function named add() and assigned a few variables within the function.
These variables will be referred to as the local variables which have scope only inside the function.
If we try to use them outside the function, we will get the error.
Global Variables
● Global variables can be used throughout the program, and its scope is in the entire program.
● We can use global variables inside or outside the function.
● A variable declared outside the function is the global variable by default.
● Python provides the global keyword to use the global variable inside the function.
● If we don't use the global keyword, the function treats it as a local variable.
Example:
# Declare a variable and initialize it
x = 100
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Pythonclub'
print(x)
mainFunction()
print(x)

33
RNGPIT Introduction to Python Programming

In the above code, we declare a global variable x and assign a value to it. Next, we defined a function and
accessed the declared variable using the global keyword inside the function. Now we can modify its value.
Then, we assigned a new string value to the variable x. Now, we called the function and proceeded to print
x. It printed the newly assigned value of x.

Print Single Variable:


# printing single value
a=5
print(a)
print((a))

Printing Multiple Variables:


a=5
b=6
# printing multiple variables
print(a,b)
# separate the variables by the comma
Print(1, 2, 3, 4, 5, 6, 7, 8)

Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
del <variable_name>

# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)

What is String in Python?


A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see
characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encodings used.

34
RNGPIT Introduction to Python Programming

In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character
in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode.

How to create a string in Python?


Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can
be used in Python but generally used to represent multiline strings and docstrings.

When you run the program, the output will be:

How to access characters in a string?


We can access individual characters using indexing and a range of characters using slicing. Index starts from
0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We
can't use floats or other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in
a string by using the slicing operator :(colon).

35
RNGPIT Introduction to Python Programming

When we run the above program, we get the following output:

If we try to access an index out of the range or use numbers other than an integer, we will get errors.

Slicing can be best visualized by considering the index to be between the elements as shown below.
If we want to access a range, we need the index that will slice the portion from the string.

How to change or delete a string?


Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. We can simply reassign different strings to the same name.

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del
keyword.

36
RNGPIT Introduction to Python Programming

Python String Operations


There are many operations that can be performed with strings which makes it one of the most used data
types in Python.
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.

When we run the above program, we get the following output:

Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.

37
RNGPIT Introduction to Python Programming

Python String Methods


Python has a set of built-in methods that you can use on strings.

38
RNGPIT Introduction to Python Programming

Case Changing of Strings


The below functions are used to change the case of the strings.
● lower(): Converts all uppercase characters in a string into lowercase
● upper(): Converts all lowercase characters in a string into uppercase
● title(): Convert string to title case
Example: Changing the case of Python Strings.

Output:

39
RNGPIT Introduction to Python Programming

For more string methods examples, visit: Python String Methods - Learn By Example

Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other value. In
any programming language, an expression is evaluated as per the precedence of its operators. So that if there
is more than one operator in an expression, their precedence decides which operation will be performed first.
We have many different types of expressions in Python.

1. Constant Expressions:
These are the expressions that have constant values only.
Example:

Output:

2. Arithmetic Expressions:
An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis.
The result of this type of expression is also a numeric value. The operators used in these expressions
are arithmetic operators like addition, subtraction, etc.
Here are some arithmetic operators in Python:

Example:

40
RNGPIT Introduction to Python Programming

Let’s see an exemplar code of arithmetic expressions in Python :

Output:

3. Integral Expressions:
These are the kind of expressions that produce only integer results after all computations and type
conversions.
Example:

Output:

4. Floating Expressions:
These are the kind of expressions which produce floating point numbers as a result after all
computations and type conversions.
Example:

41
RNGPIT Introduction to Python Programming

Output:

5. Relational Expressions:
In these types of expressions, arithmetic expressions are written on both sides of relational operator
(> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end. These expressions are also called
Boolean expressions.
Example:

Output:

6. Logical Expressions:
These are kinds of expressions that result in either True or False. It basically specifies one or more
conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so
it will return False. Studying logical expressions, we also come across some logical operators which
can be seen in logical expressions most often. Here are some logical operators in Python:

Example:

42
RNGPIT Introduction to Python Programming

Output:

7. Bitwise Expressions:
These are the kind of expressions in which computations are performed at bit level.
Example:

Output:

8. Combinational Expressions:
We can also use different types of expressions in a single expression, and that will be termed as
combinational expressions.
Example:

Output:

43
RNGPIT Introduction to Python Programming

Multiple operators in expression (Operator Precedence):


It’s a quite simple process to get the result of an expression if there is only one operator in an
expression. But if there is more than one operator in an expression, it may give different results on
basis of the order of operators executed. To sort out these confusions, the operator precedence is
defined. Operator Precedence simply defines the priority of operators that which operator is to be
executed first. Here we see the operator precedence in Python, where the operator higher in the list
has more precedence or priority:

So, if we have more than one operator in an expression, it is evaluated as per operator precedence.
For example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given
two different outputs: 22 or 52. But now looking at operator precedence, it must yield 22. Let’s
discuss this with the help of a Python program:

44
RNGPIT Introduction to Python Programming

Output:

Hence, operator precedence plays an important role in the evaluation of a Python expression.

Taking input from console in Python


What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes
input from the user i.e. one command at a time and interprets it. If it is error free then it runs the command
and gives the required output, otherwise it shows the error message. A Python Console looks like this.

Here we write a command and to execute the command just press the enter key and your command will be
interpreted.
For coding in Python you must know the basics of the console used in Python.
The primary prompt of the python console is the three greater than symbols

You are free to write the next command on the shell only when after executing the first command these
prompts have appeared. The Python Console accepts command in Python which you write after the prompt.

45
RNGPIT Introduction to Python Programming

Accepting Input from Console:


User enters the values in the Console and that value is then used in the program as it was required.
To take input from the user we make use of a built-in function input().

We can also typecast this input to integer, float or string by specifying the input() function inside the type.
1. Typecasting the input to Integer: There might be conditions when you might require integer input
from user/Console, the following code takes two input(integer/float) from console and typecasts
them to integer then prints the sum.

2. Typecasting the input to Float: To convert the input to float the following code will work out.

3. Typecasting the input to String: All kinds of input can be converted to string type whether they are
float or integer. We make use of the keyword str for typecasting.

Different Forms of Assignment Statements in Python


We use Python assignment statements to assign objects to names. The target of an assignment statement is
written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that
computes an object.
There are some important properties of assignment in Python :-
● Assignment creates object references instead of copying the objects.
● Python creates a variable name the first time when they are assigned a value.
46
RNGPIT Introduction to Python Programming

● Names must be assigned before being referenced.


● There are some operations that perform assignments implicitly.

Assignment statement forms :-


1. Basic form:
This form is the most common form.

Output:

2. Tuple assignment:

Output:

When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on
the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and
100 respectively.

3. List assignment:
This works in the same way as the tuple assignment.

Output:

47
RNGPIT Introduction to Python Programming

4. Sequence assignment:
In recent versions of Python, tuple and list assignment have been generalized into instances of what
we now call sequence assignment – any sequence of names can be assigned to any sequence of
values, and Python assigns the items one at a time by position.

Output:

5. Extended Sequence unpacking::


It allows us to be more flexible in how we select portions of a sequence to assign.

Here, p is matched with the first character in the string on the right and q with the rest. The starred
name (*q) is assigned a list, which collects all items in the sequence not assigned to other names.
Output:

This is especially handy for a common coding pattern such as splitting a sequence and accessing its
front and rest part.

Output:

48
RNGPIT Introduction to Python Programming

6. Multiple- target assignment:

In this form, Python assigns a reference to the same object (the object which is rightmost) to all the
target on the left.
Output:

7. Augmented assignment:
The augmented assignment is a shorthand assignment that combines an expression and an
assignment.

Output:

There are several other augmented assignment forms:

Lvalue and Rvalue


Overview
Some programming languages use the idea of l-values and r-values, deriving from the typical mode of
evaluation on the left and right hand side of an assignment statement. An lvalue refers to an object that
persists beyond a single expression. An rvalue is a temporary value that does not persist beyond the
expression that uses it.

Discussion
Lvalue and Rvalue refer to the left and right side of the assignment operator. The Lvalue (pronounced: L
value) concept refers to the requirement that the operand on the left side of the assignment operator is
modifiable, usually a variable. Rvalue concept pulls or fetches the value of the expression or operand on the
right side of the assignment operator. Some examples:

49
RNGPIT Introduction to Python Programming

The value 39 is pulled or fetched (Rvalue) and stored into the variable named age (Lvalue); destroying the
value previously stored in that variable.

If the expression has a variable or named constant on the right side of the assignment operator, it will pull or
fetch the value stored in the variable or constant. The value 18 is pulled or fetched from the variable named
voting_age and stored into the variable named age.

If the expression is a test expression or Boolean expression, the concept is still an Rvalue one. The value in
the identifier named age is pulled or fetched and used in the relational comparison of less than.

This is illegal because the identifier JACK_BENNYS_AGE does not have value properties. It is not a
modifiable data object, because it is a constant.
Some uses of the Lvalue and Rvalue can be confusing in languages that support increment and decrement
operators. Consider:

Postfix increment says to use my existing value then when you are done with the other operators; increment
me. Thus, the first use of the oldest variable is an Rvalue context where the existing value of 55 is pulled or
fetched and then assigned to the variable age; an Lvalue context. The second use of the oldest variable is an
Lvalue context wherein the value of the oldest is incremented from 55 to 56.

Key Terms
Lvalue
The requirement that the operand on the left side of the assignment operator is modifiable, usually a
variable.

Rvalue
Pulls or fetches the value stored in a variable or constant.

Modes for running code


In Python, there are two options/methods for running code:

50
RNGPIT Introduction to Python Programming

● Interactive mode
● Script mode

Interactive Mode
Interactive mode, also known as the REPL provides us with a quick way of running blocks or a
single line of Python code. The code executes via the Python shell, which comes with the Python
installation. Interactive mode is handy when you just want to execute basic Python commands or you
are new to Python programming and just want to get your hands dirty with this beautiful language.
To access the Python shell, open the terminal of your operating system and then type "python". Press
the enter key and the Python shell will appear. This is the same Python executable you use to execute
scripts, which comes installed by default on Mac and Unix-based operating systems.

The >>> indicates that the Python shell is ready to execute and send your commands to the Python
interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter
interprets the command.
To run your Python statements, just type them and hit the enter key. You will get the results
immediately, unlike in script mode. For example, to print the text "Hello World", we can type the
following:

Here are other examples:

We can also run multiple statements on the Python shell. A good example of this is when we need to
declare many variables and access them later. This is demonstrated below:

Output

51
RNGPIT Introduction to Python Programming

Using the method demonstrated above, you can run multiple Python statements without having to
create and save a script. You can also copy your code from another source then paste it on the Python
shell.
Consider the following example:

The above example also demonstrates how we can run multiple Python statements in interactive
mode. The two print statements have been indented using four spaces. Just like in script mode, if you
don't indent properly you will get an error. Also, to get the output after the last print statement, you
should press the enter key twice without typing anything.
Pros and Cons of Interactive Mode:
The following are the advantages of running your code in interactive mode:
1. Helpful when your script is extremely short and you want immediate results.
2. Faster as you only have to type a command and then press the enter key to get the results.
3. Good for beginners who need to understand Python basics.
The following are the disadvantages of running your code in the interactive mode:
1. Editing the code in interactive mode is hard as you have to move back to the previous
commands or else you have to rewrite the whole command again.
2. It's very tedious to run long pieces of code.

Script Mode
If you need to write a long piece of Python code or your Python script spans multiple files,
interactive mode is not recommended. Script mode is the way to go in such cases. In script mode,
You write your code in a text file then save it with a .py extension which stands for "Python". Note
that you can use any text editor for this, including Sublime, Atom, notepad++, etc.
If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl +
N" on your keyboard to open a blank script in which you can write your code. You can then press
"Ctrl + S" to save it.
After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.
Let us create a new file from the Python shell and give it the name "hello.py". We need to run the
"Hello World" program. Add the following code to the file:

Click "Run" then choose "Run Module". This will run the program:

52
RNGPIT Introduction to Python Programming

Other than executing the program from the graphical user interface, we can do it from the terminal of
the operating system. However, you must be aware of the path to the directory where you have saved
the file.
Open the terminal of your operating system then navigate to the location of the file. Of course, you
will use the "cd (change directory)" command for this.
Once you reach the directory with the file, you will need to invoke the Python interpreter on the file.
This can be done using the following syntax:

To run the Python file from the terminal, you just have to type the python keyword followed by the
name of the file. In our case, we need to run a file named "hello.py". We need to type the following
on the terminal of the operating system:

If you want to get to the Python shell after getting the output, add the -i option to the command. This
is demonstrated below:

The following example demonstrates how to execute the multiple lines of code using the Python
script.

53
RNGPIT Introduction to Python Programming

Pros and Cons of Script Mode


The following are the advantages of running your code in script mode:
● It is easy to run large pieces of code.
● Editing your script is easier in script mode.
● Good for both beginners and experts.
The following are the disadvantages of using the script mode:
● Can be tedious when you need to run only a single or a few lines of code.
● You must create and save a file before executing your code.

Mutable and Immutable in Python


Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest
definition is: An object whose internal state can be changed is mutable. On the other hand, immutable
doesn’t allow any change in the object once it has been created.

Mutable Definition
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of
objects to change their values. These are often the objects that store a collection of data.

Immutable Definition
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be
changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects


Objects of built-in type that are mutable are:
● Lists
● Sets
● Dictionaries
● User-Defined Classes (It purely depends upon the user to define the characteristics)
Objects of built-in type that are immutable are:

54
RNGPIT Introduction to Python Programming

Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)


● Strings
● Tuples
● Frozen Sets
● User-Defined Classes (It purely depends upon the user to define the characteristics)
Object mutability is one of the characteristics that makes Python a dynamically typed language. Though
Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the
intransitive nature of immutability.

Objects in Python
In Python, everything is treated as an object. Every object has these three attributes:
Identity – This refers to the address that the object refers to in the computer’s memory.
Type – This refers to the kind of object that is created. For example- integer, list, string etc.
Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2
and 3
While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Mutable Objects in Python


I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code
would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:
#Creating a list which contains name of Indian cities

# Printing the elements from the list cities, separated by a comma & space

#Printing the location of the object created in the memory address in hexadecimal format

#Adding a new city to the list cities

#Printing the elements from the list cities, separated by a comma & space

55
RNGPIT Introduction to Python Programming

#Printing the location of the object created in the memory address in hexadecimal format

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding
one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we
did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the
object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Immutable Objects in Python


Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss
the below code step-by-step:
#Creating a Tuple which contains English name of weekdays

# Printing the elements of tuple weekdays

#Printing the location of the object created in the memory address in hexadecimal format

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator
to add a new imaginary day in the tuple ‘weekdays’

#Printing the elements of tuple weekdays

#Printing the location of the object created in the memory address in hexadecimal format

56
RNGPIT Introduction to Python Programming

This above example shows that we were able to use the same variable name that is referencing an object
which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new
tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python
program manager created a new object in the memory address and the variable name ‘weekdays’ started
referencing the new object with eight elements in it. Hence, we can say that the object which is a type of
tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Difference between Interactive mode and Script mode

57
RNGPIT Introduction to Python Programming

Difference between C and Python

58

You might also like