0% found this document useful (0 votes)
57 views16 pages

cs1 PDF

The document summarizes key Python concepts including character set, tokens, literals, and operators. It discusses Python's character set including letters, digits, special symbols, and whitespaces. It describes the different types of tokens in Python including keywords, identifiers, literals, operators, and punctuators. It provides examples of various literals like strings, numbers, Booleans, None, and collections. It also explains different types of operators in Python such as arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators.

Uploaded by

Archisha Khare
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)
57 views16 pages

cs1 PDF

The document summarizes key Python concepts including character set, tokens, literals, and operators. It discusses Python's character set including letters, digits, special symbols, and whitespaces. It describes the different types of tokens in Python including keywords, identifiers, literals, operators, and punctuators. It provides examples of various literals like strings, numbers, Booleans, None, and collections. It also explains different types of operators in Python such as arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators.

Uploaded by

Archisha Khare
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
You are on page 1/ 16

Day- 1

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.

Letters A-Z , a-z

Digits 0-9

Special symbols Space + -* / ** \ ( ) [ ] { } / / = ! = = ,< , > . ‘ “ “”” , ; : % !& # <= >= @ _

Whitespaces Blank space, tabs (), carriage return,newline,formfeed.

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.

Python has following tokens:

Keywords, identifiers, Literals, Operators, Punctuators.

Keywords: - A Keyword is a word having special meaning reserved by programming language.

Python programming language contains the following keywords :

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.

Identifiers forming rules of Python are being specified below :

 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 (_).

The following are some valid identifiers :

Myfile DATE9_7_77

The following are some invalid identifiers:

DATA-REC

29CLCT

Break

Literals :- Literals can be defined as a data that is given in a variable or constant.

Python support the following literals:

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:

There are two types of Strings supported in Python:

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.

There are two ways to create Multiline Strings:

1). Adding black slash at the end of each line.

Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>

2).Using triple quotation marks:-

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.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)

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

III. Boolean literals:

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

IV. 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.

Eg:

1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>

V.Literal Collections.

Collections such as tuples, lists and Dictionary are used in Python.

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.

~+- The negation, unary plus and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+- Binary plus and minus

>> << Left shift and right shift

& Binary and.

^| Binary xor and or

<= < > >= Comparison operators (less then, less then equal to, greater then, greater then equal
to).

<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators


Punctuators:- Punctuators are symbols that are used in programming languages to organize
programming-sentence structure and indicate the rhythm and emphasis of expressions, statements and
program structure.

‘“#\()[]{}@,:.‘=
INTEGRATION OF ART

Activity :-

Program in lab using different operators of python.

Assignment:

Prepare Notes on character set, tokens, literals.


Day- 2
 Barebones of a Python Program
 Expressions
 Statements
 Comments
 Function
 Blocks and indentation
 Variables and Assignment

Expression: - An expression is any legal combination of symbols that represents a value.

Example :- 15, 2.9

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.

In the above code, you can see four comments :

(I) The physical lines beginning with # are the full line comments. There are three full
line comments in the above program are :

# This program shows a program’ s components

#Definition of function SeeYou( ) follows

#Main program code follows now

(II) The fourth comment is an inline comment as it starts in the middle of a physical line,
after Python code (see below)

If b < 5: # colon means it requires a block

Multiline comments :- Multiline comment in two ways :-

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 Seeyou() # function-call statement

Block and Indentation :- Sometimes a group of statements is part of another statement or


function. Such a group of one or more statements is called block or code-block or suite.

For ex :-

if b < 5:
print (“Value of b is less than 5”)
print(“Thank you”)

Variables and Assignment :-


Python Variables

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.

Declaring Variable and Assigning Values

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.

The equal (=) operator is used to assign value to a variable.

Eg:
Output:

1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>

Activity :-

Program to assign a value to variable and print its value.

Assignment:

Do the worksheet given in the class.


Day- 3

 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.

1. Assigning single value to multiple variables

Eg:

1. x=y=z=50
2. print iple
3. print y
4. print z

Output:

1. >>>
2. 50
3. 50
4. 50
5. >>>

2.Assigning multiple values to multiple variables:

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.

# This will store 6 in the memory and binds the

# name x to it. After it runs, type of x will


# be int.
x=6

print(type(x))

# This will store 'hello' at some location int


# the memory and binds name x to it. After it
# runs type of x will be str.
x = 'hello'

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.

Python Output Using print() function


We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given below.

print('This sentence is output to the screen')


# Output: This sentence is output to the screen

a=5

print('The value of a is', a)

# Output: The value of a is 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])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'

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

You might also like