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

IP Python - Basic-1

This document provides an introduction to Python fundamentals, including Python character sets, tokens, operators, the barebones of a Python program, variables, data types, and input/output. It discusses the basic building blocks of Python like keywords, identifiers, literals, operators, and punctuators. It also covers core concepts like variables, data types, functions, expressions, statements, blocks, indentation, operator precedence, and built-in input/output functions.

Uploaded by

Aditi Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

IP Python - Basic-1

This document provides an introduction to Python fundamentals, including Python character sets, tokens, operators, the barebones of a Python program, variables, data types, and input/output. It discusses the basic building blocks of Python like keywords, identifiers, literals, operators, and punctuators. It also covers core concepts like variables, data types, functions, expressions, statements, blocks, indentation, operator precedence, and built-in input/output functions.

Uploaded by

Aditi Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

PYTHON FUNDAMENTAL

ABHAY YADAV
PGT (IP)

1 IP@SJC Ranjhi
INTRODUCTION.................................................................................................................................................. 4

PYTHON CHARACTER SET ................................................................................................................................... 4

TOKEN ................................................................................................................................................................ 5

SMALLEST INDIVIDUAL UNIT IN A PROGRAM IS KNOWN AS TOKEN. ................................................................................ 5


1. KEYWORDS.................................................................................................................................................. 5
2. IDENTIFIERS ................................................................................................................................................. 5
3. LITERALS ..................................................................................................................................................... 5
4. OPERATORS................................................................................................................................................. 5
5. PUNCTUATORS / DELIMITERS........................................................................................................................... 5
KEYWORDS ..................................................................................................................................................... 5
IDENTIFIERS..................................................................................................................................................... 6
LITERALS ........................................................................................................................................................ 7
OPERATORS .................................................................................................................................................... 8
Types of Operators................................................................................................................................ 8
1. Arithmetic Operators. ....................................................................................................................... 8
2. Relational or Compression Operators. ............................................................................................... 8
3. Logical Operators. ............................................................................................................................. 8
4. Assignment Operators. ..................................................................................................................... 8
5. Bitwise Operators ............................................................................................................................. 8
6. Membership Operators ..................................................................................................................... 8
7. Identity Operators ............................................................................................................................. 8
Arithmetic operators............................................................................................................................. 9
Relational or Comparison operators.................................................................................................... 10
Example 2: Comparison operators in Python ....................................................................................... 11
Logical Operators................................................................................................................................ 12
Assignment operators ......................................................................................................................... 12
Bitwise operators ................................................................................................................................ 13
Membership operators ....................................................................................................................... 14
Identity operators ............................................................................................................................... 14
Example 4: Identity operators in Python.............................................................................................. 15
PUNCTUATORS / DELIMITERS ............................................................................................................................ 15

OPERATORS PRECEDENCE ................................................................................................................................ 16

BAREBONE OF A PYTHON PROGRAM .............................................................................................................. 18

THE BAREBONES OF PYTHON PROGRAM ARE EXPRESSIONS, STATEMENTS, COMMENTS,FUNCTIONS, BLOCK AND INDENTATION.18
EXPRESSIONS................................................................................................................................................. 18
STATEMENT .................................................................................................................................................. 18
COMMENTS .................................................................................................................................................. 18
FUNCTIONS ................................................................................................................................................... 18
BLOCK AND INDENTATION ................................................................................................................................ 18

VARIABLES ....................................................................................................................................................... 19

VARIABLE SCOPE AND LIFETIME IN PYTHON PROGRAM ............................................................................................ 20


1. Local Variable ................................................................................................................................. 20
2. Global Variable ............................................................................................................................... 20

PYTHON DATA TYPES ....................................................................................................................................... 21

BUILT-IN DATA TYPES...................................................................................................................................... 21

2 IP@SJC Ranjhi
DYNAMIC TYPING ........................................................................................................................................... 21

INPUT AND OUTPUT : ...................................................................................................................................... 23

PYTHON OUTPUT USING PRINT() FUNCTION ......................................................................................................... 23


PYTHON INPUT .............................................................................................................................................. 24

3 IP@SJC Ranjhi
PYTHON FUNDEMENTAL

Introduction
Python 3.0 was released in 2008. Although this version is
supposed to be backward incompatibles, later on many of
its important features have been back ported to be
compatible with version 2.7

Python Character Set


A set of valid characters recognized by python. Python
uses the traditional ASCII character set. The latest version
recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode
character set Letters :– A-Z, a-z Digits :– 0-9
Special symbols :– Special symbol available over
keyboard
White spaces:– blank space,tab,carriage return,new
line, form feed
Other characters:- Unicode

4 IP@SJC Ranjhi
Token
Smallest individual unit in a program is known
as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators / Delimiters

Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name
or any other identifier. They are used to define the syntax
and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can
vary slightly over the course of time.

All the keywords except True, False and None are in


lowercase and they must be written as they are. The list of
all the keywords is given below.

5 IP@SJC Ranjhi
Keywords in Python programming language
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Identifiers
A Python identifier is a name used to identify a variable,
function, class, module or other object.
An identifier is a name given to entities like class,
functions, variables, etc. It helps to differentiate one entity
from another.
* An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
* Python does not allow special characters
* Identifier must not be a keyword of Python.
* Python is a case sensitive programming language.
Thus, Rollnumber and rollnumber are two different
identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Some invalid identifier : 2rno,break,my.book,data-cs

6 IP@SJC Ranjhi
Literals
Literals in Python can be defined as number, text, or
other data that represent values to be stored in variables.
Example of String Literals in Python
name = ‘Johni’ , fname =“johny”
Example of Integer Literals in Python(numeric literal)
age = 22
Example of Float Literals in Python(numeric literal)
height = 6.2
Example of Special Literals in Python
name = None
Escape Characters

To insert characters that are illegal in a string, use an


escape character.
An escape character is a backslash \ followed by the
character you want to insert.
Some Escape Characters are:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
7 IP@SJC Ranjhi
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

Operators
Operators are special symbols in Python that carry out
arithmetic or logical computation. The value that the
operator operates on is called the operand.
Types of Operators
1. Arithmetic Operators.
2. Relational or Compression Operators.
3. Logical Operators.
4. Assignment Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

8 IP@SJC Ranjhi
Arithmetic operators
Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication, etc.
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or x - y- 2
unary minus
* Multiply two operands x*y
/ Divide left operand by the right one x/y
(always results into float)
% Modulus - remainder of the division of x%y
left operand by the right (remainde
r of x/y)
// Floor division - division that results x // y
into whole number adjusted to the left
in the number line
** Exponent - left operand raised to the x**y (x to
power of right the power
y)

Example of Arithmetic Operators :


x = 15
y=4

# Output: x + y = 19
print('x + y =',x+y)

9 IP@SJC Ranjhi
# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)

Relational or Comparison operators


Comparison operators are used to compare values. It
returns either True or False according to the condition.
Operator Meaning Example
> Greater than - True if left operand is greater x>y
10 IP@SJC Ranjhi
than the right
< Less than - True if left operand is less than x<y
the right
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to - True if left operand x >= y
is greater than or equal to the right
<= Less than or equal to - True if left operand is x <= y
less than or equal to the right
Example 2: Comparison operators in Python
x = 10
y = 12

# Output: x > y is False


print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

# Output: x == y is False
print('x == y is',x==y)

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)

11 IP@SJC Ranjhi
Logical Operators
Logical Operators are used to perform logical operations
on the given two variables or values.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the not x
operand)

x = True
y = False

print('x and y is',x and y)

print('x or y is',x or y)

print('not x is',not x)
Output:
x and y is False
x or y is True
not x is False

Assignment operators
Assignment operators are used in Python to assign values
to variables.
is a simple assignment operator that assigns the value
a = 5

5 on the right to the variable a on the left.


12 IP@SJC Ranjhi
There are various compound operators in Python like a +=
5 that adds to the variable and later assigns the same. It is

equivalent to a = a + 5 .
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Bitwise operators
Bitwise operators act on operands as if they were strings
of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111 .
In the table below: Let x = 10 (0000 1010 in binary) and y = 4
(0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 ( 0000 0000 )
| Bitwise OR x | y = 14 (0000 1110 )

13 IP@SJC Ranjhi
~ Bitwise NOT ~x = -11 (1111 0101 )
^ Bitwise XOR x ^ y = 14 (0000 1110 )
>> Bitwise right shift x >> 2 = 2 (0000 0010 )
<< Bitwise left shift x << 2 = 40 (0010 1000 )

Membership operators
in and not in are the membership operators in Python. They

are used to test whether a value or variable is found in a


sequence (string, list, tuple, set and dictionary).In a dictionary we
can only test for presence of key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the 5 not in x
sequence
Example :
x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)

Identity operators
is and is not are the identity operators in Python. They are

used to check if two values (or variables) are located on

14 IP@SJC Ranjhi
the same part of the memory. Two variables that are equal
does not imply that they are identical.
Operator Meaning Example
is True if the operands are identical (refer to x is True
the same object)
is not True if the operands are not identical (do not x is not
refer to the same object) True
Example 4: Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)

Punctuators / Delimiters
A delimiter is a sequence of one or more characters used
to specify the boundary between separate, independent
regions in plain text or other data streams. An example of
a delimiter is the comma character, which acts as a field
delimiter in a sequence of comma-separated values.

• Leave some space for one table here*

15 IP@SJC Ranjhi
Operators Precedence

The operator precedence in Python is listed in the


following table. It is in descending order (upper group has
higher precedence than the lower ones).

() Parentheses

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus

* / % // Multiply, divide, modulus and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

<= < > >= Comparison operators

<> == != Equality operators

16 IP@SJC Ranjhi
= %= /= //= -= Assignment operators
+= *= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

17 IP@SJC Ranjhi
Barebone of a python program
The barebones of python program are
Expressions, Statements, Comments,Functions,
Block and Indentation.

Expressions: They are the combination of symbols with


values to evaluate. eg: x + y

Statement: These are Instructions that python can


execute. eg: if statement, for statement

Comments: This is the additional information about the


statement. There are single and multiline comments
available. These are ignored by Interpreter.

Functions: It is itself a small program that takes input


and processed and gives
output.
eg: print(), input()

Block and Indentation: Block is a piece of code that


executes as a unit. Indentation is a space given for better
readability and understanding.

18 IP@SJC Ranjhi
Variables
Variable is a name given to a memory location. A variable
can be considered as a container which holds value.
Python is a type infer language that means you don't need
to specify the datatype of variable. Python automatically
get variable datatype depending upon the value assigned
to the variable.
Assigning Values to Variable
name = ‘python' # String Data Type
sum = None # a variable without value
a = 23 # Integer
b = 6.2 # Float
sum = a + b
print (sum)
Multiple Assignment: assign a single value to many
variables
a = b = c = 1 # single value to multiple variable
19 IP@SJC Ranjhi
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped

Variable Scope and Lifetime in Python


program
1. Local Variable
def fun():
x=8
print(x)
fun()
print(x) #error will be shown
2. Global Variable
x=8
def fun():
print(x) # Calling variable ‘x’ inside fun()
fun()
print(x) # Calling variable ‘x’ outside fun()

20 IP@SJC Ranjhi
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different
types can do different things.
Python has the following data types built-in by default, in
these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Dynamic typing
Data type of a variable depend/change upon the value
assigned to a
variable on each next statement.
X = 25 # integer type
X = “python” # x variable data type change to string on
just next line

21 IP@SJC Ranjhi
Now programmer should be aware that not to write like
this:
Y = X / 5 # error !! String cannot be devided

22 IP@SJC Ranjhi
Input and Output :
Python Output Using print() function
We use the print() function to output data to the standard
output device (screen).
An example of its use is given below.
print('This sentence is output to the screen')
Output:
This sentence is output to the screen

print() Function In Python is used to print output on the


screen.
Syntax of Print Function
print(expression/variable)
e.g.
print(122)
Output :-122
print('hello India')
Output :-hello India
print(‘Informatics',‘Practices')
print(‘Informatics',‘Practices',sep=' & ')

23 IP@SJC Ranjhi
print(‘Informatics',‘Practices',sep=' & ',end='.')
Output :-
Informatics Practices
Informatics & Practices
Informatics & Practices.

Python Input
Up until now, our programs were static. The value of
variables was 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'

24 IP@SJC Ranjhi

You might also like