Class X-Review of Python-1 UT2
Class X-Review of Python-1 UT2
ARTIFICIAL INTELLIGENCE
Review of Python
PART-1
Review of Python
•What is a program?
•What is Python?
•Why Python for AI?
•Applications of Python
•Getting started with Python
•Downloading and Setting up Python for use
•Python IDLE installation
•Run in the Integrated Development Environment (IDE) - Interactive Mode, Script Mode
•Python Statement and Comments
•Python Keywords and Identifiers
•Variables and Datatypes
•Python Input and Output – print( ) and input ( )
•Python Operators - Comparison operators, Logical operators, Assignment operators
•Type Conversion - Implicit and Explicit Type Conversion
Computers are used for data processing. Data processing comprises of two things– data
and processing.
Data processing is the task of converting given data into required information.
For a computer to perform data processing, the computer must know what the data is and
how to process it. After storing the data in a computer, we have to tell the computer how to
process it.
A set of instructions given to the computer to perform a specific job is called a program, and
the task of writing programs is called programming.
We have to use some language to write these programs eg. Python, C, C++, LISP, Pascal,
Java, PHP, etc.
When we write a program, we are writing a set of instructions to solve a problem involving
data processing. These instructions have to be executed by the computer to solve the
problem. If the instructions are correct and given in correct sequence, then the problem will
be solved properly by the computer, and if the instructions are incorrect or in wrong sequence
then the problem will not be solved correctly or will not be solved at all. Therefore, writing
correct instructions in correct sequence is extremely important. It means that before we start
writing a program, we should be thoroughly clear in our mind about the steps of solving the
problem.
Python was developed by Guido Van Rossum in 1991 in
Netherlands based on a language ABC and Modula-3.
Features of
Python
Applications of Python
Desktop
Business
GUI
Applications
Applications
Applications
of Python
Games and 3D
Software Development Graphics
Database
Access
Applications of Python
•Python can be used on a server to create web applications.
•Scientific and Numeric Computing-used in machine learning, data
mining and other scientific fields with its libraries like :NumPy, SciPy etc.
•Free and Open Source – can be easily and downloaded free of cost. Its code is accessible,
modifiable, and can be redistributed.
•Cross platform language (portable) – python code can run well on a variety of
platforms(Windows, linux, Unix, Mac etc) hence a portable language
• high level language(HLL)
•Expressive language – few lines of code, simpler syntax and compact thus easier to
understand.
•Interpreted Language– A computer understands only the machine language. It does not
understand programs written in any other programming language like Python. Therefore, for
program execution, each instruction of the program (written in Python) is first interpreted into
machine language by a software called the Python Interpreter, and then it is executed by the
computer. Python code is executed line by line and hence easy to debug language.
•It is a powerful object-oriented programming language. This environment makes it easy to
write programs.
•Python has IDLE( Integrated Development Learning Environment) for developing python
programs(scripts) under Windows and other operating systems. It allows to edit, run, browse
and debug Python Programs from a single interface.
•Python has a rich standard library which contains a lot of predefined functions for most of
the common operations, and a large number of pre-defined modules for specific varieties of
functions. This makes programming in Python an easy task.
Interpreter
Interpreter
Translates program one statement at a time.
It takes less amount of time to analyze the source code
but the overall execution time is slower.
Continues translating the program until the first error is
met, in which case it stops. Hence debugging is easy.
Programming language like Python use interpreters.
Slower
COMMAND SYNTAX
•It is case sensitive
•Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Python gives error if the code
is not properly indented.
CORRECT
if 5 > 2:
print("Five is greater than two!")
INCORRECT
if 5 > 2:
print("Five is greater than two!")
1. Interactive mode
2. Script mode
Interactive Mode
Vs
Script Mode
Interactive mode(Command line)
You type one command at a time and is executed to
give output and followed by again a command and so
on.
•The interactive interpreter of Python is called Python
shell. Python syntax can be executed by writing directly
in the Command Line.
•prompt (>>>) followed by a blinking cursor. It indicates
that IDLE is now ready to take Python commands from
the user. (interactive mode)
INTERACTIVE MODE - Commands are executed directly at the
prompt
SCRIPT MODE
All commands can be saved in a file and executed as follows
In Python Shell window,
click File >> New File or click Ctrl+N.
Notice that an Untitled window appears as shown below:
➢ Type Python program in a file
➢ Save it . Default extension is .py
➢ then use interpreter to execute the contents from the file by Run
option or press F5
OUTPUT
print() Function In Python is used to print output on the
console(screen).
print('hello India')
Output :-
hello India
print(‘Computer',‘Science’)
Output
Computer Science
OUTPUT
print() Function In Python is used to print output on the
console(screen).
print('hello India')
Output :-
hello India
print(‘Computer',‘Science’)
Output
Computer Science
OUTPUT
print() Function In Python is used to print output on the
console(screen).
Multiple print statements print output on new line
Syntax:
print ("Message“)
print (“Expression”)
Output
Message
Expression
Understanding print()
In the following, the first statement will output 3+4, while the second will
output 7.
print('3+4')
print(3+4)
OUTPUT
Understanding print()
More examples
print(“hello world!”)
>>>print("hello" "world")
helloworld
>>>print("hello"+ "world")
helloworld
print ( "2 plus 2 is ", 2+2, "2 times 2 is ", 2 plus 2 is 4 2 times 2 is 4
2*2)
A. Name – a variable name must start with an alphabet or _, can contain alphabets,
digits an _, cannot contain spaces, cannot be a python keyword, is case
sensitive(choose names that give an indication for what they are being used for. Ie.
Instead of a,b,c use age, name, address etc
B. An Identity - can be known using id (object). Every variable has a memory address and
points to a value. The reference object of a variable to which it points may change during
the program’s execution. When a reference to a value changes, the id changes.
D. Value
Rules for naming a variable
Every variable has a name
Follow the rules for naming them
• 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 special characters.
* Identifier must not be a keyword of Python.
* Identifiers are case sensitive
Thus, Rollnumber and rollnumber are two different identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no Some invalid
identifier : 2rno,break, my.book, data-cs
Guidelines
Remember:
Variables are created when they are first assigned a value.
Variables must be assigned a value before using them in expression
Variables A and a are different.
Classify each of the following as a valid or invalid variables or
keywords. If it is valid, write “Valid” or if it is invalid write
“Invalid” and propose a similar valid identifier.
>>> print (Prog, Ver) # prints two values separated with comma (,)
Python 3.7
Understanding print()
•Print a value, message or both message and values and vice versa.
>> Sum=50
>>> print ("The sum is", Sum) # prints a message with a value The sum is 50
Operators
• Operators can be defined as symbols that are used to perform operations on operands.
• An operator is a symbol, which works on data items and performs some mathematical
calculations or change the data. An operator may have one or two operands. Eg. in a+b , a and
b are operands, + is operator
a = 23
b = 6.2
sum = a + b
print (sum)
L-value = R-value
Assignment Operator
(=)
x = "Python is "
y = "awesome"
z= x+y
print(z)
Output :Python is awesome
For numbers, the + character works as a concatenation operator:
Understanding print()
>>> Ver = 3.7
>>> Prog = "Python"
>>> print (Prog, Ver) # prints two values separated with comma (,)
Python 3.7
Understanding print()
•Print a value, message or both message and values and vice versa.
>> Sum=50
>>> print ("The sum is", Sum) # prints a message with a value The sum is 50
Multiple Assignment:
Assigning a value to multiple variables. In Python, we can assign a value to multiple variables.
For example,
>>> a = b = c = d = 5
>>> (a, b, c, d)
(5, 5, 5, 5)
Here, all the variables a, b, c and d are assigned a single value called 5.
Example 2:
b,c,a=10,20,30
p,q,r=c-5,a+3, b-a
print(a, b, c)
print ( p,q,r)
Output
30 10 20
15 33 -20
Swapping values
expression1 += expression2
can be understood as,
expression1 = expression1 + expression2
Added and assign back the result to Will change the value of x to
+= left >>>x+=2 14
operand
Subtracted and assign back the
-= result to left operand x-=2 x will become 10
//= Perform floor division on 2 numbers and assigns the result to left a//=b
operand.
**= calculate power on operators and assigns the result to left operand. a**=b
Eg.
A=10
A+=5 means A=A+5 which will assign 15 to the variable A
Operators
Logical Operators - Logical Operators are used to combine
conditions
a=30
b=20
if(a==30 and b==20):
print('hello')
Output :- hello
Logical Operators
• The logical operators are also called as Boolean operators.
• With Boolean operators we perform logical operations by
combining two or more conditions.
• These are most often used with if and while keywords.
Logical Operators - and
Returns true only when all the conditions are true, else it returns False
the left hand side of the ‘and’ expression is False which implies that the whole
expression will be False irrespective of the other values. This is called short-
circuit evaluation.
Returns true if any of the conditions are true, else it returns False
print(True or False) # Returns True
print(7>8 or 9>3) #Returns True
x = True;
print(not x) # Returns False
• It generally takes place when in an expression more than one data type is
present in an expression. In case of operands with different data types.
• Taking an example, 5.0/4+ (63.0) is an expression in which values of different
data types are used. These type of expressions are also known as mixed
type expressions.
• When mixed type expressions are evaluated, Python promotes the result of
lower data type to higher data type, i.e. to float in the above example. This is
known as implicit type casting. So the result of above expression will be
4.25.
6/3 – 2.0
type(6/3)
<class 'float'>
Implicit Type Conversion
Eg.
>>50+2.0 will result in 52.0
All integers are promoted to floats and the final result of the expression is a
float value.
All the data types of the variables are upgraded to the data type of the variable with largest
data type.
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.
x = 20.3
y = 10
print(int(x) + y)
Output
30
Writing int(x) will convert a float number to integer by just considering the integer part of
the number and then perform the operation.
Explicit Type Conversion
you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.
Python defines type conversion functions like int(), float(), str() to perform
conversion from one data type into another.
Eg.
You can check the data type using type() covered earlier
Explicit Type Conversion
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
A=20
B=“30”
print(A+B)
Another example
Output
Enter first no.: 20
Enter second no.: 40
Here, Num1 and Num2 are concatenated(joined the values) and produce a
result 2040 instead of numeric addition to 60 because input function takes
data in string form
So “20”+”40”=2040
Output
Enter first no.: 20
Enter second no.: 40
The sum is 60
another example,
>>> Val1 = int("1243")
>>> Val2 = int(3.14159)
>>> print (Val1 + Val2)
Output
1246
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Example Example
x = int(1) # x will be 1 Floats:
y = int(2.8) # y will be 2
x = float(1) # x will be 1.0
z = int("3") # z will be 3
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
1 w = float("4.2") # w will be 4.2
2
1.0
3
2.8
3.0
4.2
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
s1
2
3.0
Precedence of Operators
• If an expression contains only one operator, then it can be evaluated very easily.
But, if an expression contains more than one operators, then to evaluate it, we
have to be careful about the sequence in which the operations have to be done.
Operator precedence determines which operators are applied before others when
an expression contains more than one operators.
• It is done based on precedence of operator. Higher precedence operator is
worked on before lower precedence operator. Operator associativity
determines the order of evaluation when they are of same precedence and
are not grouped by parenthesis.
• When an expression contains operators which have the same precedence (like
* and /), then whichever operator comes first is evaluated first. Parentheses can
be used to override the order of precedence and force some part of the
expression to be evaluated before others.
• () has the highest precedence
Precedence of Operators
Try the output for Q6.
Delimiters / Punctuators
Used to implement the grammatical and structure of a
Syntax.Following are the python punctuators.
Delimiters Classification
( ) [ ] { } Grouping
. , : ; @ Punctuation
= +=–= *= /= //= %= **= Arithmetic
assignment/binding
&= |= ^= <<= >>= Bitwise
assignment/binding
Data types supported by Python
Fundamental data types or native data types like int, float, complex, etc.
Sequence types like string, list, tuple, etc.
The variable, for which we can change the value is called mutable variable.
It means we can change their content without changing their identity. Mutability
means that in the same memory address, new value can be stored as and when
you want.
Immutable .
The variable, for which we cannot change the value is immutable variable.
example string, tuple, etc.
DATATYPES
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = True bool
x = None NoneType
DATATYP
1. Number
ES Values. This data type is immutable i.e. value of
Number data type stores Numerical
its object cannot be changed (we will talk about this aspect later).
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.
Example
y= 12.36
Complex: Complex number in python is made up of two floating point
values, one each for real and imaginary part. For accessing different parts of
variable (object) x; we will use x.real and x.image. Imaginary part of the
number is represented by “j‟ instead of “i‟, so 1+0j denotes zero imaginary
part.
Example
>>> x = 1+0j
>>> print x.real, x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
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.
bool (Boolean): In Python programing language, the Boolean data type (value of bool) is
a primitive data type having one of two values: True or False. This is a fundamental data
type. Internally, represented as 1 and 0 and can be used in numeric expressions as
values.
3. Sequence
Example
l = [“abc”, 20.5,5]
III.Tuples: Tuples are a sequence of values of any type, and are indexed by
integers. They are immutable. Tuples are enclosed in (). We have already seen
a tuple, in Example 2 (4, 2).
Sequence Data Type
String Lists Tuple
Set is an unordered collection of values, of any type, with no duplicate entry. Sets
are immutable.
Example
s = set ([1,2,34])
5. Mapping
This data type is unordered and mutable. Dictionaries fall
under Mappings.
Example
d = {1:'a',2:'b',3:'c'}
Python supports Dynamic typing
X = 25 # integer type
X = “Python” # x variable data type change to string on just next
line
TEST YOURSELF:
Observe the following script and enlist all the tokens used in it.
x=28
y=20
if x>y:
z=x/y;
else:
z=y/x;
print("x, y, z are:",x,y,z)
What is the output
Num1 = "20"
Num2 = “40”
print ('The sum of ', Num1, ' and ', Num2, ' is ',Num1+Num2)
One method
print ('The sum of ', Num1, ' and ', Num2, ' is
',(Num1+Num2))
•Refer to an object
Now we shall write a simple script to show the use of user input:
name1=input("Enter a name: ")
name2=input("Enter another name: ")
print(name1,"and",name2,"are friends")
The return type of input() is string type, so to convert the input into numeric
form, we use int()
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
x = True ?
y = 10
print(x + 10)
m = False ?
n = 23
print(n – m)
a=False
B=“hello”
a+B
True+45.8
i.Which of the following is NOT a legal variable name ?
ii. What is the correct syntax to output the type of variable in Python ?
a = 20
b = "Apples" print(str(a)+ b)
x = 20.3
y = 10
print(int(x) + y)
m = False
n=5
print(Bool(n)+ m)
lab work
Try it yourself:
1. Print the quotation “Make hay while the sun shines” (the quotes must be also
displayed)
2. Take a Boolean value “False” and a float number “15.6” and perform the AND
operation on both
3. Take a string “ Zero” and a Boolean value “ True” and try adding both by using the
Bool() function.
4. Take a string “Morning “ and the float value “90.4” and try and add both of them by
using the float() function.
L=int(input("Length"))
B=int(input("Breadth"))
Area=L*B
Perimeter=2*(L+B)
print("Area:“+area)
print("Perimeter:“+Perimeter)
Stub
programs