0% found this document useful (0 votes)
4 views50 pages

Chapter 4 Python Programming Fundamentalsnew

Chapter 4 covers the fundamentals of Python programming, including the character set, user input/output functions, tokens, keywords, identifiers, literals, operators, comments, and data types. It explains the syntax and usage of various elements such as print(), input(), and different types of operators. Additionally, it discusses the structure of a Python program and the concept of variables.

Uploaded by

ayush429856
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)
4 views50 pages

Chapter 4 Python Programming Fundamentalsnew

Chapter 4 covers the fundamentals of Python programming, including the character set, user input/output functions, tokens, keywords, identifiers, literals, operators, comments, and data types. It explains the syntax and usage of various elements such as print(), input(), and different types of operators. Additionally, it discusses the structure of a Python program and the concept of variables.

Uploaded by

ayush429856
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

Chapter - 4

Python
Programming
Fundamentals
Python Character Set
A set of valid characters recognized by Python is called
Python Character Set. Python uses the traditional ASCII
character set. The latest version of Python recognizes the
Unicode character set. The ASCII character set is a subset
of the Unicode character set. The characters supported in
Python are:

Letters:– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbols available on keyboard, like
#,@,^,&,(,),/,etc
White spaces:– blank space, tab, carriage return \r,
new line \n, form feed
Other characters:- Python can process all ASCII and
UNICODE as a part of data or literal
User Input and Output
print() function : This function In Python is used to print output on the
screen.
Syntax of print Function
print(expression/variable)
e.g. print(122)
print('hello India')
print(5+2-4)
A=45
print(A)
print(‘Computer Science')
print(‘Computer',‘Science',sep=' & ')
print(‘Computer',‘Science',sep=' & ',end=‘****@')
Output :-
Computer Science
Computer & Science
Computer & Science****@
User Input and Output
Eg:
var1=‘Computers’
var2=‘Mobiles'
print(var1,' and ',var2)
Output :-
Computers and Mobiles

input(): This function of Python allows a user to give input to a program from
a keyboard but in the form of string.
Syntax: input(“String expression”) or input(‘String expression’)

NOTE : input() function always returns a string value . A string is a


sequence of characters. So we need int() or float() functions for data
conversion from string to integer or string to fractional (floating point)
number respectively.
e.g.
age = int(input(‘enter your age’)) # age will accept integers
percentage = float(input(‘enter percentage’))
e.g.
age = input(‘enter your age’)
C = age+2 #will produce an error because age is a string
Tokens

Smallest individual unit in a program is known as token.


Types of tokens in Python are:

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators
Keywords
Reserved words of the compiler/interpreter which can’t
be used as an identifier, are called keywords. Eg:

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
Identifiers
A Python identifier is a name used to identify a variable, function,
class, module or any other object.
Rules for naming an identifier are:
1) An identifier starts with a letter A to Z or a to z or an underscore (_).
2) An identifier can have zero or more letters, underscores and digits
(0 to 9) but it cannot start with a digit.
3) Python identifier does not allow special characters like %,#,@,$,(,),”,!,
-(hyphen),blank space etc.
4) Identifier must not be a keyword of Python.
5) Python is a case sensitive programming language. Upper and lower
case are different. Thus, RollNumber and rollnumber are two different
identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _num8_9,_7num
Some invalid identifier : 2rno,break,[Link],[Link]#ty
Literals
Literals in Python can be defined as number, text(string), or other data
that represent values to be stored in variables.
1)String Literals –Enclosed within ‘ ’ or “ ”
NAME = ‘AMIT’ fname =“john”
2)Integer Literals – These are numeric literals with no fractional
part.
age = 22
3)Float Literals – These are numeric literals with fractional part
height = 6.2
4)Boolean Literals – These are True or False values
A=True B=False
5)Special Literals –
Python has one special literal, which is None. It
indicate absence of value.
In other languages it is known as NULL.
It is also used to indicate the end of lists in
Python.
name = None
Literals – Escape characters
 Escape characters are the special characters which cannot be
typed directly from keyboard like backspace, tabs, enter, etc.
When such characters are typed, they perform some action.
Escape characters always begin with backslash(\) character.
Escape Sequence Description
\\ Backslash (\)

\' Single quote (')

\" Double quote (")

\a ASCII Bell (BEL)

\b ASCII Backspace (BS)

\f ASCII Formfeed (FF)

\n ASCII Linefeed (LF)

\r ASCII Carriage Return (CR)

\t ASCII Horizontal Tab (TAB)

\v ASCII Vertical Tab (VT)

\ooo Character with octal value ooo

\xhh Character with hex value hh


Operators
Operators can be defined as symbols that are used to perform
operations on operands.

Types of Operators

1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators
Operators
1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc.
Operators Description Example

+ perform addition of two number a+b

- perform subtraction of two number a-b

/ perform division of two number a/b 9/3=3 10/3=3.333

* perform multiplication of two number a*b

% Modulus = returns remainder a%b 9%3=0

Floor Division = remove digits after the


// decimal point a//b 10//3=3

** Exponent = perform raise to power a**b 2**3=8


Operators
2. Relational Operators/Comparison Operators
Relational Operators are used to compare the values.

Operators Description Example

==(equal Equal to, return true if a equals to b a == b


to)
!= (not Not equal, return true if a is not equals to b a != b
equal to)
Greater than, return true if a is greaterthan
> a>b
b

Greater than or equal to , return true if ais


>= a >= b
greater than b or a is equals to b

< Less than, return true if a is less than b a<b

Less than or equal to , return true if a is


<= a <= b
less than b or a is equals to b
Operators
3. Assignment Operators
Used to assign values to the variables.
Operators Description Example

= Assigns values from right side operands to left side operand a=b

+= Add 2 numbers and assigns the result to left operand. a+=b

/= Divides 2 numbers and assigns the result to left operand. a/=b

*= Multiply 2 numbers and assigns the result to left operand. a*=b

-= Subtracts 2 numbers and assigns the result to leftoperand. a-=b

%= modulus 2 numbers and assigns the result to leftoperand. a%=b

//= Perform floor division on 2 numbers and assigns the result to leftoperand. a//=b

**= calculate power on operators and assigns the result to leftoperand. a**=b
Operators
4. Logical Operators
Logical Operators are used to perform logical operations on the
given two variables or values.
Operators Description Example

and return true if both condition are true x and y

or return true if either or both condition are true x or y

not reverse the condition not(a>b)

Eg:
a=30
b=20
if(a==30 or b==40): # one or more conditions can be true
print('hello')

Output :- hello
Operators
a=30
b=20
if(a==30 and b==40): # both conditions should be True
print('hello’)
else:
print(“bye”)
Output :- bye

a=30
If(not a):
print(“hello”)
else:
print(“bye”)
Output :- bye
Operators
5. Membership Operators
The membership operators in Python are used to validate whether a
value is found within a sequence such as such as strings, lists, or
tuples.
Operators Description Example

in return true if value exists in the sequence, else false. a in list

not in return true if value does not exists in the sequence, else false. a not in list

E.g.
a = 400
list = [22,99,27,31]
Ans1 = a in list
Ans2 = a not in list
print(Ans1)
print(Ans2)
Output :-
False
True
Operators
6. Identity Operators
Identity operators in Python compare the memory locations of two objects.
Operators Description Example

is returns true if two variables point the same object, else false a is b

is not returns true if two variables point the different object, else false a is not b
e.g.
a=34
b=34
if (a is b):
print('both a and b have same identity')
else:
print('a and b have different identity')
b=99
if (a is not b):
print('a and b have different identity')
else:
print('a and b have same identity')
Output :-
both a and b have same identity
a and b have different identity
Punctuators
Punctuators are used to implement the grammatical and structure part of a
syntax in Python. Following are the python punctuators.
Expressions
An expression in Python is a combination of values, constants,
variables, operators, operands, functions etc. that are interpreted
according to the particular rules of precedence.

Expressions need to be evaluated, and they return a value.


Python supports many operators for combining data objects into
expressions.

Examples of expressions :
d=a+b-5

8-9/6*4**2
Evaluate the following expressions:
a) 6*3+4**2//5-8
Ans: 6*3+16//5-8=18+3-8=13
b) 10>5 and 7>12 or not 18>3
Ans: True and False or not True
= True and False or False
=True and False
=False

c) x % y // x, if x = 5, y = 4
Ans: 5%4 // 5 = 1 //5 = 0
d) 3-10**2+99/11
Ans: 3-100+9
=-88
Comments in Python
A comment is text that doesn't affect the outcome of a code, it is just a piece of text
to let someone know what you have done in a program or what is being done in a
block of code.
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing code.

There are 2 ways in which comments can be given:


1. Single-line comments : These are created simply by beginning a line with the
hash (#) character, and they are automatically terminated by the end of line.

Example:

#This program is used to display text on the screen

print("Hello, students!")
print(“How are you doing?") #This is a comment
Comments in Python
2. Multiple-line comments : Comments that span multiple lines – used to explain
things in more detail – are created by adding a delimiter (""") on each end of
the comment.
To add a multiline comment you could insert a # for each line or insert “’”:
Example:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OR
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
OR
‘’’
This is a comment
written in
more than just one line
‘’’
Barebone(Structure) of a
Python program
#function definition comment
def area(l,b):
a=l*b Function
print(a)
Block and indentation
A = 20 expression
print(“calculating the area of a rectangle”)
area(5,6)
statements
area(7,9)
area(3,4)

A python program contain the following components:


a. Expression
b. Statement
c. Comments
d. Function
e. Block & 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("Welcome to Python Programming")
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
Function is a block of code that has a name and can be reused by specifying its
name in the program where needed. It is created with def keyword. e.g. area() in
the previous slide

e. Block & indentation : Group of statements is a block. Indentation means extra


space before writing any statement. Indentation at same level creates a block.e.g. all
2 statements of area() function
Data Types
The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters.
Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
Python has 5 standard data types:
Data Types
1) Numeric - In Python, numeric data type represent the data which has numeric
value. Numeric value can be integer, floating number or even complex numbers.
Integers : 5,-7,8,etc
Floating Number : 8.9,5.54,-70.3
Complex: 6+7j where 6 is real part and 7 is imaginary part

2) Sequence -In Python, sequence is the ordered collection of similar or different


data types. Sequences allows to store multiple values in an organized and
efficient fashion. There are several sequence types in Python –
String - A string is a collection of one or more characters put in a single quote,
double-quote or triple quote. Egs:’hello’,”amita”,”emp@123”,etc.

List - Lists are just like the arrays, which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type, and lists are
mutable. Lists in Python can be created by just placing the sequence inside
square brackets [ ]. Egs: [6,9.8,”rohan”,True]

Tuple - Tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified
after it is created. Tuples in Python can be created by just placing the sequence
inside round brackets ( ). Egs: (8,12,6,3,9)
Data Types
3) Dictionary in Python is an unordered collection of data [Link] other Data
Types that hold only single value as an element, Dictionary holds key:value pair.
Each key-value pair in a Dictionary is separated by a colon :, whereas each
element is separated by a ‘comma’.
Eg: {name:’Ram’,age:25}

4) Boolean: In Python, Boolean values are represented by True and False, where
internally True is 1 and False is 0.

5) Set: Set is an unordered collection of unique items. Set is defined by values


separated by comma inside braces { }. Items in a set are not ordered.
Eg: a={819,34,12,105}
We can perform set operations like union, intersection on two sets. Sets have
unique values. They eliminate duplicates.
Eg: a={13,4,4,5,15,6,6,6}
print(a)
Variables
Variable is a name given to a memory location. A variable can be
considered as a container which holds values. Python is a type infer
language that means you don't need to specify the datatype of [Link]
automatically sets 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
c = True # boolean
Variable in python is created when you assign value to it i.e. a variable is not create in
memory until some value is assigned to it. Let us take as example(if we execute the
following code):
print(x)
Python will show an error “x” not defined

So to correct the above code: x=5


print(x) #now it will show no error
Use of type()
type() function returns the type of the specified object passed as a
parameter. type() function is mostly used for debugging purposes
Syntax: type(object)
where object can be any of the above data types
Eg:
var=5
print(type(var))
var=9.8
print(type(var))
var='h' Output:
print(type(var))
var="hello" <class 'int'>
<class 'float'>
print(type(var))
<class 'str'>
ls=[4,5]
<class 'str'>
print(type(ls)) <class 'list'>
d={4:'four',5:'five'} <class 'dict'>
print(type(d)) <class 'tuple'>
t=(4,5)
print(type(t))
Variables - Lvalue and Rvalue
 Lvalue : expression that comes on the Left hand Side of
Assignment.
 Rvalue : expression that comes on the Right hand Side of
Assignment
Lvalue refers to object to which you can assign value. It refers to memory
location. It can appear on the LHS or RHS of assignment
Rvalue refers to the value we assign to any variable. It can
appear on RHS of assignment
For example (valid use of Lvalue and Rvalue):
x = 100 # here x is the Lvalue and 100 is the Rvalue
y = z= 200 # here y and z are Lvalues and 200 is the Rvalue
Invalid use of Lvalue and Rvalue :
100 = x
200 = y
a+b = c
Note: values cannot comes to the left of assignment. LHS must be a
memory location
Variables - Multiple Assignments
 Python is very versatile with assignments. Different ways we can use
for multiple assignments in Python:
1. Assigning same value to multiple variable
a = b = c = 50
2. Assigning multiple values to multiple variables
a,b,c = 11,22,33
3. Swapping the values
a,b = b,a

Note: While assigning values throughmultiple assignment, remember


that Python first evaluates the RHS and then assigns them to LHS
Examples:
x,y,z = 10,20,30
z,y,x = x+1,z+10,y-10
print(x,y,z)
Output will be 10 40 11
Variables - Multiple Assignments

Now guess the output of following code fragment


x,y = 7,9
y,z = x-2, x+10

print(x,y,z)

7 5 17
Variables - Multiple Assignments
Let us take another example

y, y = 10, 20

In above code first it will assign 10 to y and again it assign 20 to y, so if


you print the value of y it will print 20

Now guess the output of following code


x, x = 100,200
y,y = x + 100, x +200
print(x,y)
200 400
Variables - Dynamic Typing

 In Python, a variable declared as numeric type can be further used to


store string type or another.
 Dynamic typing means a variable pointing to a value of certain type
can be made to point to value/object of different type.
 Lets us understand with example:

x = 100 # x points to numeric type


print(x)
x=“Welcome” # now x points to string type
print(x)
x=9.56
print(x)
x=True
print(x)
Variables - Dynamic Typing

 Always ensure correct operation during dynamic typing. If types are


not used correctly Python may raise an error.
 Example
x = 100
y= x/2
print(y)

x='Exam'
y=x/2 # Error, you cannot divide string
Complex Numbers
Complex: Complex number in python is made up of two floating point
values, one each for real and imaginary part. For accessing different
parts of variable (object) x; we will use [Link] and [Link]. Imaginary
part of the number is represented by “j” instead of “i”, so 1+0j denotes
zero imaginary. In 2+5j, 2 is the real part and 5 is the imaginary part.
part.
Example
x = 1+0j
print ([Link],[Link])
Output: 1.0 0.0
Example
y = 9-5j
print([Link], [Link])
9.0 -5.0
Variables – Type Conversion
 Python allows converting values of one data type to another data
type. This is called type conversion.
There are 2 types of type conversions:
1) Implicit type conversion
2) Explicit type conversion (also called type casting)
1) Implicit type conversion
If type conversion is done by the interpreter automatically, then it will be
known as implicit type conversion.
Example of Implicit type conversion:
x = 100
print(type(x)) # <type 'int'>
y = 12.5
print(type(y) # <type 'float'>
x=y
print(type(x)) #<type 'float'>
# Here x is automatically converted to float by the interpreter
Variables – Type Conversion
2) Explicit type conversion
Explicit type conversion is also called type casting. It takes place when
the programmer forces type conversion in the program. The syntax of
explicit type conversion or type casting is:
(new data type) (expression)
To perform explicit type conversion Python provide functions like int(),
float(), str(), bool()
>>> a=50.253
>>> b=int(a)
>>> print b
50
Here 50.253 is forcefully converted to int value 50
>>>a=25
>>>y=float(a)
>>>print y
25.0
Indentation in Python
Python indentation is a way of telling the Python interpreter that a
group of statements belongs to a particular block of code. To
indicate a block of code in Python, we must indent each line of the
block by the same whitespace character.

A code block (body of a function, loop, if, elif, else) starts with
indentation and ends with the first unindented line. The amount of
indentation is up to the user, but it must be consistent (same )
throughout that block.

Generally, four whitespaces are used for indentation and are


preferred over tabs.
Example:
for i in range(1,11):
print(i) block of statements
if i == 5:
break
print(i)
Indentation in Python
Why is indentation necessary in Python?

Indentation is required for indicating what block of code a statement


belongs to. Without indentation, Python does not know which
statement to execute next or which statement belongs to which
block. This will lead to IndentationError.

The enforcement of indentation in Python makes the code look neat


and clean. This results in Python programs that look similar and
consistent.
User-defined functions in Python

Functions that we define ourselves to do certain specific tasks are


referred as user-defined functions.

Advantages of user-defined functions -


1. User-defined functions help to decompose a large program into
small segments which makes program easy to understand,
maintain and debug.
2. If repeated code occurs in a program, function can be used to
include those codes and execute when needed by calling that
function.
3. Programmers working on large projects can divide the workload
by making different functions.
User-defined functions in Python

Example 1:

# Program to illustrate the use of user-defined functions

def add(x,y): # function definition


sum = x + y # function body
print(sum) # function body

#main program starts, the Python interpreter will start execution


#from here

num1 = 5
num2 = 6
add(num1, num2) # function call
User-defined functions in Python
Example 2:
#Program that calls user-defined functions to calculate the area and
#perimeter of a circle

def areacirc(radius): # function definition


area=3.14 * radius * radius # function body
return area # function body

def pericirc(radius): # function definition


peri=2*3.14*radius # function body
return peri # function body

#main program starts, the Python interpreter will start execution


#from here
r=float(input(“Enter radius of circle:”))
a=areacirc(r) # function call
p=pericirc(r) # function call
print("Area of circle=",a)
print("Perimeter of circle=",p)
Mutable and Immutable Data Types
Mutable data types - Those data types whose values can be changed in place.
Mutable objects are easy to change.
Mutable data types in Python are:
Lists
Dictionaries
Sets

Eg:
color = ["Red", "Green", "Blue"]
print(color)
color[0] = "Black"
color[2] = "White"
print(color)
Output: ["Red", "Green", "Blue"]
[“Black", "Green", “White"]
Mutable and Immutable Data Types
Immutable data types are those that can never change their value in place.
Immutable objects are quicker to access and difficult to change because it
involves the creation of a copy. Once they are initialized, their values
cannot be changed, but their identity can be changed. This means
that new variables are created if we try to change an immutable type.
Immutable data types in Python:
Integers
Floating-Point numbers
Booleans
Strings
Tuples

Eg:
greeting = "Welcome to Python World!!!"
greeting[0] = 'Hello'
print(greeting)
This program will give an error as greeting variable is a string and strings
are immutable.
Mutable and Immutable Data Types

Eg:

text = "Data Science“


print(id(text))
text += " with Python“
print(id(text))

Output:
2450343168944
2450343426208
DEBUGGING
Debugging means the process of finding errors, finding
reasons of errors and techniques of their fixation. An error, also
known as a bug, is a programming
code that prevents a program from its successful
interpretation.
Errors are of three types –
• Syntax Error
• Run Time Error
• Logical Error

1) Syntax Error
Violation of formal rules of a programming language results in syntax error.
Eg 1: len(‘hello’) = 5
SyntaxError: can't assign to function call
Eg 2: print(hello)
SyntaxError: name 'hello' is not defined.
DEBUGGING
2) Run time Error
These errors are generated during a program execution due to resource
limitation. Python is having provision of checkpoints to handle these errors.
Eg: a=10
b=int(input(“enter a number”))
c=a/b
Value of b to be entered at run time and user may enter 0 at run time, that may cause
run time error, because any number can’t be divided by 0
In Python, try and except clauses are used to handle an exception/runtime error which
is known as exception handling
try:
# code with probability of exception will be written here.
a=10
b=int(input(“enter a number”))
c=a/b
except:
#code to handle exception will be written here.
print(“Divide by zero error”)
DEBUGGING
3) Logical Error
If a program is not showing any compile time error(syntax error) or run time error
(exception) but not producing desired output, it may be possible that program is
having a logical error. Logical error is also called a semantics error.
Semantics refers to the set of rules which sets the meaning of statements. A
meaningless statement results in semantics error.
Eg - x * y = z
#The above
statement is a logical
error as we cannot
assign a variable to an
expression

Some examples-
• Use a variable without an initial value.
• Provide wrong parameters to a function
• Use of wrong operator in place of correct operator required for operation
X=a+b (Suppose here minus – was required in place of + as per requirement)
Assignment

 WAP to enter length and breadth and calculate perimeter and area
of a rectangle and print the result.
 WAP to enter radius of circle and calculate circumference and area
of circle and print the result.
 WAP to enter radius and height of cylinder and calculate the
volume of the cylinder and print the result.
 WAP to enter name, marks of 5 subjects of a student and calculate
total,average & percentage of marks for the student.
 WAP to enter distance in feet and convert it into inches.
 WAP to enter value of temperature in Fahrenheit and convert it into
Celsius and vice-versa.

You might also like