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

Python BasicsJIdentifiers LJReserved Keywords LJData Types LJTypecasting, Error

This document provides an overview of the Python programming language. It discusses that Python is a high-level, general-purpose programming language that was created in 1991 and is recommended for beginners. The document then covers key features of Python like being high-level, interpreted, portable, having a rich library, supporting both procedural and object-oriented programming. It also discusses Python versions, identifiers, reserved words, and basic data types in Python.

Uploaded by

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

Python BasicsJIdentifiers LJReserved Keywords LJData Types LJTypecasting, Error

This document provides an overview of the Python programming language. It discusses that Python is a high-level, general-purpose programming language that was created in 1991 and is recommended for beginners. The document then covers key features of Python like being high-level, interpreted, portable, having a rich library, supporting both procedural and object-oriented programming. It also discusses Python versions, identifiers, reserved words, and basic data types in Python.

Uploaded by

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

Language Fundamentals

Introduction

• Python is a general-purpose high-level programming language.

• Python was developed by Guido Van Ressam in 1989 while


working at NationalResearch Institute at Netherlands.

• But officially Python was made available to public in 1991. The official
Date of Birth forPython is: Feb 20th 1991.

• Python is recommended as first programming language for beginners.

Eg1: To print

Helloworld:

Python:

print("Hello World")

Python:

1) a=10

3) print("The Sum:",(a+b))

Features of Python
• Python is a high-level language. It is a free and open-source language.
• It is an interpreted language, as Python programs are executed by an interpreter.
• Python programs are easy to understand as they have a clearly defined syntax and
relatively simple structure.
• Python is case-sensitive. For example, NUMBER and number are not same in
Python.
• Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services and
applications are built using Python.
• Python uses indentation for blocks and nested blocks.
1. Simple and easy to learn:

Python is a simple programming language. When we read Python


program,we can feel likereading English statements. The syntaxes are very
simple and only 30+ keywords are available. When compared with other
languages, we can write programs with very a smaller number oflines. Hence
more readability and simplicity.
We can reduce development and cost of the project.

2. Freeware and Open Source:

We can use Python software without any license and it is freeware. Its source
code is open, so that we can we can customize based on our requirement.Eg:
Jython is customized version of Python to work with Java Applications.

3. High Level Programming language:

Python is high level programming language and hence it is programmer


friendly language.Being a programmer we are not required to concentrate
low level activities like memory management and security etc.

4. Platform Independent:

Once we write a Python program, it can run on any platform without rewriting
once again. Internally PVM is responsible to convert into machine
understandable form.

5. Portability:

Python programs are portable. ie we can migrate from one platform to


another platformvery easily. Python programs will provide same results on
any platform.

6. Dynamically Typed:

In Python we are not required to declare type for variables. Whenever we


are assigning the value, based on value, type will be allocated automatically.
Hence Python is consideredas dynamically typed language.

This dynamic typing nature will provide more flexibility to the programmer.
7.
Both Procedure Oriented and Object Oriented

Python language supports both Procedure oriented (like C, pascal etc) and
object oriented(like C++,Java) features. Hence, we can get benefits of both
like security and reusability etc

8. Interpreted:

We are not required to compile Python programs explcitly. Internally


Python interpreterwill take care that compilation.

If compilation fails interpreter raised syntax errors. Once compilation success


then PVM(Python Virtual Machine) is responsible to execute.

9. Extensible:

We can use other language programs in


Python. The main advantages of this
approach are:

1. We can use already existing legacy non-Python code


2. We can improve performance of the application

10. Embedded:

We can use Python programs in any other language programs.


i.e we can embed Python programs anywhere.

11. Extensive Library:

Python has a rich inbuilt library. Being a programmer we can use this library
directly and we are not responsible toimplement the functionality.
Flavors of Python:

1. CPython:
It is the standard flavor of Python. It can be used to work with C lanugage
Applications

2. Jython or JPython:
It is for Java Applications. It can run on JVM

3. IronPython:
It is for C#.Net platform

4. PyPy:
The main advantage of PyPy is performance will be improved because JIT
compiler isavailable inside PVM.

5. RubyPython
For Ruby Platforms

6. AnacondaPython
It is specially designed for handling large volume of data processing.
...

Python Versions:

Python 1.0V introduced in Jan 1994


Python 2.0V introduced in October
2000 Python 3.0V introduced in
December 2008

Note: Python 3 won't provide backward compatibility to Python2


i.e there is no guarantee that Python2 programs will run in Python3.

Current versions

Python 3.6.1 Python 2.7.13


Identifiers
A name in Python program is called identifier.
It can be class name or function name or module name or

variable name.a = 10

Rules to define identifiers in Python:

1. The only allowed characters in Python are

• alphabet symbols (either lower case or upper case)


• digits (0 to 9)
• underscore symbol (_)

By mistake if we are using any other symbol like @ then we will get syntax
error.

• cash = 10 √
• ca@h =20 x

2. Identifier should not start with digit

• 123total x
• total123 √

3. Identifiers are case sensitive. Of course, Python language is case sensitive


language.

• total=10
• TOTAL=999
• print(total) #10
• print(TOTAL) #999
1. Alphabet Symbols (Either Upper case OR Lower case)

2. If Identifier is start with Underscore (_) then it indicates it is private.

3. Identifier should not start with Digits.

4. Identifiers are case sensitive.

5. We cannot use reserved words as


identifiersEg: def=10 X

6. There is no length limit for Python identifiers. But not recommended to


use too lengthyidentifiers.

7. Dollor ($) Symbol is not allowed in Python.

Q. Which of the following are valid Python identifiers?

1) 123total X
2) total123 √
3) java2share √
4) ca$h X
5) _abc_abc_ √
6) def X
7) if X

Note:

1. If identifier starts with _ symbol then it indicates that it is private


2. If identifier starts with (two underscore symbols) indicating that
strongly privateidentifier.
3. If the identifier starts and ends with two underscore symbols then the
identifier is language defined special name,which is also known as
magic methods.

Eg: add
Reserved Words
In Python some words are reserved to represent some meaning or
functionality. Such typeof words is called Reserved words.

There are 33 reserved words available in Python.

• True,False,None
• and, or ,not,is
• if,elif,else
• while,for,break,continue,return,in,yield
• try,except,finally,raise,assert
• import,from,as,class,def,pass,global,nonlocal,lambda,del,with

Note:
1. All Reserved words in Python contain only alphabet symbols.

2. Except the following 3 reserved words, all contain only lower-case alphabet
symbols.

• True
• False
• None

Eg: a= true X
a=True √

>>> import keyword


>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
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. In Python we are not required to specify the type
explicitly. Based on value provided, thetype will be assigned automatically.
Hence Python is Dynamically Typed Language.

Python contains the following inbuilt data types

1. int
2. float
3. compl
ex
4.bool
5.str
6. bytes
7. bytearra
Y
8. range
9.list
10.tuple
11.set
12. frozen
set
13. dict
14.None
Note: Python contains several inbuilt

functions
1. type()
to check the type of variable

2. id()
to get address of object

3. print()
to print the value

In Python everything is object

Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.

int data type:

We can use int data type to represent whole numbers


(integral values)
Eg:
a=10
type(a) #int

Note:
In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long
values also byusing int type only.

We can represent int values in the following ways

1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form

1. Decimal form(base-10):
It is the default number system in PythonThe allowed digits are: 0 to 9
Eg: a =10

2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111

3. Octal Form(Base-8):

The allowed digits are : 0 to 7


Literal value should be prefixed with 0o or 0O.

Eg: a=0o123
a=0o786

4. Hexa Decimal Form(Base-16):

The allowed digits are : 0 to 9, a-f (both lower and upper cases are
allowed)Literal value should be prefixed with 0x or 0X

Eg:
a =0XFAC
a=0XBeef

Note: Being a programmer we can specify literal values in decimal, binary,


octal and hexadecimal forms. But PVM will always provide values only in
decimal form.

a=10
b=0o10
c=0X10
d=0B10
print(a)
10
print(b)
8
print(c)
16
print(d)
2
Base Conversions
Python provide the following in-built functions for base conversions

1. bin():

We can use bin() to convert from any base

to binaryEg:
1 >>> bin(15)
)
2 '0b1111'
)
3 >>> bin(0o11)
)
4 '0b1001'
)
5 >>> bin(0X10)
)
6 '0b10000'
)

2. oct():

We can use oct() to convert from any base to octal

Eg:

1 >>> oct(10)
)
2 '0o12'
)
3 >>> oct(0B1111)
)
4 '0o17'
)
5 >>> oct(0X123)
)
'0o443'
6
)

3. hex():

We can use hex() to convert from any base to hexa

decimalEg:
1 >>> hex(100)
)
2 '0x64'
)
3 >>> hex(0B111111)
)
4 '0x3f'
)
5 >>> hex(0o12345)
)
6 '0x14e5'
)

float data type:


We can use float data type to represent floating point values (decimal values)

Eg: f=1.234
type(f) float

We can also represent floating point values by using exponential form


(scientific notation)

Eg: f=1.2e3
print(f) 1200.0
instead of 'e' we can use 'E'

The main advantage of exponential form is we can represent big values in less
memory.
***Note:
We can represent int values in decimal, binary, octal and hexa decimal
forms. But we canrepresent float values only by using decimal form.

1) f=0B11.01
2) ^
SyntaxError: invalid syntax

Complex Data Type:


A complex number is of the form

j2 = -1
a + bj
j = √−1
Real Part Imaginary Part

a and b contain integers or floating point

values

Eg:
3+5j
10+5.5j
0.5+0.1j

In the real part if we use int value then we can specify that either by
decimal,octal,binary or hexa decimal form.But imaginary part should be
specified only by using decimal form.

1) >>> a=0B11+5j
2)>>>a
3) (3+5j)

Even we can perform operations on complex type values.


Note: Complex data type has some inbuilt attributes to retrieve the
real part and imaginary part

c=10.5+3.6j

c.real==>10.5
c.imag==>3.6

We can use complex type generally in scientific Applications and


electrical engineering Applications.

4. bool data type:


Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True value is non-zero, non-null and non-
empty. Boolean False is the value zero.
Internally Python represents True as 1 and False as 0.

b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True

True+True==>2
True-False==>1

Sequence
A Python sequence is an ordered collection of items, where each item is indexed by
an integer. The three types of sequence data types available in Python are Strings,
Lists and Tuples.
5. str type:
str represents String data type.

A String is a sequence of characters enclosed within single quotes or


double quotes.
s1='Python'
s1="Python"

By using single quotes or double quotes we cannot represent multi line string

literals.

s1="Python

programming” X

For this requirement we should go for triple single quotes(''') or triple double

quotes(""")

s1='''Python
Programming'''

s1="""Python
Programming"""
We can also use triple quotes to use single quote or double quote in our
String.

Slicing of Strings:
slice means a piece
[ ] operator is called slice operator, which can be used to retrieve
parts of String.

In Python Strings follows zero based index.The index can be either


+ve or -ve.

+ve index means forward direction from Left to Right


-ve index means backward direction from Right to Left

-5 -4 -3 -2 -1
O F F E R
0 1 2 3 4

1 >>> s="OFFER"
2 >>> s[0]
3 'O'
4 >>> s[40]

IndexError: string index out of range

1 >>> s[1:40]
2 'FFER'
3 >>> s[1:]
4 'FFER'
5 >>> s[:4]
6 'OFFE'
7 >>> s[:]
8 'OFFER'
9 >>> len(s)
10 5

Note:
1. In Python the following data types are considered as Fundamental Data
types

• int
• float
• complex
• bool
• str

2. In Python,we can represent char values also by using str type and
explicitly char type isnot available.

Eg:

1) >>> c='a'

3) <class 'str'>

3. long Data Type is available in Python2 but not in Python3. In Python3


long values alsowe can represent by using int type only.

4. In Python we can present char Value also by using str Type and
explicitly char Type isnot available.
list data type:
List is a sequence of items separated by commas and the items are enclosed in
square brackets [ ]

1. insertion order is preserved


2. heterogeneous objects are allowed
3. duplicates are allowed
4. Growable in nature
5. values should be enclosed within square brackets.

Eg:

1) list=[10,10.5,'python',True,10]
2) print(list) # [10,10.5,'python',True,10]

>>> list1 = [5, 3.4, "New Delhi", "20C", 45]


#print the elements of the list list1
>>> print(list1) [5, 3.4, 'New Delhi', '20C', 45]

Note: An ordered, mutable, heterogenous collection of elements is


nothing but list, whereduplicates also allowed.

Tuple
Tuple is a sequence of items separated by commas and items are enclosed
in parenthesis ( ). This is unlike list, where values are enclosed in brackets [
]. Once created, we cannot change the tuple.

#create a tuple tuple1

>>> tuple1 = (10, 20, "Apple", 3.4, 'a')

#print the elements of the tuple tuple1

>>> print(tuple1) (10, 20, "Apple", 3.4, 'a')


Note: tuple is the read only version of list.
Set
Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have
duplicate entries. Once created, elements of a set cannot be changed.

#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
>>> print(set1) {10, 20, 3.14, "New Delhi"}

#duplicate elements are not included in set


>>> set2 = {1,2,1,3}
>>> print(set2)
>>>{1, 2, 3}

1. insertion order is not preserved


2. duplicates are not allowed
3. heterogeneous objects are allowed
4. index concept is not applicable
5. It is mutable collection
6. Growable in nature

None Data Type:

None is a special data type with a single value. It is used to signify the absence
of value in a situation. None supports no special operations, and it is neither
same as False nor 0 (zero).

>>> myVar = None


>>> print(type(myVar))
>>> print(myVar)
None

None means Nothing or No value associated. If the value is not available, then
to handle such type of cases None introduced.It is something like null value in
Java.
Eg:
def m1():
a=10
print(m1())
None

Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.

(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a
dictionary are enclosed in curly brackets { }.

Dictionaries permit faster access to data. Every key is separated from its
value using a colon (:) sign. The key : value pairs of a dictionary can be
accessed using the key.
The keys are usually strings and their values can be any data type.
In order to access any value in the dictionary, we have to specify its key in
square brackets [ ].
#create a dictionary

>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}


>>> print(dict1) {'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120} >>>
print(dict1['Price(kg)'])

120

Duplicate keys are not allowed but values can be duplicated. If we are
trying to insert an entry with duplicate key then old value will be
replaced with new value.
Mutable and Immutable Data Types
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.

All Fundamental Data types are immutable. i.e once we creates an


object, we cannot perform any changes in that object.

Concepts immutability
Constants:

Constants concept is not applicable in Python.


But it is convention to use only uppercase characters if we don’t

want to change value.MAX_VALUE=10

It is just convention but we can change the value.


Operators
Operator is a symbol that performs certain operations

1. Arithmetic Operators:
Python supports arithmetic operators that are used to perform the four basic
arithmetic operations as well as modular division, floor division and
exponentiation.

Note: / operator always performs floating point arithmetic. Hence it


will always returnsfloat value.

But Floor division (//) can perform both floating point and integral
arithmetic. If arguments are int type then result is int type. If atleast
one argument is float type thenresult is float type.
Relational Operators:

Note: Chaining of relational operators is possible. In the chaining, if all


comparisons return True then only result is True. If at least one
comparison returns False then theresult is False

Eg:

1 10<20 ==>True
2 10<20<30 ==>True
3 10<20<30<40 ==>True
4 10<20<30<40>50 ==>False

Note: Chaining concept is applicable for equality operators. If atleast one


comparison returns False then the result is False. otherwise the result is
True.

Eg:
1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
4) True
Logical Operators:
There are three logical operators supported by Python. These operators (and, or,
not) are to be written in lower case only.
The logical operator evaluates to either True or False based on the logical operands
on either side.
Every value is logically either True or False.
By default, all values are True except None, False, 0 (zero), empty collections "", (),
[], {}, and few other special values.
So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically True.

For boolean types behaviour:


and ==>If both arguments are True then only result is True
or ====>If at least one argument is True then result is True
not ==>complement
True and False =>False
True or False ===>True
not False ==>True

For non-boolean types behaviour:

0 means False
non-zero means True
empty string is always treated as False
Assignment Operators:
We can use assignment operator to assign value to the variable.

Eg:
x=10

We can combine assignment operator with some other operator to


form compound assignment operator.(Augmented Assignment Opera

Eg: x+=10 ====> x = x+10

The following is the list of all possible compound assignment operators in


Python

+= ,-= ,*=,/=,%=,//=,**=&=,|=,>>=,<<=
Special operators:
Python defines the following 2 special operators

1. Identity Operators
2. Membership operators

1. Identity Operators
Identity operators are used to determine whether the value of a variable is of
a certain type or not. Identity operators can also be used to determine whether
two variables are referring to the same object or not. There are two identity
operators.
We can use identity operators for address comparison.

Note:
We can use is operator for address comparison where as ==
operator for contentcomparison.

2. Membership operators:
We can use Membership operators to check whether the given object
present in thegiven collection.(It may be String,List,Set,Tuple or Dict)

in : Returns True if the given object present in the specified Collection


not in :Retruns True if the given object not present in the specified

Collection
EXPRESSIONS
An expression is defined as a combination of constants, variables,
and operators. An expression always evaluates to a value. A value or
a standalone variable is also considered as an expression but a
standalone operator is not an expression. Some examples of valid
expressions are given below.
(i) 100
(ii) num
(iii) num – 20.4
(iv) 3.0 + 3.14
(v) 23/3 -5 * 7(14 -2)
(vi) "Global" + "Citizen”

Operator Precedence:
Evaluation of the expression is based on precedence of operators. When an
expression contains different kinds of operators, precedence determines which
operator should be applied first. Higher precedence operator is evaluated before
the lower precedence operator.

• Binary operators are operators with two operands.


• The unary operators need only one operand, and they have a higher
precedence than the binary operators.
• The minus (-) as well as + (plus) operators can act as both unary and binary
operators, but not is a unary logical operator.
Eg:
print(3+10*2) ➔ 23
print((3+10)*2) ➔ 26
How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
Solution:
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4
STATEMENT
In Python, a statement is a unit of code that the Python interpreter can
execute.

Example
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement 4 64

TYPE CONVERSION
we can change the data type of a variable in Python from one type to another.
Such data type conversion can happen in two ways: either explicitly (forced)
when the programmer specifies for the interpreter to convert a data type to
another type; or implicitly, when the interpreter understands such a need by
itself and does the type conversion automatically.

Explicit Conversion
Explicit conversion, also called type casting happens when data type
conversion takes place because the programmer forced it in the program.

The general form of an explicit data type conversion is:

(new_data_type) (expression)

With explicit type conversion, there is a risk of loss of information since we


are forcing an expression to be of a specific type.
For example, converting a floating value of x = 20.67 into an integer type,
i.e., int(x) will discard the fractional part .67.

Following are some of the functions in Python that are used for explicitly
converting an expression or a variable to a different type.

Type Casting
We can convert one type value to another type. This conversion is
called Typecasting orType coersion.
The following are various inbuilt functions for type casting.

1. int()
2. float()
3. complex()
4. bool()
5. str()

1.int():
We can use this function to convert values from

other types to intEg:

1) >>> int(123.987)
2) 123
3) >>> int(10+5j)
4) TypeError: can't convert complex to int
5) >>> int(True)
6 1
)
7) >>> int(False)
8 0
)
9 >>> int("10")
)
10) 10
11) >>> int("10.5")
12) ValueError: invalid literal for int() with base 10: '10.5'
13) >>> int("ten")
14) ValueError: invalid literal for int() with base 10: 'ten'
15) >>> int("0B1111")
16) ValueError: invalid literal for int() with base 10: '0B1111'

Note:

1. We can convert from any type to int except complex type.


2. If we want to convert str type to int type, compulsary str should
contain only integral value and should be specified in base-10

2. float():

We can use float() function to convert other type values to float type.

1 >>> float(10)
)
2 10.0
)
3 >>> float(10+5j)
)
4) TypeError: can't convert complex to float
5) >>> float(True)
6 1.0
)
7) >>> float(False)
8 0.0
)
9 >>> float("10")
)
10) 10.0
11) >>> float("10.5")
12) 10.5
13) >>> float("ten")
14) ValueError: could not convert string to float: 'ten'
15) >>> float("0B1111")
16) ValueError: could not convert string to float: '0B1111'

Note:
1. We can convert any type value to float type except complex type.

2. Whenever we are trying to convert str type to float type


compulsary str should beeither integral or floating point literal
and should be specified only in base-10.

3. complex():

We can use complex() function to convert other types to complex type.

Form-1: complex(x)
We can use this function to convert x into complex number with real
part x and imaginarypart 0.

Eg:

1 complex(10)==>10+0j
)
2 complex(10.5)===>10.5+0j
)
3) complex(True)==>1+0j
4) complex(False)==>0j
5 complex("10")==>10+0j
)
6 complex("10.5")==>10.5+0j
)
7) complex("ten")
8) ValueError: complex() arg is a malformed string

Form-2: complex(x,y)

We can use this method to convert x and y into complex number such
that x will be realpart and y will be imaginary part.
Eg: complex(10,-2)==>10-
2j
complex(True,False)==>1+
0j

4. bool():

We can use this function to convert other type

values to bool type.Eg:

1) bool(0)==>False
2) bool(1)==>True
3) bool(10)===>True
4) bool(10.5)===>True
5) bool(0.178)==>True
6) bool(0.0)==>False
7) bool(10-2j)==>True
8) bool(0+1.5j)==>True
9) bool(0+0j)==>False
10) bool("True")==>True
11) bool("False")==>True
12) bool("")==>False

5.str():

We can use this method to convert other type

values to str typeEg:

1) >>> str(10)
2) '10'
3) >>> str(10.5)
4) '10.5'
5) >>> str(10+5j)
6) '(10+5j)'
7) >>> str(True)
8) 'True'

Implicit Conversion
Implicit conversion, also known as coercion, happens when data type
conversion is done automatically by Python and is not instructed by the
programmer.

Program to show implicit conversion from int to float.


#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

DEBUGGING
A programmer can make mistakes while writing a program, and hence, the
program may not execute or may generate wrong output. The process of
identifying and removing such mistakes, also known as bugs or errors, from
a program is called debugging. Errors occurring in programs can be
categorised as:

i) Syntax errors
ii) Logical errors
iii) Runtime errors

Syntax errors
Python has its own rules that determine its syntax. The interpreter
interprets the statements only if it is syntactically (as per the rules of Python)
correct. If any syntax error is present, the interpreter shows error
message(s) and stops the execution there. Such errors need to be removed
before the execution of the program.
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. Since the program interprets successfully
even when logical errors are present in it, it is sometimes difficult to identify
these errors. The only evidence to the existence of logical errors is the wrong
output. While working backwards from the output of the program, one can
identify what went wrong. Logical errors are also called semantic errors as
they occur when the meaning of the program (its semantics) is not correct.

Runtime Error
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.
Accepting data as input from the console
and displaying output

Reading dynamic input from the keyboard:

In Python 2 the following 2 functions are available to read


dynamic input from the keyboard.

1. raw_input()
2. input()

1. raw_input():

This function always reads the data from the keyboard in the form of
String Format. We have to convert that string type to our required type
by using the corresponding type casting methods.

Eg:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type

2. input():

input() function can be used to read data directly in our required


format.We are notrequired to perform type casting.

x=input("Enter Value)
type(x)

***Note: But in Python 3 we have only input() method and raw_input()


method is not available.
Python3 input() function behaviour exactly same as raw_input()
method of Python2. i.e. every input value is treated as str type only.

raw_input() function of Python 2 is renamed as input() function in


Python3
How to read multiple values from the keyboard in a single line:

1) a,b= [int(x) for x in input("Enter 2 numbers :").split()]


2) print("Product is :", a*b)
3)
4) D:\Python_classes>py test.py
5) Enter 2 numbers :10 20
6) Product is : 200

Note: split() function can take space as separator by default. But


we can pass anything as separator.

eval Function take a String and evaluate the Result.

Eg: x = eval(“10+20+30”)
print(x)

Output: 60

Command Line Arguments


• argv is not Array it is a List. It is available sys Module.
• The Argument which are passing at the time of execution are called
Command LineArguments.

Eg: D:\Python_classes py test.py 10 20 30

Command Line Arguments

Within the Python Program this Command Line Arguments are available in argv.
Which ispresent in SYS Module.

test.py 10 20 30

Note: argv[0] represents Name of Program. But not first Command Line
Argument.argv[1] represent First Command Line Argument.

Program: To check type of argv from

sysimport argv
print(type(argv))
D:\Python_classes\py test.py

output statements:
We can use print() function to display output.

Form-1: print() without any


argumentJust it prints new line
character

Form-2:
1) print(String):
2) print("Hello World")
3) We can use escape characters also
4) print("Hello \n World")
5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
7) print(10*"Hello")
8) print("Hello"*10)
9) We can use + operator also
10) print("Hello"+"World")

You might also like