0% found this document useful (0 votes)
70 views79 pages

Ilovepdf Merged-2

class 12

Uploaded by

dawofim217
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views79 pages

Ilovepdf Merged-2

class 12

Uploaded by

dawofim217
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FUNDAMENTALS OF PYTHON

• TOKENS
• VARIABLES AND ASSIGNMENTS
• SIMPLE INPUT AND OUTPUT
PYTHON CHARACTER SET
• Character set is a set of valid characters that a language can
recognize.
• A character represents any letter, digit, or any other symbols.
• Python supports unicode encoding standard.
letters: a-z, A-Z
digits: 0-9
special symbols: + - */ ** () {} // =! == < > [] ect.
whitespaces: blank space, tabs, newline.
TOKENS
• It is a smallest individual unit of a program
KEYWORDS
• A keyword is a word having special meaning reserved by
programming language.
• A keyword is a word whose value is predefined.
• Keywords are reserved for special purpose and cannot be used as
identifiers names.
• Example:False, None, del, for, while, from, class, try, import, finally
IDENTIFIERS
• Identifiers are the major building blocks of a program and are used as the
general terms for the names given to different parts of the program.
• The first character must be a letter or underscore(_).
• An identifier cannot contain any special character except underscore(_).
• The digits 0-9 can be a part of the identifier except for the first character.
• Uppercase and lowercase letters are different.
• An identifier must not be a keyword.
• Example: valid identifiers are MyFile, DATE_7_77, file13, _HJ13_JK, Z2TOZ9
• Example: invalid identifiers are DATA-REC, 29lct, break, my.file_
LITERALS
• Literals are data items that have a fixed value.
• Python allows several kind of literals like, String literals, Numeric literals,
Boolean literals, Special literal none, Literal collections.
• Example: ‘Astha', '1-x-0-w-25', 2.0, 1.7E, "Amy's"
STRING LITERAL
• A string literal is a sequence of characters surrounded by quotes.
Example: 'a', 'abc', "abc“
• Two types of string literals
1. single-line string
2. Multiline string
NUMERICAL LITERALS
• The numeric literals in python may be of the following three different
types:
1. Int (56, 774, 32)
2. Float (0.56, 1.752, 23.546)
3. Complex
BOOLEAN LITERALS
Boolean literals in python are used to represent the two Boolean values
true or false.
SPECIAL LITERAL NONE
• Python has one special literal, which is none.
• The none literal is used to indicate absence of value or end of lists in
python.
OPERATORS
• Operators are tokens that start some computation or action when applied
to variables and other objects in an expression.
Example:
+,_,~, %,&,<<,>>,is .**, > =, + =, and, or, not, !=
TYPES OF OPERATORS
• Arithmetic operators (+, -.*, /. %, **. //)
• Bitwise operators (&, ^, I)
• Shift operators (<<, >>)
• Identity operators ( is, is not)
• Relational operators (<,>, < =, > =, ==, !=)
• Assignment operatotrs(=, /=, +=, %=, -=)
• Logical operator(AND, OR)
• Membership operators(in, not in)
• Unary operators(+unary plus, - unary minus, ~ bitwise complement,
not logical negation)
PUNCTUATORS
• Punctuators are symbols that are used in programming languages to
form programming sentences structures, and indicate the importance
of expressions, statements and program structure.
Example:
‘, ”, #, {}, ( ), [], @ ,:, =, .
BAREBONES OF A PYTHON PROGRAM
VARIABLES AND ASSIGNMENT
• CREATING A VARIABLE
• Python variables are created by assigning value of desired type to
them.
Example: marks = 70
student = 'Jacob'
Lvalues and Rvalues
• Lvalue: expressions that can come on the lhs (left hand side) of an
assignment.
• Lvalues are the objects to which you can assign a value or expressions.
Lvalues can come on lhs or rhs of an assignment statement.
• Rvalue: expressions that can come on the rhs (right hand side) of an
assignment.
• Rvalues are the literals and expressions that are assigned to lvalues.
Rvalues can come on rhs of an assignment statement.
Example: you can say that
a=20 b=10
but you cannot say
20=a 10=b a*2=b
MULTIPLE ASSIGNMENT
• Assigning same value to multiple variables : a = b = c = 10
• Assigning multiple values to multiple variables : x, y, z = 10, 20, 30
DYNAMIC TYPING
• Dynamic typing means a variable can hold values of different types at
different times.
Example: x=10
x= "hello world"
SIMPLE INPUT AND OUTPUT
To get input from user you can use built in function input()
SYNTAX:
variable_to_hold_the_value = input( )
Eg: >>> num =input('Enter a number:’)
or
age= int(input(“enter your age:”))
PYTHON OUTPUT USING PRINT() FUNCTIONS
SYNTAX: print ( )
Eg:
print("hello")
print(17.5)
print(3.14*15)
print"My","name", "is")
DATA HANDLING
• DATA TYPES
• IMMUTABLE TYPE
• MUTABLE TYPE
DATA TYPES
Data type is a set of values, and the allowable operations on those values.
It can be one of the following:
NUMBERS
• Python offers data types to store and process different types of
numeric data:
1. Integers
2. Floating point numbers
3. Complex numbers.
• Example: 5, 39, true, false, 3500.75, 0.5E-04, a = 0+3.1j etc.
STRING
• A python string is a sequence of characters and each character can be
individually accessed using its index.
• 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.
Example: “abcd” “1234” ‘marks10’
STRING AS A SEQUENCE OF CHARACTERS
• A python string is a sequence of characters and each character can be
individually accessed using its index.
• Strings in python are stored by storing each character seperately in
contiguous locations.
• The characters of the strings are given in two way indices:
0, 1, 2, 3, ……. Is the farword direction
-1, -2, -3, …….. Is the backward direction
LIST
• A list in python represents a group of comma-seperated values of any data
type within the square bracket [ ].
• Example1:
[1, 2, 3, 4, 5]
[‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
• Example2:
>>> L= ['neha', 102, 79.5]
>>>L
[1, 2, 3, 4, 5]
>>>print (a)
[1, 2, 3, 4, 5]
TUPLES
• Tuples are represented as group of comma -separated values of any
data type within the parentheses ( ).
• Example:
p = (1, 2, 3, 4)
r = ('a', 'e’, ‘i', 'o', 'u')
DICTIONARY
• The dictionary is an unordered set of comma separated key:value
pairs, within { }, with the requirement that within a dictionary, no two
keys can be the same.
• Example:
d = {'a’:1, 'e':2, ‘i’:3, ‘o':4, 'u':5).
IMMUTABLE TYPE
• The immutable types are those that can never change their values in
place.
Types of immutable:
1. Integers
2. floating point numbers
3. Booleans
4. String
5. Tuples.
MUTABLE TYPE
• Mutable are those whose values can change.
• The three mutable types in python.
1. Lists
2. dictionaries
3. sets
MUTABLE TYPE
• Mutability means that in the same memory address, new value can
be stored as and when user wants.
• Types that do not support this property a immutable types.
• Mutable types are those values can be changed in place.
VARIABLE INTERNALS
• Every python object has three key attributes:
1. The type of an object: determines the operations that can be
performed on the object. Built-in function type() returns the type of
an object.
2. The value of an object: it is the data item contained in the object.
Using print() statement you can display the value of the object.
3. The id of an object: the id of an object is mostly the memory
location of the object. buit-in function id() returns the id of an
object.
ARITHMETIC OPERATORS
• unary operator: the operator that act on one operand.
Example: a=5 or a=-3
• binary operator: the operator that act upon two operands.
Example: 5+3 or a+b or a/b
Augmented assignment operators
• Python also offers augmented assignment arithmetic operators,
which combine the impact of an arithmetic operator with an
assignment operator.
Example1: a = a+b
you may write
a += b
Example2: x = x+y
you may write
x += y
RELATIONAL OPERATORS
IDENTITY OPERATORS
• There are two identity operators in python is and is not.
• There are used to check if both the operands reference the same
object memory.
1. is - Returns True if both its operands are pointing to same object or
returns false otherwise.
Example A=10 B=10 A is B i.e true
A=10 B=20 A is B i.e false
2. is not - Returns true if both the operands are pointing to different
objects or returns false otherwise
Example: A=10 B=20 A is not B i.e true
A=10 B=10 A is not B i.e false
LOGICAL OPERATORS
BITWISE OPERATORS
OPERATOR PRECEDENCE
OPERATOR PRECEDENCE
CONTENTS
• EXPRESSIONS
• TYPE CASTING
• WORKING WITH STANDARD LIBRARY MODULES
• USING RANDOM MODULES
• USING STATISTIC MODULE
EXPRESSIONS
• An expression in python is any valid combination of operators, literals
and variables(operands).
• Example: a+b, a>c, a*b< c*d
EXPRESSIONS
• The expressions in python can be of any type:
1. Arithmetic expressions - example:2+5 ** 3, - 8*6/5, etc.
2. String expressions - example: "and" + "then", "and" * 2, etc.
3. Relational expressions - example: x > y, y <= z, z != q, etc.
4. Logical expressions - example: a or b, a and not b.
EVALUATING ARITHMETIC EXPRESSIONS
• Determines the order of evaluation in an expression considering the
operator precedence.
• As per the evaluation order, for each of the sub-expression
. Evaluate each of its operands or arguments.
. Performs any implicit conversions.(done by compiler)
. Compute its result based on the operator.
. Replace the sub-expression with the computed result and
carry on the expression evaluation.
. Repeat till the final result is obtained.
EVALUATING RELATIONAL EXPRESSION
• All comparison operations in python have the same priority, which is
lower than that of any arithmetic operations. All relational
expressions yield Boolean values only i.e ., true or false.
• Chained expressions like a < b < c have the interpretation that is
conventional in mathematics i.e .. comparisons in python are chained
arbitrarily. It is treated as a<b and b<c.
EVALUATING LOGICAL EXPRESSION
• The precedence of logical operators among themselves is not, and, or.
So the expression a or b and not c will be evaluated as given below
(a or ( b and (not c))).
TYPE CASTING
• An explicit type conversion is user-defined conversion that forces an
expression to be of specific type. The explicit type conversion is also
known as type casting.
• Type casting in python is performed by <type>( ) function of
appropriate data type.
• Syntax:
< datatype > (expression)
example: if we have (a=3 and b=5.0), then
int(b) i.e 5
Will cast the datatype of the expression as int
Similarly, float(a) i.e 3.0
WORKING WITH SOME STANDARD LIBRARY
MODULES
Working with math module:
• Python's standard library provides a module namely math for maths
related functions that work with all number types except for complex
numbers. Some of the functions of math module are sqrt(), sin(),
cos(), tan(), pow(), log() etc.
Syntax:
import math
SOME OF THE MATHEMATICAL FUNCTIONS ARE
USING RANDOM MODULE
• Random module provides random number generators. It means that
a number generated by chance.
• To work with functions of random module. first need to import to the
program by giving statement as follows:
import random
USING RANDOM MODULE
• Three most common random number generators are:
1. random( ): it returns a random floating point number N in the
range.
2. radiant(a, b): it returns a random integer N in the range
3. randrange(<start>, <stop>, <step>): it returns random numbers
from range start, stop with step value.
USING STATISTICS MODULE
• The statistics module of the python library provides many statics
functions such as mean( ), median( ), mode( ) etc.
• To use these we need to first import the module as follows:
Import statistics
or
from statistics import mean, median, mode
CONTENTS
• STATEMENTS AND TYPES
• STATEMENT FLOW CONTROL
• PROGRAM LOGIC DEVELOPMENT TOOLS
• THE IF STATEMENTS OF PYTHON
• STORING CONDITIONS
• THE RANGE ( ) FUNCTION
• ITERATION /LOOPING STATEMENTS
• JUMP STATEMENTS
STATEMENTS
• Statements are the instructions given to the computer to perform any kind
of action like data item or making decision or repeating actions.
or
• A statement in Python is a logical instruction which Python interpreter can
read and execute.
• Statements can be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection
or iteration.
• A conditional is a statement set which is executed,on the basis of result of a
condition.
STATEMENTS
• A loop is a statement set which is executed repeatedly, until the end
condition is satisfied.
• Three types of statements:
1. Empty statement
2. Simple statement
3. Compound statement
TYPES OF STATEMENTS
1. EMPTY STATEMENTS: The simplest statement is the empty statement that is a
statement which does nothing. In python an empty statement is pass
statement.
2. SIMPLE STATEMENT: Any single executable statement is a simple statement in
python.
example: name = input(“your name”) or print(name)
3. COMPOUND STATEMENT: A compound statement represents a group of
statements executed as a unit.
syntax:
<compound statement header> :
<indented body containing multiple simple or compound statements>
#It has a header line which begins with a keyword and ends with a colon.
A boby with one or more statements
STATEMENT FLOW CONTROL
Statements may be executed in three forms:
• Sequence: The sequence construct means the statements are being
executed sequentially. Sequence refers to the normal flow of control in a
program.
• Selection: The selection construct means the execution of statements
depending upon condition test. Selection is also known as decision
construct.
• Iteration: The iteration construct means repetition of a set of statements
depending upon a condition test. It is also known as looping construct.
PROGRAM LOGIC DEVELOPMENT TOOLS
• An algorithm is a step by step procedure to solve a given problem. An
algorithm is a set of ordered and finite steps to solve problems.
Algorithm are commonly written out with tools like pseudocode, flow
charts. decision tree or tables.
• A flowchart is a graphical representation of an algorithm. A flow chart
shows different subtasks with different symbols.
PROGRAM LOGIC DEVELOPMENT TOOLS
THE SIMPLE IF STATEMENTS OF PYTHON
THE IF CONDITIONAL:
• An if statement tests a particular condition. if the condition evaluates
to true it carries out some instruction, if the condition is false it does
nothing.
Syntax: example:
If < conditional expression> : if ch == ‘ ‘ :
Statement spaces += 1
[statement] chars += 1
THE if-else STATEMENTS OF PYTHON
The if-else conditional statement:
• This form of if statement tests a condition and if the condition evaluates to
true, it carries out the statements indented below if and in case condition
evaluates to false, it carries out statement indented below else.
Syntax:
If < conditional expression>:
Statement
[statements]
else:
Statement
[statements]
THE if-else STATEMENTS OF PYTHON
• Example:
if a>=0:
print(a, “ is zero or positive number”)
else:
print(a, “is an negative number”)
THE if-elif STATEMENTS OF PYTHON
The if- elif conditional statement:
• If the user wants to check a condition after or when control reaches else i.e ..
condition test in the form of else if. To serve such conditions, python provides if-elif
and if-elif-else statements.
The general form is:
if <conditional expression>:
statement
[statements]
elif <coditional expression>:
statement
[statements]
else:
statement
[statement]
THE if-elif STATEMENTS OF PYTHON
• Example:
if num<0:
print(num,” is a negative number”)
elif num ==0:
print(num,” is equals to zero”)
else:
print(num,” is a “positive number”)
THE nested if STATEMENTS OF PYTHON
Nested if statements:
• A nested if is an if that has another if in its if's body or in else body or in elif body.
Syntax:
if < conditional expression>:
if<conditional expression> :
Statement(s)
else:
Statement
[statements]
elif < conditional expression>:
statement
[statements]
else:
statement
[statements]
NESTED IF EXAMPLE
STORING CONDITIONS
• The conditions being used in code are complex and repetitive. In such
cases to make program more readable, named conditions can be
used, we can store conditions in a name and then use that name
conditional in the if statement.
THE RANGE() FUNCTION
• The range( ) function of python generates a list which is a special
sequence type. A sequence in python is a succession of values bound
together by a single name.
• The common use of range( ) is in the form:
range(<lower limit>, <upper limit>)
Example:
range(12, 18) will give a list as (12, 13, 14, 15, 16, 17)
ITERATION/ LOOPING STATEMENTS
• The iterative statements allows a set of instructions to be performed
repeatedly until a certain conditions if fulfilled.
• Python provides two kind of loops:
1. For loop
2. While loop
• These two loops represent two categories of loops:
1. Counting loops: the loops that repeat a certain number of times ex: for
2. Conditional loops: the loops that repeat until some condition is true ex:
while
ITERATION/ LOOPING STATEMENTS
FOR LOOP:
• The for loop of python is designed to process the items of any sequence.
such as list or a string, one by one.
Syntax:
for <variable > in <sequence> :
Statements to repeat
Example:
for element in [ 10, 15, 20, 25]:
Print (element + 2, end = ‘ ‘)
ITERATION/ LOOPING STATEMENTS
WHILE LOOP:
• A while loop is a conditional loop that will repeat the instructions within
itself as long as a conditional remains true ( boolean true or truth value true).
Syntax:
while <logical Expression>:
loop-body #single or multiple statements
Example:
while count > 0:
count = count -1
product = product + n2
ITERATION/ LOOPING STATEMENTS
Loop control elements of a while Example:
loop: n=10
• Initialization While n>0:
expressions.(starting)
print(n)
• Test expression(repeating or
stopping) n -= 3
• The body of the loop(Doing)
• Update expression(changing)
ITERATION/ LOOPING STATEMENTS
Loop else statement:
• Python loops have an optional else clause.
• Syntax of python loops along with else clause is as given:
for <variable > in <sequence>
statement1
statement2
…..
else:
statement (s)
#the else clause of a python loop executes when the loop terminates
normally, not when the loop is terminating because of a break statement.
JUMP STATEMENTS
Python offers two jump statements to be used within loops to jump out of
loop iterations. These are break and continue.
The Break statement
• The break statement enables a program to skip over a part of the code.
• A break statement terminates the very loop it lies within.
• A break statement skips the rest of the loop and jumps over to the
statement following the loop
JUMP STATEMENT
• The Break statement
Example:
if b == 0:
Print(“division by zero error! Aborting !” )
break
else:
c = a/b
print(“quotient = “, c)
print(“program over!”)
JUMP STATEMENTS
• The Continue statement: instead of forcing termination, the continue
statement forces the next iteration of the loop to take place
• Example:
for i in range(1, 11)
if i % 3 == 0:
continue
else:
print(i)
JUMP STATEMENTS
Nested loops
• A loop may contain another loop in its body. This form of a loop is
called nested loop.
• In a nested loop the inner loop must terminate before the outer loop.
• Example:
for i in range (1, 6):
for j in range (1, i):
print( “ * “ , end = ‘ ‘)

print( )

You might also like