cs1 PDF
cs1 PDF
Class Work
Python Character Set
Tokens
1. Keyword
2. Identifiers
3. Literals
4. Operators
5. Punctuators
Python Character Set :- Character set is a set of valid characters that a language can recognise. A
character represents any letter, digit or any other symbol.Python supports Unicode encoding standard.
Digits 0-9
Other characters Python can process all ASCII AND Unicode characters as part of data or literals
Tokens: - The smallest individual unit in a program is known as Token or a lexical unit.
False assert del for in or while None break elif from is pass with True class else global lambda
raise yield and continue except if nonlocal return as def finally import not try
Identifiers: - Identifiers are fundamental building blocks of a program and are used as the general
terminology for the names given to different parts of the program viz. variables, objects, classes,
functions, lists, dictionaries etc.
The first character must be a letter, the underscore (_) counts as a letter.
Upper and lower case letters are different. All characters are significant.
The digits 0 through 9 can be part of the identifier except for the first character.
Identifiers are unlimited in length. Case is significant i.e. Python is case sensitive as it treats
upper and lower-case characters differently.
An identifier must not be a keyword of Python.
An identifier cannot contain any special character except for underscore (_).
Myfile DATE9_7_77
DATA-REC
29CLCT
Break
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for
a String.
Eg:
"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
Eg:
1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
II.Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
Numbers( can be Integers of unlimited Real numbers with In the form of a+bj where a
both positive and size followed by both integer and forms the real part and b forms
negative) with no lowercase or fractional part eg: - the imaginary part of complex
fractional part.eg: uppercase L eg: 26.2 number. eg: 3.14j
100 87032845L
A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in Python.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
List:
o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can
store different type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
Operators
The operator can be defined as a symbol which is responsible for a particular operation between two operands.
Operators are the pillars of a program on which the logic is built in a particular programming language. Python
provides a variety of operators described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes +(addition), -
(subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**).
Consider the following table for a detailed explanation of arithmetic operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value result negative. For example, if a = 20, b = 10
=> a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a *
(Multiplication) b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0
** (Exponent) It is an exponent operator represented as it calculates the first operand power to second
operand.
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns boolean true or false
accordingly. The comparison operators are described in the following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes true.
>= If the first operand is greater than or equal to the second operand, then the condition becomes
true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Python assignment operators
The assignment operators are used to assign the value of the right expression to the left operand. The assignment
operators are described in the following table.
Operator Description
= It assigns the the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assign the reminder
back to left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands.
For example,
1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the result.
and) Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will
be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Python supports the
following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are the two expressions, a
→ true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are the two expressions,
a → true, b → false => a or b → true.
not If an expression a is true then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a Python data structure. If the
value is present in the data structure, then the resulting value is true otherwise it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list, tuple, or
dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or
dictionary).
Identity Operators
Operator Description
is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both side do not point to the same object.
Operator Precedence
The precedence of the operators is important to find out since it enables us to know which operator should be
evaluated first. The precedence table of the operators in python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
<= < > >= Comparison operators (less then, less then equal to, greater then, greater then equal
to).
‘“#\()[]{}@,:.‘=
INTEGRATION OF ART
Activity :-
Assignment:
Statements :- A statement is a programming instruction that does some thing i.e. some action
takes place.
Example :- print(“hello”)
Comments :- Comments are the additional readable information to clarify the source code.
Comment in Python begin with symbol # and generally end with end of physical line.
(I) The physical lines beginning with # are the full line comments. There are three full
line comments in the above program are :
(II) The fourth comment is an inline comment as it starts in the middle of a physical line,
after Python code (see below)
i) Add a # symbol in the beginning of every physical line part of the multi-line
comments e.g.
# Multi-line comments are useful for detailed additional information.
# Related to the program in question.
#I thelps clarify certain important things
ii) Type comment as a triple quoted multi-line string e.g.
``` Multi –line comments are useful for detailed additional information related to the
program in question. It helps clarify certain important things
```
Functions :- A function is a code that has a name and it can be reused by specifying its name in
the program, where needed.
For ex :-
if b < 5:
print (“Value of b is less than 5”)
print(“Thank you”)
Variable is a name which is used to refer memory location. Variable also known as identifier and used to
hold value.
In Python, we don't need to specify the type of variable because Python is a type infer language and smart
enough to get variable type.
Variable names can be a group of both letters and digits, but they have to begin with a letter or an
underscore.
Python does not bound us to declare variable before using in the application. It allows us to create
variable at required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable that
variable is declared automatically.
Eg:
Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>
Activity :-
Assignment:
Multiple assignment
Variable definition
Dynamic Typing
Simple Input and output
Class Work
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also known as multiple
assignment.
We can apply multiple assignments in two ways either by assigning a single value to multiple variables or assigning
multiple values to multiple variables. Lets see given examples.
Eg:
1. x=y=z=50
2. print iple
3. print y
4. print z
Output:
1. >>>
2. 50
3. 50
4. 50
5. >>>
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
Variable definition :- A variable is defined only when you assign some value to it. Using an undefined
variable in an expression /statement cause an error called NameError.
X=20
print(X)
Dynamic Typing: - Python is a dynamically typed language. It doesn’t know about the type of the
variable until the code is run. So declaration is of no use. What it does is, It stores that value at some
memory location and then binds that variable name to that memory container. And makes the contents of
the container accessible through that variable name. So the data type does not matter. As it will get to
know the type of the value at run-time.
print(type(x))
print(type(x))
Output:
<class 'int'>
<class 'str'>
Simple Input and output:- Python provides numerous built-in functions that are readily available to
us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output
operations respectively. Let us see the output section first.
a=5
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into the source
code.
To allow flexibility we might want to take the input from the user. In Python, we have the input() function
to allow this. The syntax for input() is
input([prompt])
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But it takes it further. It can evaluate even
expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5