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

CH - 6 Python Fundamentals

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

CH - 6 Python Fundamentals

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

JINI N K

PYTHON CHARACTER SET


• Set of valid characters that Python can
recognize

• Every component of a Python program is


created using the character set
PYTHON CHARACTER SET
Other
Special Characters
Symbols
Letters All ASCII
space Whitespaces and Unicode
Digits
A-Z + - * / ** \
( ) [ ] { } // Blank space,
characters
as part of
a-z 0-9 = != == < > tabs (→) data and
. ‘ “ ‘’’ , ; : Carriage literals
% ! & # <= return,
>= @ _ newline,
formfeed
Set of valid characters that Python can recognize
Tokens
Keywords
in
Python
Identifiers

Literals

Smallest individual unit in Operators


a program is known as a
Token or Lexical Unit Punctuators
Keywords
Keywords are the words having special meaning
reserved by programming language

Identifier
Literals
Operator

Punctuator
Keyword
Identifiers
Identifiers are fundamental building blocks of a program.
Names given to different parts of the program.

Identifiers
a
b
c
sum
Identifiers forming rules of Python
➢ Must be a combination of letters, numbers and underscore
➢ The first character must be a letter or underscore
➢ Upper and lower caseare different
➢ Thedigits 0-9 are allowed except for first character
➢ Identifier mustnot be a keyword
➢ No special characters are allowed other than underscore.
➢ Space notallowed
Valid Identifiers Invalid Identifiers
sum first-val
choice 6std
_data break
File12 True
Frt_100_L Data.open
Date_9_7_23 File 1
true value56$
Literals Literals are data items
that have a fixed value

Literals

String Boolean Numeric Special Collections


Single line True int None List

Multi line False float Tuple

complex Dictionary

Set
String Literals
String literal is a sequence of characters surrounded
by quotes (single/double/triple quotes)
String Literals
→ Non-graphic characters are allowed in string
→ Non-graphic characters – When keys are pressed
only some action takes place
→ Can be represented using escape sequences – a
backslash(\) followed by one or more character

\\ Backslash \n New line


\’ Single quote \t Horizontal tab
\” Double quote \r Carriage return
String Types
Single line Strings / Basic Strings

Strings that terminates in Python by default


a single line creates single-line
strings

Single line string

Python shows ERROR when


Enter key is pressed without
the closing quote
String Types
Multiline Strings Strings that stores multiple lines as
one single string

By adding a \ By typing the text in triple quotes


Size of Strings
Count of characters in the string
Count the escape sequence as one character
Size of Strings
Backslashes at the
end of intermediate Enter keys are
considered as EOL
lines are not counted
characters and counted
in the length of in the length of
multiline string. multiline string
Numeric Literals
int float complex
Positive or Positive or a+bj form where a,
negative whole negative b are floats and j
numbers with numbers with represents the
no decimal decimal point imaginary number
√-1
point

543 543.78 2+3j


-23 -23.001 -1+5j
Integer Literals
Decimal Integer Octal Integer Hexadecimal
Literals Literals Integer Literals

Sequence of Sequence of digits Sequence of digits


digits unless it [0 – 7] starting [0 – 9, A-F] starting
begins with 0 with 0o (digit 0 with 0x (digit 0
followed by the followed by the
letter o) letter x or X)
543 0o26 0x26
-23 0o51  Valid 0X9C  Valid
+66
0o281 0x26G
 Invalid  Invalid
0o98 0XQp8
Floating Point Literals
Also called real literals
Real numbers are numbers having fractional parts

Fractional Form 9.0


-51.89
-0.000812  Valid
• Must have atleast one digit with the
.7
decimal point, either before or after
6.
• Can have a + or – sign preceding it
8
• No sign is assumed to be positive +14/6
21,89.009  Invalid
67.008.12
Floating Point Literals
Exponent Form

121E04
• A real constant in exponent form has 1.71e06
two parts – a mantissa and an 12.6E01  Valid
exponent .25E-4
3.E2
•The mantissa is followed by a letter E -0.123E-2
or e and the exponent
1.5E
• The exponent must be an integer 0.13E5.2  Invalid
12,61e02
Boolean Literals
True / False

True and False are the


only two Boolean
literal values in Python
Special Literal None
None
None literal represents
the absence of a value
Literal Collections
Lists

Tuples

Dictionaries
Operators
Operators are tokens that trigger some computation/action
when applied to variables and other objects in an expression.

Unary Operators Binary Operators


Lists
Requires one operand Requires two operands
toDictionaries
operate upon to operate upon
Unary Operators
+ Unary plus - Unary minus

~ Bitwise complement

not
Dictionaries
Logical negation
Binary Operators
+ Addition
- Subtraction
* Multiplication
Arithmetic * Multiplication
Operators / Division
% Remainder/Modulus
** Exponent
// Floor division
Bitwise Operators

& Bitwise AND | Bitwise OR

^ Bitwise Exclusive OR

Shift Operators

<< Shift left >> Shift right


Dictionaries
Identity Operators

is is the identity same?

is not is the identity not same?

Logical Operators

Dictionaries
and Logical AND or Logical OR
< Addition
> Subtraction
Relational <= Multiplication
Operators >= Division
== Remainder/Modulus
!= Exponent
= Assignment
/= Assign quotient
+= Assign sum
Assignment *= Assign product
Operators %= Assign remainder
-= Assign difference
**= Assign Exponent
//= Assign Floor division
Membership Operators

in whether variable in sequence

not in whether variable not in sequence


sequence
Dictionaries
Punctuators
Punctuators are symbols that are used in programming
languages to organize programming sentence structures

Lists
‘ “ # \ ( ) [ ] { } @ , : . ` =
Barebones of a Python program
#Structure of a Python Program
#Definition of function SeeYou()
def SeeYou() : Functions
print(“Good Bye !!”)
Comments
#Main Program
a=25 Blocks/suite

Lists
b=a-15
print(a+5) Function call
if b>5 : #colon means it’s a block
print(“Value of ‘a’ is more than 15”) Statements/
else: Expressions
print(“Value of ‘a’ is less than 15”)
SeeYou() #function call
Expressions
→ An expression is any legal combination
of symbols that represents a value
→ Python evaluates and produces a value

Lists
Expressions that
are values only Complex expressions
Statement
→ A statement is a programming instruction that does
something
→ A statement executes and may or may not yield a value

Lists
Comments
→ Comments are the additional readable information to
clarify the source code
→ Begin with a symbol #
→ Comments enclosed in triple quotes are called doc strings

Full line comment


Lists Inline comment

Multi line
comment
Blocks and Indentation
→ Block or Code-Block or Suite
→ Group of statements or a function which are part of
another statement or a function
→ Python uses indentation to create blocks or code
→ Statements at same indentation level are part of same
Lists
block/suite
→ Python will raise error for unnecessary indentation
→ Indentation – 4 spaces
→ Line length – maximum 79 characters
Block inside
function

Two different
indentation
levels
Variables
→ Named labels or named storage locations
→ Values can be used and processed during program run
→ Variables in Python do not have fixed locations

Student = “Alex” Variable of string type

Age = 13 Variable of integer type


Python will
Student Alex
internally create
labels to refer
Age 13 the values
Python Variables in Memory

10 15 20 21 40 55
1935435072 1935435152 1935435232 1935435144 1935435552 1935435180

a b c x y z

a=10 x=20
b=a y=40
c=15 z=y
Lvalues and Rvalues
lvalue rvalue
→ Objects to which you → Literals and
assign a value or an expressions that are
expression assigned to lvalues
→ Expressions that come → Expressions that come
on the lhs of an on the rhs of an
assignment expression
Lists

lvalue rvalue
Multiple Assignments
Assignment same Assignment
value to multiple multiple values to
variables multiple variables

Lists
To assign values To swap values

→ While assigning values through multiple assignments, Python first


evaluates the RHS and then assigns them to the LHS
→ Expressions separated by commas are evaluated from left to right
Lists
and assigned in same order
Variable Definition
→ A variable is defined only when some value is assigned to it
→ Undefined variable causes an error called Name Error

Valid

Lists
Invalid
Dynamic Typing
A variable pointing to a value of a certain type, can be made
to point to a value/object of different type.

int
A X 10

Python string
Caution - Dynamic Typing
Programmer is responsible to ensure correct data types
is used in expressions

Dynamic typing
int

float
Static Typing
→ Data type of a variable cannot be changed
→ Once declared, data type is fixed
→ C, C++ supports static typing

Python supports
dynamic typing
Determining the Data type
type(<variable name>)
Input Statement
To get input from user interactively, use built-in
function input()

Syntax: variable = input(<prompt message>)

Prompt Message

Input data
Note - Input Statement
The input() function always return a value of String type
Input – Numbers
int() and float() functions to be used with input()
float()
Possible Errors
Output Statement
The print() function is used to display the output
Syntax:
print(*objects,[sep=‘ ’ or end=‘\n’ or <end-string>])
Empty line

A print() without any value or


expression prints a blank line
Features – print()
→ It auto converts the items to strings and then prints

String
→ Inserts spaces between items automatically
→ The default value of sep=‘ ‘
→ Inserts sep character between items automatically
→ Appends a new line character at the end of the line
→ end argument with print() function
→ The default value of end argument is newline
character (\n)
Predict the output

Output
Write a program to
input a welcome
message and print it
Program to input a welcome message and print it

Output
Write a program to
obtain three
numbers and print
their sum
Program to obtain three numbers and print their sum

Output
Write a program to
obtain length and
breadth of a rectangle
and calculate its area
Program to obtain length and breadth of a rectangle
and calculate its area

Output
Write a program calculate
BMI (Body Mass Index) of a
person.
BMI=kg/m where
2

kg – person’s weight in kg
m – height in meter squared
2
Program to calculate BMI = kg/m2

Output
Write a program to
input a number and
print its cube
Write a program to input a number and print its cube

Output
Write a program to
input a value in
kilometres and
convert into miles
(1 km=0.621371)
Write a program to convert kilometres to miles

Output
Write a program to input a
value in tonnes and convert
into quintals and kilograms
1 tonne = 10 quintals
1 tonne = 1000 kgs
1 quintal = 100 kgs
Write a program to convert it
into quintals and kilograms

Output
Write a program to
input two numbers
and swap them
Write a program to input two numbers and swap them

Output
Write a program to input
three numbers and swap
them.
→ 1 number becomes 2
st nd

→ 2 number becomes 3
nd rd

→ 3 number becomes 1
rd st
Write a program to input three numbers and swap

Output
JINI N K

You might also like