0% found this document useful (0 votes)
15 views15 pages

Chap-4 Python Fundamentals

Uploaded by

clashesofclans79
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)
15 views15 pages

Chap-4 Python Fundamentals

Uploaded by

clashesofclans79
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/ 15

CHAPTER-3(Python Fundamentals)

Python Fundamentals
Python Character Set- A to Z, a to z, 0-9, whitespaces (spaces, tabs(\t), newline
feeds(\n)) , special symbols(#,_,=,+,-,*,** etc.).

ASCII CODES ::::::


A to Z = 65 to 90
a to z = 97 to 122
0 to 9 = 48 to 57

TOKEN (Smallest individual or Lexical unit )


1. Keywords( Reserved Words)
2. Identifiers ( user/programmer defined words)
3. Literals (Constants)
4. Delimiter( Separators or Punctuators)
5. Operator

1) Keywords – These are the special reserved words that convey a special meaning
to the language compiler/interpreter. Python have 33 keywords. Eg; if, else, for,
while, break, from, import, and, or , not, in, return etc.
2) Identifiers - These are user-defined words and are fundamental building blocks
of program. Generally Identifiers are used to give names to the different parts in
program viz. variables, objects, classes, functions, lists etc.

Variables (Kind of Identifiers)


Variables are containers for storing data values. Unlike other programming
languages, Python has no command for declaring a variable. A variable is created
the moment you first assign a value to it.
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
age = 39

age 39

Variable name Data / Value

*Rules for valid Python variables/identifiers :::


1. A variable name must start with a letter or the underscore character
2. A variable name cannot start with a number
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three different variables)

#Legal variable names:


myvar = "Silicon"
my_var = "Silicon"
_my_var = "Silicon"
myVar = "Silicon"
MYVAR = "Silicon"
myvar2 = "Silicon"
z=20
sum=23+90
num=50.3

#Illegal variable names:


2myvar = "Silicon"
my-var = "Silicon"
my var = "Silicon"

Concept of L-value and R-value


Lvalue and Rvalue refer to the left and right side of the assignment operator.
The Lvalue (pronounced: L value) concept refers to the requirement that the operand
on the left side of the assignment operator is modifiable, usually a variable.
Rvalue concept pulls or fetches the value of the expression or operand on the right
side of the assignment operator.
Some examples:
age = 39

L value R value

The value 39 is pulled or fetched (Rvalue) and stored into the variable named age
(Lvalue); destroying the value previously stored in that variable.
voting_age = 18
age = voting_age

3) Literals/ Values – Literals are data items that have fixed/ Constant value. Types
of Literals:::
i) String Literals
ii) Numeric Literals
iii) Boolean Literals
iv) Special Literal None
v) Literal Collection
1. String Literals – The text enclosed in quotes ( single(‘ ‘), double(“ “), triple( “””
“””)) forms a String Literal in python. Eg; ‘abc’, “abc”, “””abc”””, ‘123’, ’Raman’ etc.
String types in Python:-
(1) Single Line String- Strings that are terminated within a single-line and surrounded with
mainly single(‘ ‘) and double quotes(“ “) are known as Single line Strings.

Example
a) text1='hello'
b) s=”Python Programming”

(2) Multi-line String - A piece of text that is written in multiple lines is known as multiple
lines string. There are two ways to create multiline strings:

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


Example
text1='hello\
user'
print(text1)

Output -
hellouser
2) Using triple quotation marks:-
Example
str2="""welcome
to
SSSIT"""
print (str2)

Output
welcome
to
SSSIT

2. 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 both Integers of unlimited Real numbers with In the form of a+bj
positive and negative) size followed by both integer and where a forms the real
with no fractional lowercase or uppercase fractional part eg: -26.2 part and b forms the
part.eg: 100 L eg: 87032845L imaginary part of the
complex number. eg:
3.14j

Example
Numeric Literals
x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
Float Literal
float_1 = 100.5
num_2 = 1.5e2
Complex Literal
a = 5+3.14j

print(x, y, z, u)
print(float_1, num_2)
print(a, a.imag, a.real)

Output
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0

3. Boolean literals:
A Boolean literal can have any of the two values: True or False.
Example
Boolean Literals
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)

Output
x is True
y is False
z is False
a: 11
b: 10

4. Special literal (None)- 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 the end of lists in
Python.
Example:-
Special Literals
val1=10
val2=None
print(val1)
print(val2)

Output
10
None

5. Literal Collections- Python provides the four types of literal collection such as
List literals, Tuple literals, Dictionary literals and Set literals.

4) Delimiter (Punctuators) - 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.
The following tokens serve as delimiters:
( ) [ ] { } @ , : . ` = ;+= -= *= /= //= %= &= |= ^= >>= <<= **=
5) Operators- Operators are used to perform operations on variables and
values.

Escape sequence
Escape Sequence are non-printable characters.
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Form-feed (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

COMMENTS
Comments are used to add a remark or a note in the source code. Comments are not
executed by interpreter. In Python, a comment starts with # (hash sign). Everything
following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.
They are added with the purpose of making the source code easier for humans to
understand.

Types of Comments:-
1. Single line Comments
Single-line comments are created simply by beginning a line with the hash (#) character, and they are
automatically terminated by the end of line.
Example
#This is a comment in Python
2. Multiline 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.
Example
"""
This would be a multiline comment
in Python that spans several lines and
describes your code or anything you want it to be. """

#To display values of variables


message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)

Output:
Keep Smiling
User Number is 101

Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data .

Mutable and Immutable Data Types


Sometimes we may require to change or update the values of certain variables used in a
program. However, for certain data types, Python does not allow us to change the values once a
variable of that type has been created and assigned values.
Variables whose values can be changed after they are created and assigned are called mutable.
Variables whose values cannot be changed after they are created and assigned are called
immutable.
When an attempt is made to update the value of an immutable variable, the
old variable is destroyed and a new variable is created by the same name in memory.
Operators
Operators are symbols used to perform operations on operands/variables and values.
There are three types of operators: (i) Unary, ( ii) Binary and (iii) Ternary.

( i) Unary - Which works on one operand/variable/ data value.


( ii) Binary - Which works on exactly two operands/variables/ data values.
(iii) Ternary - Which works on three operands/variables/ data values.

Python divides the operators in the following groups:


1. Arithmetic operators (+, -, *, /, //(integer division), %(remainder), **(power))
2. Assignment operators (=)
3. Relational/ Comparison operators (>, <, >=, <=, ==, !=(<>) (not equal to))
4. Logical operators (and, or , not)
5. Identity operators
6. Membership operators
7. Bitwise operators

1) Arithmetic Operators: - Python supports arithmetic operators that are used to


Perform the four basic arithmetic operations as well as modular division, integer
division and exponentiation.

Operator Name Example


+ Addition x+y
- Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Integer Division x // y

2) Assignment Operators: - Assignment operator assigns or changes the value of


the variable on its left.
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
3) Comparison (Relational) Operators: - Comparison operators are used to compare
two values.
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

4) Logical Operators: - Logical operators are used to combine conditional statements.

Operator Description Example


And Returns True if both statements are true x < 5 and x < 10
Or Returns True if one of the statements is true x < 5 or x < 4
Not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

TRUTH TABLE (Logical and operator)


X Y X and Y
FALSE(0) FALSE(0) FALSE(0)
FALSE(0) TRUE (1) FALSE(0)
TRUE (1) FALSE(0) FALSE(0)
TRUE (1) TRUE (1) TRUE(1)
TRUTH TABLE (Logical or operator)
X Y X or Y
FALSE(0) FALSE(0) FALSE(0)
FALSE(0) TRUE (1) TRUE(1)
TRUE (1) FALSE(0) TRUE(1)
TRUE (1) TRUE (1) TRUE(1)

TRUTH TABLE (Logical not operator)

X not (X)
FALSE(0) TRUE (1)
TRUE (1) FALSE(0)
5) Identity Operators : - Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object, with the same memory
location.
Operator Description Example
is Returns True if both variables are x is y
the same object
is not Returns True if both variables are x is not y
not the same object

6) Membership Operators : - Membership operators are used to check if a value is a


member of the given sequence or not. There are 2 types of membership operators:
(i) in operator
(ii) not in operator

7) Bitwise Operators : - Bitwise operators are used to compare (binary) numbers.

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
~ NOT Inverts all the bits

BASIC TERMS
Expressions: - An expression is defined as a combination of constants,
variables, and operators. An expression always evaluates to a value.

Statement: - In Python, a statement is a unit of code that the Python interpreter


can execute.

BASIC PREDEFINED FUNCTIONS IN PYTHON

1. print( ) function – To return and print strings/values on the shell window.

2. id( ) function - To return and print the identity or address of the passed
variable.
Every object/variable in Python is assigned a unique identity (ID) which
remains the same for the lifetime of that object. Eg;
num1 = 20
>>> id(num1)
1433920576 #identity of num1

3. type( ) function - To return and print the type or class of the passed
variable. Python has an in-built function type() to ascertain the data type of a
certain value. For example, enter type(1234) in Python shell and it will
return <class 'int'>, which means 1234 is an integer value.
Eg;
>>> type(20)
<class 'int'>
>>> type(55.50)
<class 'float'>
>>> type(6+4j)
<class 'complex'>
>>> type("hello")
<class 'str'>
>>> type([1,2,3,4])
<class 'list'>

DYNAMIC INPUT – input() function

Accepting Input from Console/Shell -The input() function prompts the user to enter data.
It accepts all user input as string. The user may enter a number or a string but the
input() function treats them as strings only.
input1 = input()
print(input1) # output

Typecasting the input to Integer:


There might be conditions when you might require integer input from user/Console, the following
code takes two input (integer/float) from console and typecasts them to integer then prints the sum.
# input
num1 = int(input())
num2 = int(input())
print(num1 + num2) # printing the sum in integer

Typecasting the input to Float:


To convert the input to float the following code will work out.
# input
num1 = float(input())
num2 = float(input())
print(num1 + num2) # printing the sum in float

eval() function – It is used to convert any string type into Numeric(int/float) depends upon the
entered value.
num1 = eval(input())
num2 = eval(input())
print(num1 + num2) # printing the sum in int/float depends upon input .

TYPE CONVERSION

The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type conversion.

1. Implicit Type Conversion

2. Explicit Type Conversion

Implicit Type Conversion- Python automatically converts one data type to


another data type. This process doesn't need any user involvement. No any data loss
occurs in this case. Eg;
#Implicit type conversion from int to float

num1 = 10 #num1 is an integer


num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float
and an integer
print(sum1)
print(type(sum1))

Output:
30.0
<class 'float'>

Explicit Type Conversion- Programmers/Users convert the data type of an


object to required data type. We use the predefined functions like int() , float() , str() ,

etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects. Data loss may occurs in this case. Eg;
#Explicit type conversion from float to int

num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))

Output:
30.8
<class 'float'>
30
<class 'int'>

Debugging - The process of identifying and removing mistakes, also known


as bugs or errors from a program is called debugging.

Types of Errors

i) Syntax errors - Syntax errors are the types of errors which arise when
there is a Violation of Programming language grammatical rules like;
incorrect indentation, incorrect arguments etc. Such errors need to be
removed before the execution of the program.

ii) Logical errors – A logical error is a bug in the program that causes
it to behave incorrectly. A logical error produces an undesired output but
without abrupt termination of the execution of the program. Logical errors
are also called semantic errors as they occur when the meaning of the
program (its semantics) is not correct.

iii) Runtime errors - A runtime error causes abnormal termination of


program while it is executing. Runtime error is when the statement is
correct syntactically, but the interpreter cannot execute it. Runtime errors
do not appear until after the program starts running or executing. Eg;
“division by zero”.
*** PYTHON PROGRAMMING ***

1. Write a Python program to perform the basic calcii operations on 2 static


values.
Ans.
#PROGRAM FOR BASIC CALCII OPERATIONS

NUM1=50
NUM2=30
print("SUM IS:::: ",NUM1+NUM2)
print("SUB IS:::: ",NUM1-NUM2)
print("MUL IS:::: ",NUM1*NUM2)
print("DIV IS:::: ",NUM1/NUM2)

2. Write a Python program to perform the basic calcii operations on 2


dynamic values.
Ans.
#PROGRAM FOR BASIC CALCII OPERATIONS

NUM1=eval(input(“Enter first number : ”))


NUM2= eval(input(“Enter second number : ”))
print("SUM IS:::: ",NUM1+NUM2)
print("SUB IS:::: ",NUM1-NUM2)
print("MUL IS:::: ",NUM1*NUM2)
print("DIV IS:::: ",NUM1/NUM2)

3. PROGRAM FOR CALCULATING AREA OF CIRCLE, RECTANGLE, SQUARE


Ans.
#PROGRAM FOR CALCULATING AREA OF CIRCLE, RECTANGLE, SQUARE

r=eval(input("Enter radius of circle : "))


print("AREA OF CIRCLE IS:::: ",3.14*r*r)

l= eval(input("Enter length of rectangle : "))


b= eval(input("Enter breadth of rectangle : "))
print("AREA OF RECTANGLE IS:::: ",l*b)

s=eval(input("Enter side of square : "))


print("AREA OF Square IS:::: ",s*s)

You might also like