Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

IX AI Python Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

PYTHON

Prepared by Mrs. Sonam Dutta, PGT-Computer Science, KV DRDO Bangalore

Python programming language was created by Guido van Rossum and was released in 1991.

Python can be downloaded from the website https://www.python.org/downloads/ at free of cost


and can be installed in the system.

Features of Python:
1. Python is interpreted language i.e., each line of code is read by the interpreter and is
translated to machine code one by one.
2. Python is free and open-source software i.e., it can be downloaded at free of cost from the
official website of python and the program code can be read, modified/customized as per
requirement and used by anyone.
3. Python supports Unicode character set i.e., symbols of all the recognized languages in the
world. Therefore, the program code, written in one language need not be translated to
another before execution and saves time.
4. Python is platform independent i.e., can be supported by all types of hardware and software.
5. Python is portable language i.e., program written in one system can be modified and
executed in any other system.
6. Python supports both procedural and object-oriented programming approach.
7. Python is case sensitive language.
8. Python can handle big data applications.

Application of Python:

 Designing web applications and scripting


 Game development
 Developing full-fledged software
 Data Science and Data Visualization
 Designing Machine Learning and Artificial Intelligence system

Modes of Python

Interactive Mode Script Mode


Interactive Mode: (Python)
➢ One line of program code is accepted by the system, immediately executed and output
/ error is displayed on the screen.
➢ Very easy for verifying correctness of a python statement.
➢ Fast execution
➢ Program code cannot be saved for future use. It is removed once the window is closed.

Script Mode: (Python IDLE)


❖ The entire program code to be executed as a unit is saved in a file and can be executed
as and when required.
❖ Program can be developed in installments and can be modified and executed any no. of
times.
❖ Comparatively slower execution
❖ Can be saved, sent, modified and executed in future any no. of times.

IDLE stands for Integrated Developing Environment.

Q. 1. Differentiate between Script mode and interactive mode of using python.

Tokens of Python:
Token is an indivisible and individual part of a programming language that can be identified
and translated by the language translator. Every program consists of a set of tokens only.

Classification of Tokens:
Token

Keywords Data types Literals Identifiers Operators Punctuations

Q. 2. Identify the tokens from the following program code and count the total no. of tokens:

a = 10
b=7
c = a + b*2
print('Result =', c)

Keywords
Keywords are the reserved words for the language translators which have special meanings and
usage and cannot be redefined by the programmers.
Data types
Data types are the type of values stored in a memory location. Every data stored in memory
can be classified as a particular data type.

Classification of Data types

Data types

Basic / Primitive / Fundamental Derived

Integer Floating Boolean Complex


point Data
(int) (bool) (complex) Sequence
(float)

8, -3 etc 8.23, -3.6 etc 6+3j, 7.2-7j


True,
False etc

String Tuple List Dictionary


(str)
(tuple) (list) (dict)

"Green house", ('d', 7, 6), ['d', 7, 6], {'s':6, 4.5: "are"}


'word' etc. (2, 9.1) etc. [2, 9.1] etc. etc.
Literals
Literals are the unnamed constant values stored in memory and used in the programs.
Examples of the literals of various data types are mentioned in the above chart.

int literals

Decimal Octal (Digits 0-7) Hexadecimal (Digits 0-9, A-F)


(By default) starting with 0 starting with 0x
e.g. – 23, -8.46 e.g. – 027, -03.46 e.g. – 0x9D, -0x3.A6

Q. 3. Identify the data types of the following expressions:


i. 85 + 3 * 2
ii. 8 – 5 * 0.63 + 9.4
iii. True or False
iv. "Green" + 'Tea'
White-space Characters

Invisible or Non- printable characters like Blank space, Tab (8 blank spaces), New line etc.
The first 33 characters of Unicode are non-printable.

Escape Sequence => A combination of 2 or more characters starting with ‘\’ (back slash)
having a special meaning and purpose are not displayed on the screen as it is.

Some of the escape sequence are given below:


Q. 4 What will be displayed on the screen?
print(''What\'s up? '')
Q. 5 Write the statement for printing the following:
He said, “I will definitely come today\ tomorrow”.

Identifiers
Identifier is the name of a programming construct given by the programmer.
Identifiers can be variables, functions, objects etc.

Rule of defining identifiers:

An identifier can contain alphabets (both lower and upper case), digits (0-9) and
only one special character _ (underscore).

An identifier can start with either alphabet or _ (underscore) only, but not digit.

Identifier does not allow white space characters in between.

Keywords must not be used as identifiers.

Q. 6. Identify the correct identifiers from the following list:


A2B, +91-53789, 4ab, Else, hello3, _5656, Roll No, break

Q. 7. Identify the correct and incorrect variables from the following:


‘dear’, xy45, 4x5y, INT, a-b, at_

Variable => Variable is a named memory location which can store a value of any data type
during the execution of a program.
For example, consider the following program code

No1 = 23
No2 = 45
Sum = No1 + No2

Here variables are No1, No2 and Sum. Literals are 23 and 45.

Function => Function is a named piece of program code or sub-program which can be called
and executed independently.
A function can take 0 or more parameter and returns 0 or more values.
Advantage of using function:
A function once defined can be called and executed any no. of times. No need to write the same
piece of code multiple times for repeated use, hence saves time and effort.

Examples:

 Python inbuilt functions – print(), input(), eval(), int(), list() etc.

 print() takes one or more values (comma-separated) and construct a string to


display in the screen. If no parameter is passed a new line character is printed
and the cursor moves to the next line.

 input() takes an input from the user through the input device in the form of
string and returns the same. Input can take a string as parameter and display the
same in the screen for the ease of user.

 eval() takes a value in the form of a string and returns the value into the
designated data type.

 Library functions – math library functions like sin(), floor(), sqrt(), pow() etc.
 User defined functions

Comment Line:
Comment lines are the line(s) of code which are skipped by the language translator and hence
are not read and executed.

Comment lines are mostly used to describe the purpose, working functionality of any statement
or a block of statements. It is used for documentation of the program code which helps to
analyze and modify the code in future.

Classification of Comment Lines:

Comment Line

Single Line Comment Multi-line Comment

# This line will not be executed ''' These lines will not
be executed at all. '''
Q. Write a program in python to input 3 words from the user and display the same.

Ans-
PROGRAM SAMPLE OUTPUT

# INPUT FROM THE USER Enter 1st word : Green


a = input("Enter 1st word : ") Enter 2nd word : Blue
b = input("Enter 2nd word : ") Enter 3rd word : Red
c = input("Enter 3rd word : ") The words are: Green Blue Red

# DISPLAY RESULT
print("The words are: ", a, b, c)

Operators

Classification

A. Types of operators depending on the number of operands required:

• Arithmetic : +, -
Unary • Logical : not

• Arithmetic : +, -

Binary • Comparison : >, <=


• Assignment : =
• Membership : in, not in

B. Types of operators depending on the nature of operations


Arithmatic: Operands are numerical values

+ , - , * , / , // (floor division), % (modulo), ** (exponent)

Comparison / Relational: Operands are expressions

> , < , >= , <= , == (equality) , != (inequality)

Assignment: L_value is variable, R_value is expression

= , += , -= , *= , /= , //= , %= , **=

Logical: Operands are Conditions i.e. Boolean values

or , and , not

Membership: Left operand is value, Right operand is data sequence

in , not in

Expression => An expression consists of 0 or more operators and 1 or more operands.


e.g. –
21 // 3 + 45 % 2 – 2**3 is an example of arithmetic expression.
4>=5 or 3*2<5 and 7+2==8 is an example of Boolean expression.
Priority
Highest

Lowest

Associativity: Order of execution


i. Right to Left (R-> L) : ** , assignment operators, unary operators
ii. Left to Right (L -> R) : All other operators

Commutative Property:
i. Among arithmetic operators +, * are commutative, all others are not.
ii. Among relative operators ==, != are commutative, others are not.
iii. Among logical operators or, and both are commutative

Example : If a = 5 and b = 3, then,

a+b 8
a>b True
a-b 2
a>=b True
a*b 15
a<b False
a/b 1.67 (Real quotient)
a//b 1 (Integer quotient) a<=b False
a%b 2 (remainder) a==b False
a**b 125 (a=base, b=exponent) a!=b True
a+=1 Logical Operators Membership Operators
6

a-=1
4 5<3 or 4<=6 : 'i' in "String"
True : True
a*=2
10
5<3 and 4<=6 : 'ri' not in "String" :
a/=2
2.5 False False
a//=2
2 not 5>3 : 'x' in "String"
False : False
a%2
1
'x' not in "String" :
a**=2 True
25

Q. Write a program to input 2 numbers from the user and display their sum,
difference, product, quotient (both integer and real), remainder and exponential
value.

Ans –
PROGRAM SAMPLE OUTPUT

# INPUT FROM THE USER Enter 1st number : 10


X = INT(INPUT("ENTER 1ST NUMBER : "))
Enter 2nd number : 7
Y = INT(INPUT("ENTER 2ND NUMBER : "))
Sum = 17
# CALCULATION Difference = 3
SUM = X + Y Product = 70
DIFF = X - Y Integer quotient = 1.42857
PROD = X * Y Real quotient = 1
QTNI = X / Y
Remainder = 3
QTNF = X // Y
REM = X % Y Exponent = 10000000
EXP = X ** Y

# DISPLAY RESULT
PRINT("SUM = ", SUM)
PRINT("DIFFERENCE = ", DIFF)
PRINT("PRODUCT = ", PROD)
PRINT("INTEGER QUOTIENT = ", QTNI)
PRINT("REAL QUOTIENT = ", QTNF)
PRINT("REMAINDER = ", REM)
PRINT("EXPONENT = ", EXP)
Multiple Assignment Operators

x = y = z = 10
• At first 10 is assigned to z, then the same value is assigned to y
and x respectively. (Right to Left)

x, y, z = 3, 5, 4
• This statement is equivalent to x=3;y=5;z=4 and can be expressed
in a single line of code.

Q. Write a program in python to initialize a with 10, b with 20. Write statement
to swap the contents of the variables.
Ans –
Option 1: Using 3rd variable Option 2: Without using 3rd variable
a = 10 a = 10
b = 20 b = 20
t=a a, b = b, a
a=b print("a = ", a)
b=t print("b = ", b)
print("a = ", a)
print("b = ", b)

Q. Write a program in python to input the altitude (L) and base (B) of a right-
angled triangle and find its hypotenuse (H). (H =√𝐿2 + 𝐵2 )
Ans -

PROGRAM SAMPLE OUTPUT

# IMPORT LIBRARY Enter the base : 3


import math Enter the height : 4
Hypotaneous = 5.0
# INPUT FROM THE USER
B = float(input("Enter the base : "))
L = float(input("Enter the height : "))

# CALCULATION
H = math.sqrt(L**2 + B**2)

# DISPLAY RESULT
print("Hypotaneous = ", H)
Data type Conversion

Automatic / Explicit /
Implicit Type casting

i. Automatic Type Conversion:

If an expression consists of data of various data types (Mostly numeric), during the
operation the lower precision operand is promoted to the matching higher precision data
type and the result is of the higher precision data type.

Example: In the expression F = True + 5 - 3.1, True (bool data type) is internally
converted to 1 (integer), so True+5 is 6 (integer). Next, 6 (integer) is internally
converted to 6.0 (float), so 6.0 – 3.1 is 2.9 (float)

ii. Type casting:

Forceful conversion of data type of any data is said to be type casting.


 int() => Converts a value to integer. E.g. int(6.7) = 6, int(“234”) = 234
 float() => Converts a value to float. E.g. float(6) = 6.0, float(“23.4”) = 23.4
 bool() => Converts a value to boolean. E.g. bool(“False”)=False, bool(5)=True
 str() => Converts a value to string. E.g. str(5.6) = ’5.6’, str(2+3)=’5’

Punctuators
, Separators of values / expressions
; End of statement
. Accessing Member
: Branch / Nested statement
"" or '' String literals
() Tuple
[] List
{} dictionary

You might also like