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

class xi AI-chinhat

The document provides an introduction to Python, highlighting its characteristics as an object-oriented, high-level, and open-source programming language developed by Guido van Rossum in the late 1980s. It covers essential concepts such as Python's character set, tokens, variables, data types, operators, and control flow, along with examples of syntax and usage. Additionally, it discusses the importance of comments, indentation, and the dynamic typing feature of Python.

Uploaded by

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

class xi AI-chinhat

The document provides an introduction to Python, highlighting its characteristics as an object-oriented, high-level, and open-source programming language developed by Guido van Rossum in the late 1980s. It covers essential concepts such as Python's character set, tokens, variables, data types, operators, and control flow, along with examples of syntax and usage. Additionally, it discusses the importance of comments, indentation, and the dynamic typing feature of Python.

Uploaded by

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

INTRODUTION TO PYTHON

1.1 Introduction:
➢ Python is Object Oriented Programming language
➢ It is High-level language
➢ Developed in late 1980 by Guido van Rossum
➢ It is derived from programming languages such as ABC, Modula 3
➢ It is free and Open Source language.
➢ It is Case-sensitive language (Difference between uppercase and lowercase letters).

1.2 Characteristics of Python:


✓ Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte
code can be interpreted by the interpreter.
✓ Interactive
✓ Object Oriented Programming Language
✓ Easy & Simple
✓ Portable

There are two modes to use the python interpreter:


i. Interactive Mode
ii. Script Mode

Python Character Set : It is a set of valid characters that a language recognize.


Letters: A-Z, a-z
Digits : 0-9
Special Symbols
Whitespace

TOKENS -Smallest individual unit in a program is known as token. There are 5 types of token in
python.
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
1. Keyword: Reserved words in the library of a language. There are 33 keywords in python. E.g.
False, None, True, and, or, not, if, elif, else, for, is, in etc. All the keywords are in lowercase except 03
keywords (True, False, None).
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
Rules for identifiers:
▪ It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or
an underscore.
▪ It cannot start with a digit.
▪ Keywords cannot be used as an identifier.
▪ We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
▪ Commas or blank spaces are not allowed within an identifier.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given in a
variable or constant.

Literal

String Literal
Numeric Boolean Special
Collections

int float complex

True False None

A. Numeric literals:

int(whole number) 5,-10,0

float(decimal number) 6.7,.8

complex(imaginary number) 6+9j


B. String literals: String literals can be formed by enclosing a text in the quotes. We can use
single, double, triple quotes for a String. Eg: "Aman" , '12345'

Escape sequence characters:


\\ Backslash
\’ Single quote
\” Double quote
\a ASCII Bell
\b Backspace
\f ASCII Formfeed
\n New line charater
\t Horizontal tab

C. Boolean literal: A Boolean literal can have any of the two values: True or False.

D. Special literals: Python contains one special literal i.e. None.

None is used to specify to that field that is not created. It is also used for end of lists in
Python.

E. Literal Collections: tuples (10,20,30), lists [10,20,30] and Dictionary {‘a’:10,’b’:20}

4. Operators: An operator performs the operation on operands. Basically, there are two types
of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator

A. Unary Operator: Performs the operation on one operand. Example: + Unary plus
- Unary minus

B. Binary Operator: Performs operation on two operands. Operators are symbols that
perform operations on operands to produce a result. Python supports a wide range
of operators:
5. Separator or punctuator : , ; , ( ), { }, [ ]

Basic terms of a Python Programs:


A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments
A. Blocks and Indentation:
• Python provides no braces to indicate blocks of code for class and function definition or
flow control.
• Maximum line length should be maximum 79 characters.
• 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 –
if True:
print(“True”)
else:
print(“False”)

B. Statements -A line which has the instructions or expressions.


C. Expressions: A legal combination of symbols and values that produce a result. Generally it
produces a value.
D. Comments: Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment

i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines.
Triple quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10
values. First find the sum of 10 values and divide
the sum by number of values
‘’’

Multiple Statements on a Single Line:


The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)

Variable/Label in Python: Named location that refers to a value and whose value can be used and
processed during program execution. Variables in python do not have fixed locations. The location
they refer to changes every time their values change.
Creating a variable: A variable is created the moment you first assign a value to it.
Example:
x=5
y = “hello”

Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)

variable assignment
Python allows assign a single value to multiple variables.

Example: x=y=z=5

You can also assign multiple values to multiple variables.

Example: x , y , z = 4, 5, “python”

4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.


#program for swapping the value of 2 variable
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12

Lvalue and Rvalue: An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-
1 print (p,q,r)
Now the result will be:
6 6 12
Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
type( ) -It return data type of varible.
Example: x=6
type(x)
The result will be: <class ‘int’>
id( )- It return memory address of the object.
Example:
>>>b=5
>>>id(b)
1561184448
Input from a user:
input( ) method is used to take input from the user. It always returns a value of string type.
Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)
Type Casting: To convert one data type into another data type.
Casting in python is therefore done using constructor functions:

• int( ) - constructs an integer number from an integer literal, a float literal or a string
literal.
Example:

x = int(1) # x will be 1 y =
int(2.8) # y will be 2 z =
int("3") # z will be 3

• float( ) - constructs a float number from an integer literal, a float literal or a string literal.

Example:

x = float(1) # x will be 1.0 y


= float(2.8) # y will be 2.8 z
= float("3") # z will be 3.0
w = float("4.2") # w will be
4.2

• str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.

Example:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Reading a number from a user:


x= int (input(“Enter an integer number”))

OUTPUT using print( ) statement:


Syntax: print(object, sep=<separator string >, end=<end-string>)
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ). Example:
x,y,z=10,20,30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30

MUTABLE & IMMUTABLE Data Type:


Mutable Data Type: These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type: These are unchangeable. In the same memory address new value cannot be
stored. Example: integer, float, Boolean, string and tuple.

Basic Operators in Python:


i. Arithmetic Operators: To perform mathematical operations.
RESULT
OPERATOR NAME SYNTAX
(X=14, Y=4)

+ Addition x+y 18

_ Subtraction x–y 10

* Multiplication x*y 56

/ Division (float) x/y 3.5

// Division (floor) x // y 3

% Modulus x%y 2

** Exponent x**y 38416


Example:
>>>x= -5
>>>x**2
>>> -25

ii. Relational Operators: Relational operators compare the values. It


either returns True or False according to the condition.

RESULT
OPERATOR NAME SYNTAX (IF X=16, Y=42)

> Greater than x>y False

< Less than x<y True

== Equal to x == y False

!= Not equal to x != y True

>= Greater than or equal to x >= y False

<= Less than or equal to x <= y True

iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.

OPERATOR DESCRIPTION SYNTAX


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x
Examples of Logical Operator:

The and operator: The and operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands
a. Relational expressions as operands:

X Y X and Y
False False False
False True False
True False False
True True True
>>> 5>8 and 7>3
False
>>> (4==4) and (7==7)
True

b. numbers or strings or lists as operands:


In an expression X and Y, if first operand has false value, then return first operand X as a
result, otherwise returns Y.
X Y X and Y
>>>0 and 0
0 false false X
>>>0 and 6 0 false true X
>>>‘a’ and ‘n’ true false Y
’n’ true true Y
>>>6>9 and ‘c’+9>5 # and operator will test the second operand
only if the first operand False # is true, otherwise ignores it, even if the second operand is
wrong

The or operator: The or operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

a. Relational expressions as operands:

X Y X or Y
False False False
False True True
True False True
True True True
>>> 5>8 or 7>3
True
>>> (4==4) or (7==7)
True
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.

X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6 6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is wrong

The not operator:


>>>not 6
False
>>>not 0
True
>>>not -7
False

Chained Comparison Operators:


>>> 4<5>3 is equivalent to >>> 4<5 and 5>3
True True

iv. Assignment operators and Augmented Assignment operator: Assignment operators are
used to assign values to the variables.

OPERA
TOR DESCRIPTION SYNTAX

= Assign value of right side of expression to left side operand x=y+z


Add AND: Add right side operand with left side operand and a+=b
+=
then assign to left operand a=a+b

v. Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:
Let x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x) output- True
print('digital' not in x) output- True
print('Digital' not in x) output- False
print(3 in y) output- True
print('b' in y) output- False

Operator Precedence and Associativity:


Operator Precedence: It describes the order in which operations are performed when an
expression is evaluated. Operators with higher precedence perform the operation first.
Operator Associativity: whenever two or more operators have the same precedence, then
associativity defines the order of operations . All the operators of same precedence solve from left to
right except ** It only solve from right to left

FLOW OF CONTROL
 Decision Making and branching (Conditional Statement)
 Looping or Iteration
DECISION MAKING & BRANCHING
Decision making is about deciding the order of execution of statements based on certain
conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE
as outcome.

There are three types of conditions in python:


1. if statement
2. if-else statement
3. elif statement

1. if statement: It is a simple if statement. When condition is true, then code which is


associated with if statement will execute.
Example:
a=40
b=20
if a>b:
print(“a is greater than b”)

2. if-else statement: When the condition is true, then code associated with if statement
will execute, otherwise code associated with else statement will execute.
Example:
a,b=10,20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

3. elif statement: It is short form of else-if statement. If the previous conditions were not
true, then do this condition". It is also known as nested if statement.
Example:

a=int(input(“Enter first number”))


b=int(input("Enter Second Number:"))

if a>b:

print("a is greater")

elif b>a:
print("b is greater")

else:
print("both numbers are equal")

Loop: Execute a set of statements repeatedly until a particular condition is satisfied.


1. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)

The range( ) function:

it generates a list of numbers, which is generally used to iterate over with for loop. range( )
function uses three types of parameters, which are:

• start: Starting number of the sequence.


• stop: Generate numbers up to, but not including last number.
• step: Difference between each number in the sequence.

Python use range( ) function in three ways:


a. range(stop)
b. range(start, stop)
c. range(start, stop, step)
Note:
➢ All parameters must be integers.
➢ All parameters can be positive or negative.

a. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop, but not
including stop value.

Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including stop value.
Example:
for x in range(2, 6):
print(x)
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
for x in range(3, 8, 2):
print(x)
Output:
3
5
7

Programs
1. WAP to check a number whether it is even or odd.
num=int(input("Enter the number: "))
if num%2==0:
print(num, " is even number")
else:
print(num, " is odd number")
2. WAP to check a number whether it is divisible by 5 or not.
num=int(input("Enter the number: "))
if num%5==0:
print(num, " is divisible by 5")
else:
print(num, " is not divisible by 5")
3. WAP to check if the number is positive, negative, or zero.
num=int(input("Enter the number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

4. WAP to enter age from user and check whether the person is eligible to vote or not.
age=int(input(“enter age”))
if age>=18:
print(“eligible to vote”)
else:
print(“not eligible to vote”)

You might also like