Python_Notes
Python_Notes
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.
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.
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
To write and run Python program, we need to have Python interpreter installed in
our computer.
CLICK
ON
CLICK
ON
CLICK ON
Make New
ABC
1
ABC
2
ABC
Name the Folder
as Python37
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.
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.
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.
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.
Hello
Line 4 will display Learner and will allow the next output to get displayed in the same line
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
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)
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.
Keywords
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.
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:
Constants:
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.
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.
Create a info.py
NAME = "Ajay"
AGE = 24
Create a main.py
import info
print(info.NAME)
print(info.AGE)
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.
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
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:
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) 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) Strings
b) Lists
c) Tuples
String
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
>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}
5) Mapping
Dictionaries
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
a = "Hello World!"
print(a)
Hello World!
Example Code Sample Output
a = 20 30
b = 10
print(a + b)
print(15 + 35) 50
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.
principle_amount = 2000
roi = 4.5
time = 10
Try It Yourself:
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"
Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))
In above program,
Try it yourself:
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
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
Let’s Practice
INPU
T
L=int(input("Length"))
PROCESS
Area=L*B
Perimeter=2*(L+B)
OUTPUT
print("Area:",Area)
print("Perimeter:",Perimeter