You are on page 1of 18

PYTHON

FUNDAMENTALS.
[Dear students please continue the notes of this
chapter ]
Blocks and indentation: Sometimes a group of
statements are a part of another statement or
function. Such a group of one or more statement is
called as a block or code block or a suite.
Example 1 if b<5:
print(“ value of b is less than 5”)
print (“Thank you “)
C and C plus plus Java use curly braces to show blocks.
Python does not use any such symbols it uses
indentation.
Example 2 if b < a:
temp = a
a =b
b= temp
print (“Thank you “)
A group of individual statements which makes a single
code block is also called as a suite in Python.
Example 3 def check( ):
c=a+b
if c< 50:
print(“ less than 50 “)
b = b*2
a = a+10
else
print (“Greater or equal to 50”)
a= a*2
b=b+10

Note: Python uses indentation to create blocks of


code. Statements at same indentation level are part of
the same block/suite.
Statements requiring suit / code block have a colon(:)
at their end .
You cannot unnecessarily indent a statement ,Python
will raise a error for that.
Python style rules and conventions
Some basic style rules
Statement termination: Python does not use any
symbol to terminate a statement. When you end a
physical code- line by pressing enter key, the
statement is considered terminated by default.
Maximum line length: Line length should be maximum
of 79 characters.
Lines and indentation: Blocks of code are denoted by
line indentation which is enforced through 4 spaces
(not tabs) per indentation level.
Blanks: Use two blank lines between top-level
definitions ,one blank line between method / function
definitions. Function and methods should be separated
with two blank lines and class definations with three
blank lines.
Avoid multiple statements on one line: Although you
can combine more than one statement in one line
using the symbol semicolon(;) between two statements
,but it is not recommended.
White space: You should always have White space
around operators and after punctuation, but not with
parenthesis. Python consider the following 6 spaces as
whitespaces, ' ' (space), \n (newline), \t(horizontal tab),
\v(vertical tab), \f(form feed), and \r (carriage return).
Case Sensitive: Python is case sensitive, showcase of
statements is very important. Care should be taken
when typing code and identifier names.
Docstring convention: Triple double strings (" " ") are
used for docstrings.
Identifier naming: Underscores may be used to
separate words in an identifier loan_amount or use
level case by capitalising first letter of each word Eg
LoanAmount.

Variables and assignments


Variable is a named label whose value can be used and
processed during program run.
For Example: To store name of a student and marks of
a student during program run we require some labels
to refer to these marks so that they are identified
easily.
Variables are called symbolic variables because these
are named labels.
Example1 marks=70
Creates a variable mark of numeric type.
Creating a variable
Python variables are created by assigning value of
desired type to them.
Example: To create a numeric variable assign a numeric
value to variable name, to create a string variable
assign a string value to variable name and so on.
Example1 Student = ‘Jacob ‘
Age =16
Student Jacob
Age 16
Example 2 :
Train_number = ‘#T123’ #Variable created of string
type
Balance = 2345 6.73 #Variable created for numeric
float type
Roll_no = 105 #Variable created for integer
numeric type.

Note: Variables are not storage containers in Python


like how variables are stored in other programming
languages like C, C + + or Java .
Traditional programming language variable creation .
Age = 15
The variable is created as a container at the memory
address and it stores value 15 in it.
Age =20
Now this statement changes the contents of variable
ageAge
but the location
15 memory address of variable does
not change.
Age 20
202530 202530

Python variables in memory


Python preloads commonly used values.
(Even before the identifier is created) in an area of
memory. We can refer it as front-loaded data space.
The database memory has literals/ values at different
memory locations and each memory location has a
memory address.
When we write age = 15, variable age is created as a
label pointing to memory location where value 15 is
stored.
.. 13 15 20
…………………………….20216…………………………………..20296
Age Age
And we write a statement age = 20 the label age will
not be having the same location as earlier. It will now
refer to value 20 which is at different location.
Now it is referring to location 20296.
Hence variables in Python do not have fixed locations
unlike other programming languages. Location changes
every time the value changes.[ this rule is not applied
for all variables]

L values and R values


Lvalues are the objects to which you can assign a value
or expression. Rvalues are literals and expressions that
are assigned to Lvalues. Rvalues can come on RHS of an
assignment statement.
Lvalue: Expressions that come on the LHS (left hand
side) of an assignment.
Rvalue: Expressions that come on the RHS (right hand
side) of an assignment.
Eg.1 a =20
b =10 #These are valid assignments
Eg.2 20=a
10=b #These are invalid assignment statements
a*2=b

Eg 3. age =18
Voting age = age
Note: In Python assigning a value to a variable means
variables label is referring to that value.
Multiple assignments
Python is very versatile with assignments.
a) Assigning same value to multiple variables
Example a=b=c =10
The above statement will assign value 10 to all the
variables a, b, c.
b) Assigning multiple values to multiple variables
Example x,y, z= 10, 20, 30
It will assign the values in the same order as mentioned
.First variable x is equal to 10 and so on. This type of
assigning is very compact.
Consider x, y= 25, 50
print(x, y)
It will print the result as 25 50
To swap the values of x and y we write
x,y =y,x
print (x,y)
Now the output will be 50 25
While assigning values through multiple assignments
remember Python first evaluates the RHS expressions
and then assigns them to the LHS
Example a, b,c = 5, 10, 7
b, c, a = a + 1, b + 2, c -1
print(a, b, c)
The final value printed will be 6, 6,12 .
[ please refer to the problems solved in the class]
Variable definition
In Python a variable is created when you first assign a
value to it. It also means that a variable is not created
until some value is assigned to it.
Example print (x)
X = 20
print (x)
The above code generates an error for statement at
line 1 since X is not defined.
x=0 # variable X is created now.
print (x)
x =20
print(x) # now the adjacent code is executed
without error.
Dynamic typing
A variable pointing to a value of creation type can be
made to point/ object of different type. This is called as
dynamic typing .
Example x =10
print (x)
x =" hello "
print (x)
Above code will yield the output as
10
Hello.
Hence variable X is first pointing to / referring to an
integer value 10 and then to a string value " Hello ".
Here the variable X does not have a type but the value
it points to has a type. So we can make the variable
point to a value of different type by re assigning a
value of that type. Python does not raise an error. This
is called as dynamic typing feature of Python.
Caution with dynamic typing
Although Python is compatible with changing types of a
variable, the programmer is responsible for ensuring
right types for certain type of operations.
Example x =10
y = 10
y= x/2 # this is legal since two integers can be used
for the divide operation.
x= " day " # python does dynamic typing.
y= x/2 # error is generated a string cannot be divided.
Hence as a programmer, ensure that variables with
right type of values should be used in expressions.

To determine the type of variable what type of value


does it point to the comment type (< variable name >)
can be used
Example a =10
type (a)
< class 'int'> # the type returned as integer
Example a =20.5
type (a)
< class 'float'> # the type returned as float
Example a = “Hello”
type (a)
< class 'str'> # the type returned as string

Simple input and output


In Python 3.8, to get the input from the user interactively you
can use built in functions input).
The general form is
variable_to_hold_the_value = input(< prompt to be
displayed >)
For example
Name= input (" what is your name?")
What is your name? # type your input data here
In front of this you can type your name. The value typed will
be assigned to the variable name in the above case.
Consider the following code
Name = input (" Enter your name ")
Enter your name: Riya
= age input (" Enter your age ")
Enter your age 16
>>> name
' riya'
>>> age
'16'
In the above code input( ) function is used to input 2 values
name and age.
Note: input() function always returns a value of string type.
When displaying the values name and age, Python has
enclosed both the values in quotes, i.e ‘Riya ‘ and ‘16’

Consider the following code


>>> age = input(“What is your age?”)
What is your age ? 16
>>> age
‘16’
>>>type(age)
str
/PF/
Reading numbers
String values cannot be used for arithmetic or other numeric
operations. For these operations numeric types (integer or
float) have to be used. Python offers two functions int( ) and
float( ) to be used with input( ) to convert the values received
through input() into ‘int’ and ‘float’ types. It can be used to
 Read in the value using the input() function.
 And then use int( ) or float( ) function with read value to
change the type of input value to ‘int’ or ‘float’
respectively.

Consider the following code


Example 1
>>>age = input (“what is your age?”)
what is your age? 16
>>>age = int( age )
>>>age=age+1
17
(After inputting value through input(), use int() or float() with
variable to change its type to ‘int’ or ‘float’ type)

Example 2
>>>Marks =input (“ Enter marks “)
Enter marks : 73.5
>>> Marks= float (marks)
>>> Marks + 1
74.5

The above steps can also be combined in a single step too .


<variable_name> = int(input(< prompt string >))
OR
< variable_name= float( input (< prompt string >))

Example 3
>>>Marks =float( input(“ Enter marks :”))
Enter marks : 73.5
>>>age= int( input (“what is your age ?”))
what is your age? 16
>>>type(marks)
float
>>>type (age)
int
Note: Function int( ) around input( ) converts the read value
into int type and function float( ) around input( ) function
converts the read value into float type. The type( ) function
is used to display data type of the variable.

Possible errors when reading numeric values


Whenever we use input( ) along with int( ) or float( ) care
should be taken to see that value entered should be in the
right format that is easily convertible to the target type .
Example age = int(input( “Enter your age :”))
Or
Percentage= float( input(“Enter your percentage:”)

1) >>>age=int( input(“ what is your age ?”))


What is your age 17.5
Value error: Invalid literal type for int()

What is your age? seventeen


Value error: Invalid literal

2) Enter your percentage


74.5.6
Value error: Could not convert string to float
Enter your percentage
73 percent
Value error: Could not convert string to float

Note: Values like 73, 73.0 , 0.73 can be easily converted into
float, hence Python reports no error if you enter such values
with float( ) used with input( )

Output through print () function


The print function of Python 3.x is a way to send output to
standard output device which is the monitor.
Consider the following examples
print (" hello ") # a string
print (17.5) # a number
print (3.14*r*r) # result of calculation assuming value is
stored in r.
print(" I am" ,12+5," years old") # multiple comma separated
expressions.

Consider the following examples with output


Example 1 print(" python is wonderful")
It will print the output as
Python is wonderful

Example 2 print (" Sum of 2 and 3 is ",2+3)


Sum of 2 and 3 is 5

Example 3 a=25
print(" Double of", a," is", a*2)
Double of 25 is 50.
Features of print function
The print function has a number of features
1) It 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 expressions it first evaluates
them and then converts the result to string before printing.
Note: With print the objects / that you give must be
convertible to string type.
2) It inserts spaces between items automatically because the
default value of sep argument is space(' '). The print
automatically adds the sep character between items / objects
being printed in a line. If no value is given for sep the print( )
will add a space in between the items when printing.
Consider the code
print (" My "," name "," is "," Riya")
will print My name is Riya
[ The output line has automatically spaces inserted in
between them because default sep character is a space]
print ("" My," name"," is","Riya ",sep="...")
will print
My... name... Is... Riya.
[ the print ()sep separated items with the given character
which is...]
3) It appends a newline character at the end of the line
unless you give your own end argument.
Consider the code
print (" My name is Amit ")
print(" I am 16 years old")
It will produce output as
My name is Amit
I am 16 years old.
So print () statement appended a newline at the end of
objects it printed.i,e
My name is Amit (with a cursor to the next line or \n)
The print( ) works this way only when you have not specified
any end argument with it, by default it takes the \n as the
newline
character.
Note: A print function without any value or name or
expression prints a blank line.
Example1 : print (" My name is Riya ", end=$)
print(" I am 16 years old")
Output: My name is Riya$ I am 16 years old.

Example2 : a , b=20,30
print ("a =" ,a, end =' ')
print ("b= ",b)
Output is a= 20 b =30
The space is because of end= ' ' the print().
Reason: In Example1 since the end character is given as $
the newline character '\ n' is not appended at the end of
output generated. Hence the output position cursor stays on
the same line.
[ Dear students please write down the program examples
discussed in the class at the end of the chapter]
1. Program to input length and breadth of a rectangle and
calculate the area
2. Program to input three numbers and print their sum
3. Write a program to input a number and print its cube
4. Write a program to input two numbers and interchange
them (swap them)
5.Write a program to input three numbers and swap them as
1st  2nd , 2nd  3rd , 3rd --> 1st .
**************************************************
**********************************

You might also like