0% found this document useful (0 votes)
4 views

Python_Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python_Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter 2: Introduction to Python

In the previous section, you learnt about the different methodologies for
programming. A programming language is a formal language that specifies a set
of instructions that can be used to produce various kinds of output.

In simple Words, a programming language is a vocabulary and set of


grammatical rules for instructing a computer to perform specific tasks. Though
there are many different programming languages such as BASIC, Pascal, C, C++,
Java, Haskell, Ruby, Python, etc. we will study Python in this course.

What is a program?
A computer program is a collection of instructions that perform a specific task
when executed by a computer. It is usually written by a computer program in a
programming language.

Before getting into understanding more about Python, we need to first


understand what is Python and why we need to use Python?

What is Python?
Why Python for AI?
Artificial intelligence is the trending technology of the future. You can see so
many applications around you. If you as an individual can also develop an AI
application, you will require to know a programming language. There are various
programming languages like Lisp, Prolog, C++, Java and Python, which can be
used for developing applications of AI. Out of these, Python gains a maximum
popularity because of the following reasons:

Applications of Python

Python is used for a large number of applications. Some of them are mentioned below:
Web and
Internet
Developm
e nt

Deskto Business
p GUI Applicatio
Applicati ns ns
o
Application
of
Python
Software Games
Developm and 3D
e nt Graphics

Databas
e
Access

Getting started with Python


Python is a cross-platform programming language, meaning, it runs on
multiple platforms like Windows, MacOS, Linux and has even been ported to the
Java and .NET virtual machines.

To write and run Python program, we need to have Python interpreter installed in
our computer.

Downloading and Setting up Python for use

 Download Python from python.org using link python.org/downloads


 Select appropriate download link as per Operating System
[Windows 32 Bit/64 Bit, Apple iOS]
 FOR EXAMPLE, for Windows 64 Bit OS
 Select the following link

Python IDLE installation


CLICK
ON
Next

CLICK
ON
CLICK
ON

CLICK ON
Make New
ABC
1
ABC
2
ABC
Name the Folder
as Python37

Name the Folder


as Python37
CLICK
ON
OK

CLICK
ON
Install
Run in the Integrated Development Environment (IDE)

When we install Python, an IDE named IDLE is also installed. We can use it to
run Python on our computer.

IDLE (GUI integrated) is the standard, most popular Python development


environment. IDLE is an acronym of Integrated Development Environment. It lets
one edit, run, browse and debug Python Programs from a single interface. This
environment makes it easy to write programs.

Python shell can be used in two ways, viz., interactive mode and script mode.
Where Interactive Mode, as the name suggests, allows us to interact with OS;
script mode lets us create and edit Python source file.

Interactive Mode

You can see the above example, Python IDLE Shell account has >>> as Python
prompt, where simple mathematical expressions and single line Python
commands can be written and can be executed simply by pressing enter.

The first expression 3+10 written on the first Python prompt shows 13 as output
in the next line.

The second expression 2+4*10 written on the second Python prompt shows 42
as output in the next line.

The third statement print("Hello Learner") written on the third Python prompt
shows Hello Learner as output in the next line.

The third statement print("Result:", 40+5*100) written on the fourth Python


prompt shows Result: as output in the next line.
Try Yourself

1. Find the result of (75+85+65)/3 i.e. the average of three marks


2. Find the result of 22/7 * 5 * 5 i.e. the area of circle having radius as 5
3. Find the result of "RAVI"+"Kant"
4. Find the result of "###" * 3

Script Mode

In script mode, we type Python program in a file and then use the interpreter to
execute the content from the file. Working in interactive mode is convenient for
beginners and for testing small pieces of code, as we can test them
immediately. But for coding more than few lines, we should always save our
code so that we may modify and reuse the code.

Note: Result produced by Interpreter in both the modes, viz., Interactive and
script mode is exactly the same.

Python Script/Program: Python statements written in


a particular sequence to solve a problem is known as
Python Script/Program.

In shell Mode,
Click File >> New
File

To write a Python script/program, we need to open a new file - File >> New File, type a
sequence of Python statements for solving a problem, save it with a meaningful name - File
>> Save, and finally Run the program to view the output of the program.
Now, type your first Python Program

Code Explanation:

Line 1 in the above code starting with # is a comment line, which means the line is non-
executable and it is only for the programmer’s reference.

Line 2 will simply display

Hello

Line 3 will assign a string value "Sam" to a variable Name

Line 4 will display Learner and will allow the next output to get displayed in the same line

Line 5 will display Sam in the same line as Learner

Line 6 will assign an integer 50 to a variable A

Line 7 will assign an integer 300 to a variable B

Line 8 will display 50 times 300 is 15000

So, the complete output of the Python Code will be

Hello
Learner Sam
50 times 300 is 15000
Python Statement and Comments
In this section we will learn about Python statements, why indentation is
important and how to use comments in programming.

Python Statement
Instructions written in the source code for execution are called statements. There
are different types of statements in the Python programming language like
Assignment statement, Conditional statement, Looping statements etc. These
help the user to get the required output. For example, n = 50 is an assignment
statement.

Multi-line statement

In Python, end of a statement is marked by a newline character.

However, Statements in Python can be extended to one or more lines using


parentheses (), braces {}, square brackets [], semi-colon (;), continuation
character slash (\). When we need to do long calculations and cannot fit these
statements into one line, we can make use of these characters.

Examples:
Type of Multi-line Usage
Statement
Using s = 1 + 2 + 3 + \
Continuation 4 + 5 + 6 + \
7 + 8 + 9
Character (/)
Using Parentheses () n = (1 * 2 * 3 + 4 – 5)

Using Square Brackets [] footballer = ['MESSI',


'NEYMAR',
'SUAREZ']
Using braces {} x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}

Using Semicolons ( ; ) flag = 2; ropes = 3; pole = 4

Python Comments
A comment is text that doesn't affect the outcome of a code, it is just a piece of text
to let someone know what you have done in a program or what is being done in a
block of code.

In Python, we use the hash (#) symbol to start writing a comment.


Python Keywords and Identifiers
In this section, we will learn about keywords (reserved words in Python) and
identifiers (names given to variables, functions, etc.).

Keywords

Keywords are the reserved words in Python used by Python


interpreter to recognize the structure of the program.
The list of all the keywords is given below.
Note:

Python is a case-sensitive language. This means, Variable and variable are not
the same. Always name identifiers that make sense.

While, c = 10 is valid. Writing count = 10 would make more sense and it would
be easier to figure out what it does even when you look at your code after a long
gap.

Multiple words can be separated using an underscore, for example


this_is_a_long_variable

Variables and Datatypes


Variables
A variable is a named location used to store data in the memory. It is
helpful to think of variables as a container that holds data which can be
changed later throughout programming. For example,

x = 42
y = 42
These declarations make sure that the program reserves memory for two
variables with the names x and y. The variable names stand for the memory
location. It's like the two shoeboxes, which you can see in the picture. These
shoeboxes are labelled with x and y and the corresponding values are stored in
the shoeboxes. Like the two shoeboxes, the memory is empty as well at the
beginning.

Note:

Assignment operator is used in Python to assign values to variables. For example, a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.

Examples on Variables:

Task Sample Code Output

Assigning a value Website = "xyz.com" xyz.com


to a variable print(Website)

Changing value Website = "xyz.com" xyz.com


of a variable print(Website) abc.com
Website = "abc.com"
print(Website)
Assigning different a,b,c=5, 3.2, 5
values to different "Hello" 3.2
variables print(a) Hello
print(b)
print(c)

Assigning same value x=y=z= "Same" Same


to different variable print(x) Same
print(y) Same
print(z)

Constants:

A constant is a type of variable whose value cannot be changed. It is helpful to


think of constants as containers that hold information which cannot be changed
later.

Non technically, you can think of constant as a shoe box with a fixed size of shoe
kept inside which cannot be changed after that.

Assigning Value to a constant in Python

In Python, constants are usually declared and assigned on a module. Here, the
module means a new file containing variables, functions etc. which is imported
to the main file. Inside the module, constants are written in all capital letters and
underscores separating the words.

Example : Declaring and assigning value to a constant

 Create a info.py

NAME = "Ajay"
AGE = 24

 Create a main.py

import info

print(info.NAME)
print(info.AGE)

 When you run the program the output will be,

Ajay
24
In the above program, we create a constant.py module file. Then, we assign the
constant value to PI and GRAVITY. After that, we create a main.py file and import
the constant module. Finally, we print the constant value.

Note: In reality, we don't use constants in Python. The global or constants


module is used throughout the Python programs.

Rules and Naming convention for variables and constants

Use camelCase
Create a name that Use capital letters
notation to declare a
makes sense. where possible to
Suppose, vowel makes variable. It starts with
declare a constant. For
lowercase letter. For
more sense than v. example: PI
example: myName

Constant and variable


names should have
Never use special
combination of letters
symbols like !, @, #, $,
in lowercase or
%, etc.
uppercase or digits or
an underscore (_).

Datatypes
Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object)
of these classes.

There are various data types in Python. Some of the important types are
mentioned below in the image
1) Python Numbers

Number data type stores Numerical Values. These are of three different types:

a) Integer & Long


b) Float / floating point

Integer & Long Integer

Range of an integer in Python can be from -2147483648 to


2147483647, and long integer has unlimited range subject to available
memory.

Integers are the whole numbers consisting of + or – sign with decimal digits like
100000, -99, 0, 17. While writing a large integer value, don’t use commas to
separate digits. Also, integers should not have leading zeros.

Floating Point:

Numbers with fractions or decimal point are called floating point numbers.

A floating-point number will consist of sign (+,-) sequence of decimals digits and
a dot such as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be used
to represent a number in engineering/ scientific notation.

-2.0 x 105 will be represented as -


2.0e5 2.0X10-5 will be 2.0E-5

2) None

This is special data type with single value. It is used to signify the absence of
value/false in a situation. It is represented by None.

3) Sequence

A sequence is an ordered collection of items, indexed by positive integers. It is a


combination of mutable and non-mutable data types. Three types of sequence
data
type available in Python are:

a) Strings
b) Lists
c) Tuples

String

String is an ordered sequence of letters/characters. They are enclosed in single quotes


(‘ ‘) or double (“ “). The quotes are not part of string. They only tell the computer
where the string constant begins and ends. They can have any character or sign,
including space in them.

Lists

List is also a sequence of values of any type. Values in the list are called
elements / items. These are indexed/ordered. List is enclosed in square brackets.
Example:
dob = [19,"January",1990]

Tuples:

Tuples are a sequence of values of any type, and are indexed by integers.
They are immutable. Tuples are enclosed in ().

Example:

t = (5,'program',2.5)

4) Sets

Set is an unordered collection of values, of any type, with no

duplicate entry. Example:

>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}

5) Mapping

This data type is unordered. Dictionaries fall under Mappings.

Dictionaries

Dictionary is an unordered collection of key-value pairs. It is generally used when


we have a huge amount of data. Dictionaries are optimized for retrieving data.
We must know the key to retrieve the value.

In Python, dictionaries are defined within braces {} with each item being a
pair in the form key: value. Key and value can be of any type.

Example

>>> d = {1:'Ajay','key':2}
>>> type(d)
<class 'dict'>
Python Operators I
Operators are special symbols which represent computation. They are applied on
operand(s), which can be values or variables. Same operators can behave
differently on different data types. Operators when applied on operands form an
expression. Operators are categorized as Arithmetic, Relational, Logical and
Assignment. Value and variables when used with operator are known as
operands.

Arithmetic Operators

Operat Meaning Expressi Resu


or on lt
+ Addition 10 + 20 30
- Subtraction 30 - 10 20
* Multiplication 30 * 100 300
/ Division 30 / 10 20.0
1 / 2 0.5
// Integer Division 25 // 10 2
1 // 2 0
% Remainder 25 % 10 5
** Raised to power 3 ** 2 9

Python Input and Output

INPU PROCE OUTPUT


T SS “Amar can goto School”
Name Age
"Amar" 5 Is Age of Amar
greater than 4?

Python Output Using print() function


We use the print() function to output data to the standard output
device (screen). We can also output data to a file. An example is given
below.

a = "Hello World!"
print(a)

The output of the above code will be:

Hello World!
Example Code Sample Output
a = 20 30
b = 10
print(a + b)

print(15 + 35) 50

print("My name is Kabir") My name is Kabir

a = "tarun" My name is : tarun


print("My name is :",a)

x = 1.3 x =
print("x = /n", x) 1.3

m = 6 I have 6 apples
print(" I have %d apples",m)

User input

In all the examples till now, we have been using the calculations on known
values (constants). Now let us learn to take user’s input in the program. In
python, input() function is used for the same purpose.

Synta Meanin
x g
<String Variable>=input(<String>) For string input
<integer Variable>=int(input(<String>)) For integer input
<float Variable>=float(input(<String>)) For float (Real no.)
input

Type Conversion
The process of converting the value of one data type (integer, string, float, etc.)
to another data type is called type conversion. Python has two types of type
conversion.

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion, Python automatically converts one data type to
another data type. This process doesn't need any user involvement.
Example:

# Code to calculate the Simple Interest

principle_amount = 2000
roi = 4.5
time = 10

simple_interest = (principle_amount * roi * time)/100

print("datatype of principle amount : ", type(principle_amount))


print("datatype of rate of interest : ", type(roi))

print("value of simple interest : ", simple_interest)


print("datatype of simple interest : ", type(simple_interest))

When we run the above program, the output will be

datatype of principle amount : <class 'int'>


datatype of rate of interest : <class 'float'>

value of simple interest : 900


datatype of simple interest : <class 'float'>

In the above program,


 We calculate the simple interest by using the variable priniciple_amount
and roi with time divide by 100
 We will look at the data type of all the objects respectively.
 In the output we can see the datatype of principle_amount is an integer,
datatype of roi is a float.
 Also, we can see the simple_interest has float data type because Python
always converts smaller data type to larger data type to avoid the loss of
data.
Example Sample Output Explanation
Code
a = 10 File "cbse2.py", line 3, in The output shows an
b = "Hello" <module> error which says that
print(a+b) print(a+b) we cannot add integer
TypeError: unsupported and string variable
operand type(s) for +: types using implicit
'int' and 'str' conversion
c = 'Ram' RamRamRam The output shows that
N = 3 the string is printed
print(c*N) 3 times when we use a
multiply operator with
a string.
x = True 11 The output shows that
y = 10 the boolean value x
print(x + 10) will be converted to
integer and as it is
true will be
considered as 1 and
then give the output.
m = False 23 The output shows that
n = 23 the boolean value m
print(n – m) will be converted to
integer and as it is
false will be
considered as 0 and
then give the output.

Try It Yourself:

1) Take a Boolean value and add a string to it


2) Take a string and float number and try adding both
3) Take a Boolean and a float number and try adding both.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc to perform
explicit type conversion.

This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.
Syntax:

(required_datatype)(expression)

Typecasting can be done by assigning the required data type function to the
expression. Example: Adding of string and an integer using explicit
conversion

Birth_day = 10
Birth_month = "July"

print("data type of Birth_day before type casting :", type(Birth_day))


print("data type of Birth_month : ", type(Birth_month))

Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))

Birth_date = Birth_day + Birth_month

print("birth date of the student : ", Birth_day)


print("data type of Birth_date : ", type(Birth_date))

When we run the above program, the output will be

data type of Birth_day before type casting : <class 'int'>


data type of Birth_month : <class 'str'>

data type of Birth_day after type casting : <class 'str'>

birth date of the student : ' 10 July '


data type of Birth_date : <class 'str'>

In above program,

 We add Birth_day and Birth_month variable.


 We converted Birth_day from integer(lower) to string(higher) type using
str() function to perform the addition.
 We got the Birth_date value and data type to be string.
Example Code Sample Output Explanation
a = 20 20 Apples Writing str(a) will
b = "Apples" convert integer a
print(str(a)+ b) into a string and
then will add to
the string b.

x = 20.3 30 Writing int(x) will


y = 10 convert a float
print(int(x) + y) number to integer
by just considering
the integer part of
the number and then
perform the
operation.
m = False 1 Writing Bool() will
n = 5 convert the integer
print(Bool(n)+ m) value to Boolean.
If it is zero then
it is converted to
False, else to True
for all other
cases.

Try it yourself:

1) Take a Boolean value “False” and a float number “15.6” and


perform the AND operation on both
2) Take a string “ Zero” and a Boolean value “ True” and try adding both
by using the Bool() function.
3) Take a string “Morning “ and the float value “90.4” and try and add
both of them by using the float() function.

Perform the above mentioned Try it Yourself in the lab and write down the
observations to be discussed later in the class.

Note:
There is no difference in single or double quoted string. Both representations can
be used interchangeably. However, if either single or double quote is a part of the
string itself, then the string must be placed in double or single quotes
respectively.
Python Operators II

Comparison operators
Operat Meaning Expression Resu
or lt
> Greater Than 20 > 10 True
15 > 25 False
< Less Than 20 < 45 True
20 < 10 False
== Equal To 5 == 5 True
5 == 6 False
!= Not Equal to 67 != 45 True
35 != 35 False

>= Greater than 45 >= 45 True


or Equal to
23 >= 34 False

<= Less than or 13 <= 24 True


equal to
13 <= 12 False

Comparison operators are used to compare values. It either returns True or


False according to the condition.

Logical operators
Operat Meaning Expression Resu
or lt
And And operator True and True True
True and False False
Or Or operator True or False True
False or False False
Not Not Operator not False True
not True False

Logical operators are the and, or, not operators.


Assignment operators

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

Operat Expressi Equivalent


or on to
= X=5 X = 5
+= X +=5 X = X + 5
-= X -= 5 X = X – 5
*= X *= 5 X = X * 5
/= X /= 5 X = X / 5

Let’s Practice

INPU
T
L=int(input("Length"))

PROCESS
Area=L*B
Perimeter=2*(L+B)

OUTPUT
print("Area:",Area)
print("Perimeter:",Perimeter

Python Code Sample Output


# To calculate Area and Length:50
# Perimeter of a rectangle Breadth:20
L=int(input("Length")) Area:100
B=int(input("Breadth")) Perimeter:140
Area=L*B
Perimeter=2*(L+B)
print("Area:",Area)
print("Perimeter:",Perimeter)
Try writing your code Sample Output
# To calculate Area of a triangle Base:20
# with Base and Height Height:10
#Input Base Area:100
#Input Height
#Calculate Area
#Display Area

# To calculating average marks English:80


# of 3 subjects Maths :75
#Input English Marks Science:85
#Input Maths Marks Total Marks : 240
#Input Science Marks Average Marks: 80.0
#Calculate Total Marks
#Calculate Average Marks
#Display Total Marks
#Display Average Marks

# To calculate discounted amount Amount: 5000


# with discount % Discount%:10
#Input Amount Discount:500
#Input Discount% Discounted Amt:4500
#Calculate Discount
#Calculate Discounted
Amount
#Display Discount
#Display Discounted Amount

# To calculate Surface Area and Volume Length:20


# of a Cuboid Breadth:10
#Input Length Height:15
#Input Breadth Surface Area:1300
#Input Height Volume:3000
#Calculate Surface Area
#Calculate Volume
#Display Surface Area
#Display Volume

Test Your Knowledge


Q1) What are the key features of python ? Mention various
applications along with it Q2) What are the different modes for
coding in python?
Q3) What are comments in python ? List down the various
types of comments. Q4) What are the different properties
of an identifier ?
Q5) What are the rules for naming of variables
and constants Q6) Explain python input and
output with the help of an example.
Q7) What is type conversion ? Explain the types of type
conversion with the help of an example.
Q8) What is a variable? Give example.

You might also like