0% found this document useful (0 votes)
5 views94 pages

Python Basics: Character Sets & Tokens

The document provides an introduction to Python programming, covering fundamental concepts such as character sets, tokens, keywords, identifiers, literals, operators, and variables. It explains the rules for forming identifiers, the types of literals (string, numeric, boolean, and special), and the importance of indentation in Python code. Additionally, it discusses various operators and their functions, along with examples of variable assignments and dynamic typing.

Uploaded by

ekanshchawla940
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)
5 views94 pages

Python Basics: Character Sets & Tokens

The document provides an introduction to Python programming, covering fundamental concepts such as character sets, tokens, keywords, identifiers, literals, operators, and variables. It explains the rules for forming identifiers, the types of literals (string, numeric, boolean, and special), and the importance of indentation in Python code. Additionally, it discusses various operators and their functions, along with examples of variable assignments and dynamic typing.

Uploaded by

ekanshchawla940
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

CLASS XI

INFORMATICS
PRACTICES
Python
Fundamentals
INTRODUCTION
Python is a high-level, interpreted and general-
purpose dynamic programming language that
focuses on code readability. The syntax in Python
helps the programmers to do coding in fewer steps
as compared to Java or C++.

Let us learn the basic elements of python


programming
PYTHON CHARACTER SET
What is Character Set?
Character set is a bunch of identifying elements
in the programming language.

Python Character Set


A set of valid characters recognized by python. The latest version
of Python recognizes the Unicode character set. The ASCII
character set is a subset of the Unicode character set.
PYTHON CHARACTER SET

PYTHON
CHARACTER
SET

• Letters:- A-Z, a-z


• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab,
Carriage Return.
• Other Characters:- Python can process all 256 ASCII and
Unicode Characters.
What is Token or Lexical Unit?
TOKENS
Smallest individual elements that are identified by
programming language are known as tokens.

Various types of Tokens are:


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. punctuators
Types of Tokens
1.
Key
Word
s
5.
Punctuator 2.
s Identifiers
TOKENS

4.
Operators 3.
. Literals
1. What is Keyword or reserved word?
KEYWORDS
• Keywords are also called as reserved
words these are having special meaning in
python language.

• The words are defined in the python


interpreter hence these cant be used as
programming identifiers.
KEYWORDS
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
except
2. What is an Identifier?
IDENTIFIER
• A Python Identifier is a name given to a
function, class, variable, module, or other
objects that you’ll be using in your Python
program.
• In short, its a name appeared in the
program.
For example: a, b, c
a b and c are the identifiers and a b &
c and , are the tokens
PYTHON NAMING CONVENTIONS

OR

IDENTIFIER FORMATION RULES


Identifier Forming Rules
➢ An identifier can be a combination of uppercase letters,
lowercase letters, underscores, and digits (0-9).

➢ The first character must be a letter or an underscore.

➢ An identifier cannot contain any special character except


for underscore(_).

➢ An identifier should not begin with a number.

➢ You cannot use Python keywords as identifiers.

➢ Python is a case-sensitive language and this behaviour


extends to identifiers. Thus, Labour and labour are two
distinct identifiers in Python.
Identifier Forming Rules

SOME VALID IDENTIFIERS:


Myfile1 DATE9_7_8
y3m9d3 _xs
MYFILE _FXd
SOME INVALID IDENTIFIERS:
MY-REC 28dre break
elif False del
3. What is a Literal?
LITERALS
• Literals are data items that have fixed value.

• Literals are also called constants or constant


values

• Python allows several kinds of literals:


(i) String Literals
(ii) Numeric Literals
(iii)Boolean Literals
(iv)Special Literal None
4
1. Special Literal
STRING NONE
LITERALS
LITERALS

2.
NUMERIC 3. BOOLEAN
LITERALS. LITERALS
3. What is a String?
STRING LITERALS
• Sequence of letters enclosed in
quotes is called string literal.

• Python supports both form of


quotes

• Example: ‘hello’
‘’hello”
STRING LITERALS
Following are some valid string:
‘Aarti’
‘112FBasd’
‘1-2-f-g-h’
“12345”

>>> s = “hello world”


Types of String
SINGLE LINE STRINGS
• Strings created using single quote or
double quote must end in one line
are called Single Line Strings

For Example:
Item=“Computer”
Or
Item= ‘Computer’
MULTILINE STRINGS
Multiline string in Python can be
created in two ways:

a) By adding a backslash at the end


of a single quote or double quote
strings.

b) By typing the text in triple


quotation mark.
a)By adding backslash

Adding a backslash (\) at the end of


the line allows you to continue typing
text in the next line.

Example:
item = “key\
board is an\
input device”
a)By adding backslash
b) By typing the text in triple Quotation
Mark.
Python allows to type multiline text by enclosing
them in triple quotation marks (both triple
apostrophe or trile quotation mark will work”

Example:
item = “’key
board is an
input device’’’
b) By typing the text in triple Quotation
Mark.
For multi line strings created by triple
quotes, while calculating size, the
EOL(End of Line) character at the end of
line is also counted.
Strings With Triple Quotes
For multi line strings created by triple
quotes, while calculating size, the
EOL(End of Line) character at the end of
line is also counted.

For instance: Enter keys are


considered as
Str2=“’x EOL so size of
y str2 is 5

Z”’
Escape
Sequences
ESCAPE SEQUENCES

\\ Back Slash

\’ Single Quote (‘)

\” Double Quote (“)


ESCAPE SEQUENCES

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed
ESCAPE SEQUENCES

\n New Line

\r Carriage return

\t Horizontal Tab
ESCAPE SEQUENCES

\x 16 bit hex value

\ooo Octal Value


\\ Back Slash
\’ Single Qote
\” Double Quote
\a ASCII Bell
\n New Line
\r Carriage Return
\t Horizontal Tab
SIZE OF STRINGS
‘\\’ Size is 1 (\ is an escape
sequence)
‘abc’ size is 3
“\ab” size is 2
“Raama\’ Laptop” size is 13
“Raama’s Laptop” Size is 14
Python allows a single
quote(without escape
sequence)in double
quoted string and vice
versa
SIZE OF MULTILINE STRINGS
ST3= ‘’’a ST3= ’a\
b b\
c’’’ c’

Size is 5. Size is 3.
For multiline strings created For multiline strings created
using triple quotes, while using triple quotes, while
calculating the size, the calculating the size, the
EOL(end-of-line) character at backslash(\) character at the
the end of the line is also end of the line is not counted.
counted.
SIZE OF MULTILINE STRINGS

ST3= ’IN\ ST3= “””XY


FOR\ YZ”””
MATION’

Size is 11. Size is 5.


2. NUMERICAL LITERALS
Numerical Literals have the following
types:

int or integers - Whole numbers


float - real values
Complex - Complex numbers
Types of Numeric Literals
INTEGER LITERALS

❖ Decimal Integer Literals: Any whole number


(+ve) or (-ve).

Example of Integer Literals in Python(numeric literal)


age = 22

rollno-=121

Sc3=3456
INTEGER LITERALS

❖Octal Integer Literals(base 8): A Sequence of


digits starting with 0O (digit zero followed by
letter o) is taken to be an Octal Integer
Literals.

An octal value can contain only digits 0-7.

Example of Octal Integer Literals in Python:


0o22
0o77
0o829(invalid octal number as it contains digits 8 and 9)
INTEGER LITERALS

❖Hexadecimal Integer Literals (base 16):


Sequence of digits preceded by ox or OX is
hexadecimal integer literals

❖ A Hexadecimal value can contain only digits


0-9 and letters A-F.
Example of Hexadecimal Integer Literals in Python:
0x22
0X7A
FLOATING POINT LITERALS
Floating point literals are also
called as real literals having fractional part.

These may be written in one of the two forms:

1. Fractional Form: for example 15.75

2. Exponent Form: It consists of two parts


Mantissa and Exponent. for example 5.8 can be
represented as 0.58 x 101 = 0.58E01. where
mantissa part is 0.58 and E01 is the exponent.
COMPLEX LITERALS
[Link] LITERALS
A Boolean literal in python is used
to represent the Boolean values (true or
false).
4. SPECIAL LITERAL NONE
The None literal is used to indicate
absence of value.
For example: val = None
OPERATORS
OPERATORS
What is an operator?
Operators are tokens that
computation when applied to a variable.

What is Unary Operator?


Unary operators are those operators that
require one operand to operate upon.
Unary Operators:
+ Unary Plus
- Unary Minus
~ Bitwise Compliment
not Logical Negation
OPERATORS
What is Binary Operator?
Binary operators are those operators that
require two operands to operate upon.

Following are some Binary Operators:

(i) Arithmetic Operators


+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder or Modulus
** Exponent.
// Floor Division
OPERATORS
(ii) Relational Operators:

< Less than


> Greater than
<= Less than equal to
>= Greater than equal to
== Equal to
!= Not equal to
(iii) Logical Operators:
and Logical AND
or Logical OR
not Logical NOT
OPERATORS
(iv) Assignment Operators:
= Assignment Operator
*= Assign Product
/= Assign Quotient
+= Assign Sum
-= Assign Minus
%= Assign Remainder
**= Assign Exponent
//= Assign Floor Division.
BINARYOPERATORS EXAMPLE
BINARYOPERATORS EXAMPLE

Exponent

Floor
Division
OPERATORS
STRING OPERATOR
String operators work on String values These operators are of
two types:
• Concatenation( + ) : It is used to join two strings.
Example: print(‘Hello’ + ‘World’)
Output: HelloWorld

Example: print(“12345”+”40”)
Output: 1234540

Example: print(“Python”+ 40)


Output: Error(Python does not add a string and an
integer value

• Replication ( * ) : It is used to repeat a string a number of times.


Example: print(‘KIPS’ * 4)
Output: KIPSKIPSKIPSKIPS
PUNCTUATORS
PUNCTUATORS
Punctuators are also called as separators
The Followings are used as punctuators:
Brackets [ ]
Parentheses ( )
Braces { }
Comma ,
Semicolon ;
Colon :
Pound Sign #

Ellipsis …
VARIABLES AND ASSIGNMENTS
VARIABLES AND ASSIGNMENTS
Named labels are called variables.
For example: marks =86

78 79 80 81 82 83 84 85 86 87
2000 2016 2018 2026 2032 2044 2048 2050 2054 2068

marks refers to
location 2054
VARIABLES AND ASSIGNMENTS
Some more variables:

TrainNo = ‘T#12324’
balance = 234.45
rollNo = 105
VARIABLES AND ASSIGNMENTS

lvalues & rvalues:

Lvalue: Expressions that is on LHS (Left


Hand Side) is called Lvalue.

Rvalue: Expressions that is on RHS (Right


Hand Side) is called Rvalue.
VARIABLES AND ASSIGNMENTS

Multiple Assignments
Python is very versatile with
assignment statements.

1. Assigning same value to multiple


variables:
a=b=c=d=e=10
VARIABLES AND ASSIGNMENTS

2. Assigning Multiple values to multiple


variables:
p,q,r =5,10,15
print(q, r) will print 10 15
p,q=q,p
print (p,q) will print 10 5
VARIABLES AND ASSIGNMENTS

Expressions separated by commas


are evaluated from left to right.
Now,
x = 10
y,y = x+2,x+5

First It will assign y = 12 then y = 15


So print(y) will print 15
VARIABLES AND ASSIGNMENTS

Dynamic Typing:
A variable pointing to a value of certain
type can be made to point to a value/object
of different type this is called Dynamic
Typing.
x=10
print(x)
x=“ Hello World”
print(x)
VARIABLES AND ASSIGNMENTS

Output will be
10
x
Hello World
10

10

Hello World
VARIABLES AND ASSIGNMENTS

Caution with Dynamic Typing:

x = ‘day’
y = x/2 Error! String can not be divided.
VARIABLES AND ASSIGNMENTS
• type() function:

• To know the data type of a value which is pointing


use type ( )
• >>>a=10
• >>>type(a)

<class ‘int’> Type returned as integer


>>>a=20.4
>>>type(a) Type returned as float
<class ‘float’>
VARIABLES AND ASSIGNMENTS

• type() function:

• To know the data type of a value which is pointing


use type ( )
• >>>a=“Hello”
• >>>type(a)

<class ‘str’> Type returned as string


Barebone of a python program

A python program contain the following


components
a. Expression
b. Statement
c. Comments
d. Function
e. Block &n indentation
Barebone of a python program
a. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4
b. Statement :- instruction that does something.
e.g
a = 20
print("Calling in proper sequence")
c. Comments : which is readable for programmer but ignored by python
interpreter
i. Single line comment: Which begins with # sign.
ii. Multi line comment (docstring): either write multiple line beginning with # sign
or use triple quoted multiple line. E.g.
‘’’this is my
first
python multiline comment
‘’’
d. Function
a code that has some name and it can be reused.e.g. keyArgFunc in above
program
e. Block & indentation : group of statements is [Link] at same level
create a block.e.g. all 3 statement of keyArgFunc function
Indentation
Indentation refers to the spaces applied at the beginning of
a code line. In other programming languages the
indentation in code is for readability only, where as the
indentation in Python is very important.
Python uses indentation to indicate a block of code or used
in block of codes.
E.g.1
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented

E.g.2
if 3 > 2:
print(“Three is greater than two!") //indented so no error
INPUT FUNCTION
INPUT FUNCTION
Input( ) Function is a built in function of
python used to read values from the user
The general format or syntax of the input() is:

Variable_to_hold_the_value=input(message)

Where,
variable_to_Hold_the_Value is a variable
which is the label for a memory location
where the value is stored.
INPUT FUNCTION
For Example:
p = input(“Enter the value”)

NAME=input(“Whats your name?”)


INPUT FUNCTION

The input() function always returns a value of


String type.
READING NUMBERS

int ( ) and float ( ) Functions:


Python offers two functions to be used
with input( ) to convert the received values:

Example 1: >>age = int(input(“Enter age”))

Example 2: >>sal=float(input(“Enter salary))


READING NUMBERS

x = int(input(“Enter x value”))
reads the value and converts it in to integer type
data or value.
y=float(input(“Enter y value”))
reads the value and converts it in to float type
data or value.
INPUT FUNCTION

The input() function always returns a value of


String type.
PRINT FUNCTIONS
PRINT FUNCTION
print( ) Function is a built in function of
python used to display the values on the screen

The general format or syntax of the input() is:


print(*objects, sep=' ', end='\n)

The print function can print an arbitrary number


of values ("value1, value2, ..."), which are separated
by commas. These values are separated by blanks. In
the following example we can see two print calls. We
are printing two values in both cases, i.e. a string and
a float number:
PRINT FUNCTION
print(*objects, sep=' ', end='\n)

• Print() auto converts the items to strings i.e., if


you are printing a numeric value. It will
automatically convert it into equivalent string
and print it.
• For numeric expression, it first evaluates them
and then converts the result to string, before
printing.
PRINT FUNCTION
print(*objects, sep=' ', end='\n)

Examples:
print(“Python is an open source”)

print(“Sum of 2 and 3 is “, 2+3)

a=25
print(“Double of”, a, “is”, a*2)
PRINT FUNCTION
Examples:
print(“My”, “name”, “is”, “John.”)

Output: My name is John.

Using sep
print(“My”, “name”, “is”, “John.”, sep = ‘…’)

Output: My…name…is…John.
PRINT FUNCTION
Examples:
print(“My name is John.”)
print(“I am 16 years old.”)
Output: My name is John.
I am 16 years old.

Using end
print(“My name is John.”, end = ‘$’)
print(“I am 16 years old”)
Output: My name is John. $I am 16 years old
PRINT FUNCTION
Example 1: How print() works in Python?
print("Python is fun.")
a=5
#Two objects are passed:
print("a =", a)
b=a
# Three objects are passed:
print('a =', a, '= b‘)
Output
Python is fun.
a=5
a=5=b

You might also like