PROGRAMMING WITH PYTHON
UNIT-I :: INTRODUCTION TO PYTHON
Introduction
History
Features
Applications
First Python Program
Variables
Data Types
Numbers
Operators and I/O Statements
PROGRAMMING WITH PYTHON
UNIT-I CONTROL STATEMENTS
Control Statements
Conditional Statements
Indentation
Looping Statements
The else suite
Break
Continue
Pass
Assert
Return
UNIT-1 INTRODUCTION TO PYTHON
What is Python ?
Python is an general purpose , interpreted, object-oriented,
high-level programming language with dynamic semantics.
It was created by Guido van Rossum in 1991 and further
developed by the Python Software Foundation.
It was designed with an emphasis on code readability, and its
syntax allows programmers to express their concepts in fewer
lines of code.
UNIT-1 INTRODUCTION TO PYTHON
Why Python ?
Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can
be executed as soon as it is written.
Python can be treated in a procedural way, an object-oriented
way or a functional way.
UNIT-1 INTRODUCTION TO PYTHON
Why Python ?
Python supports modules and packages.
Python provides a huge collection of standard
library
UNIT-1 INTRODUCTION TO PYTHON
Python Syntax compared to other programming
languages
Python was designed for readability, and has some similarities
to the English language with influence from mathematics.
Python uses new lines to complete a command, as opposed to
other programming languages which often use semicolons or
parentheses.
Python relies on indentation, using whitespace, to define
scope; such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this
purpose.
UNIT-1 INTRODUCTION TO PYTHON
History of Python
Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by
Guido Van Rossum at CWI in Netherland.
In February 1991, Guido Van Rossum published the code (labeled
version 0.9.0) to alt.sources.
In 1994, Python 1.0 was released with new features like lambda,
map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage
collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw of the
language.
UNIT-1 INTRODUCTION TO PYTHON
History of Python
ABC programming language is said to be the
predecessor of Python language, which was capable of
Exception Handling and interfacing with the Amoeba
Operating System.
The following programming languages influence
Python:
ABC language.
Modula-3
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
High Level Language
Object Oriented Language
Scalable
Extensible
Portable
Easy to Read, Learn and Maintain
Interpreted Language
Free and Open Source
Large Standard Library
Dynamically Typed Language
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
High Level Language
Python is a high-level language. When we write programs in
python, we do not need to remember the system architecture,
nor do we need to manage the memory. It is easy to
understand ,
Object Oriented Language
One of the key features of python is Object-Oriented
programming. OOP allows for associating specific behaviors,
characteristics, and/or capabilities with the data that they
execute on.
It is actually a pleasant mix of multiple programming
paradigms.
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
Scalable
Python provides basic building blocks on which you can build
an application, and as those needs expand and grow, Python's
pluggable and modular architecture allows your project to
flourish as well as maintain manageability
Extensible
Python is a Extensible language. We can write us some Python
code into C or C++ language and also we can compile that
code in C/C++ language.
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
Portable
Python language is also a portable language. For example, if
we have python code for windows and if we want to run this
code on other platforms such as Linux, Unix, and Mac then we
do not need to change it, we can run this code on any platform.
Easy to Read, Learn and Maintain
Python is extremely easy to learn.
Python has relatively few keywords, simple structure, and a
clearly defined syntax
The indentation used instead of curly braces in Python makes
it very easy to read Python code
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
Intrepreted Language
Python is an Interpreted Language because Python code is
executed line by line at a time. The source code of python is
converted into an immediate form called bytecode
Free and Open Source
Python is an open-source programming language and one can
download it for free
UNIT-1 INTRODUCTION TO PYTHON
Features of Python
Large Standard Library
Python has a large standard library which provides a rich set
of module and functions. There are many libraries present in
python for such as regular expressions, unit-testing, web
browsers, etc
Dynamically Type Language
Python is a dynamically-typed language. That means the type
(for example- int, double, long, etc.) for a variable is decided
at run time not in advance because of this feature we don’t
need to specify the type of variable.
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Python is used in many application domains.
Web and Internet Development
Scientific and Numeric
Desktop GUIs
Software Development
Business Applications
Image Processing Application
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Web and Internet Development
Python is used to develop web applications.
It provides libraries to handle internet protocols such as HTML
and XML, JSON, Email processing, request….
One of Python web-framework named Django is used on
Instagram.
Python provides many useful frameworks, and these are given
below:
Django and Pyramid framework(Use for heavy applications)
Flask and Bottle (Micro-framework)
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Scientific and Numeric
Python is widely used in scientific and numeric computing:
It consists of many scientific and mathematical libraries, which
makes easy to solve complex calculations.
SciPy,
Pandas,
NumPy,
Scikit-learn
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Desktop GUIs
Python provides a Tk GUI library to develop a user interface.
Some popular GUI libraries are given below.
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Software Development
Python is often used as a support language for
software developers, for build control and
management, testing, and in many other ways.
SCons for build control.
Buildbot and Apache Gump for automated
continuous compilation and testing.
Roundup or Trac for bug tracking and project
management.
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Business Applications
Python is also used to build ERP and e-commerce
systems:
Odoo is an all-in-one management software that offers
a range of business applications that form a complete
suite of enterprise management applications.
Tryton is a three-tier high-level general purpose
application platform.
UNIT-1 INTRODUCTION TO PYTHON
Applications of Python
Image Process Applications
Python contains many libraries that are used to work with the
image. The image can be manipulated according to our
requirements. Some libraries of image processing are given
below.
OpenCV
Pillow
SimpleITK
UNIT-1 INTRODUCTION TO PYTHON
1. Select Version of Python to Install
2. Download Python Executable Installer
[ Visit https://www.python.org/downloads/, select the
version of python to be installed]
3.Run the Python Executable Installer
----Select Install Now ,Install Launcher for all users and
Select Add Python 3.x version to PATH
4. Installation completes ,close the window.
WRITING FIRST PYTHON PROGRAM
Open Notepad
Type the following python statement
print(“Hello World”)
save the file as file_name.py
Open command line prompt
Execute the above file by typing the command
D:>python file_name.py
UNIT-1 INTRODUCTION TO PYTHON
Variables
A variable is a name given to a memory location.
It is the basic unit of storage in a program.
The value stored in a variable can be changed during program
execution.
Python is not “statically typed”.
We do not need to declare variables before using them or
declare their type.
A variable is created the moment we first assign a value to it.
UNIT-1 INTRODUCTION TO PYTHON
Rules for Naming Variables in Python
A variable name must start with a letter or the
underscore character.
Ex: age, first_name, _color
A variable name cannot start with a number.
Invalid variable names Ex: 1age, 1sum, 9_score
UNIT-1 INTRODUCTION TO PYTHON
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ ).
Variable names are case-sensitive (name, Name and
NAME are three different variables).
The reserved words(keywords) cannot be used naming
the variable
UNIT-1 INTRODUCTION TO PYTHON
Declaring the variable
variable_name=value
Ex: number = 30
name = “John”
Re-Declaring the variable
a=40
print(a)
a=78
print(a)
UNIT-1 INTRODUCTION TO PYTHON
Variable Declaration
Assigning a single value to multiple variables
ex: a=b=c=30
Assigning different values to multiple variables
ex: a,b,c=35,56,78
Local Variables
Global Variables
UNIT-1 INTRODUCTION TO PYTHON
DATA TYPES IN PYTHON
Data types are the classification or categorization of data
items.
It represents the kind of value that tells what operations
can be performed on a particular data.
Since everything is an object in Python programming, data
types are actually classes and variables are instance
(object) of these classes.
UNIT-1 INTRODUCTION TO PYTHON
DATA TYPES IN PYTHON
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
UNIT-1 INTRODUCTION TO PYTHON
UNIT-1 INTRODUCTION TO PYTHON
Numeric Data Type
It represents the data which has numeric value. Numeric
value can be integer, floating number or even complex
numbers.
These values are defined as int, float and complex class
in Python.
UNIT-1 INTRODUCTION TO PYTHON
Numeric Data Type
Integers – This value is represented by int class. It contains
positive or negative whole numbers (without fraction or
decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real
number with floating point representation. It is specified by a
decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify
scientific notation.
UNIT-1 INTRODUCTION TO PYTHON
Numeric Data Type
Complex Numbers – Complex number is represented by
complex class. It is specified as
(real part) + (imaginary part)j.
For example – 2+3j
UNIT-1 INTRODUCTION TO PYTHON
# Python program to demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
UNIT-1 INTRODUCTION TO PYTHON
Sequence Type
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
List
Tuple
UNIT-1 INTRODUCTION TO PYTHON
String type
The string can be defined as the sequence of characters
represented in the quotation marks.
In Python, we can use single, double, or triple quotes to define
a string.
The operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the
operation "Python" *2 returns 'Python Python'.
UNIT-1 INTRODUCTION TO PYTHON
Creating Strings
Single Quote String
String1=‘String type in Python’
Double quote string
String2=“String type in Python”
TripleQuote String
String3=‘ ‘ ‘ String in triple quotes ’ ’ ’
s = '''''A multiline
string'''
DATA TYPES IN PYTHON
str1 = 'hello javatpoint‘ #string str1
str2 = ' how are you' #string str2
print (str1[0:2])
#printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and
str2
DATA TYPES IN PYTHON
LIST
Python Lists can contain data of different types.
The items stored in the list are separated with a comma (,) and
enclosed within square brackets [].
Elements of list are accessed using index operator ‘[ ]’.
We can use slice [:] operators to access the data of the list.
The concatenation operator (+) and repetition operator (*)
works with the list in the same way as they were working
with the strings.
DATA TYPES IN PYTHON
Creating an Empty List
list = [ ]
print(list)
Creating a List
list1=[1,’”hi”,”python”,2]
print(list1)
Multidimensional List
list2=[[‘red’,’blue’],25,56]
DATA TYPES IN PYTHON
Accessing Elements of List
list1=[1,’”hi”,”python”,2]
print(list1[1])
print(list1[0:2])—accesses first 2 elements
print(list1[-1])– accesses the last element of the list
In Python, negative sequence indexes represent positions
from the end of the array
DATA TYPES IN PYTHON
TUPLE
A tuple is similar to the list in many ways.
Tuples also contain the collection of the items of
different data types.
The items of the tuple are separated with a comma (,)
and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify
the size and value of the items of a tuple.
DATA TYPES IN PYTHON
TUPLE
creating an empty tuple
tuple1=( )
print(tuple1)
creating a tuple
t1=(‘science’,’social’)
print(t1)
creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
DATA TYPES IN PYTHON
TUPLE
creating a tuple with built in function tuple()
t2=tuple(‘science’,’social’,’english’)
print(t2)
Operations on tuple
tup = ("hi", "Python", 2)
print (tup[1:])
print (tup[0:1])
print (tup + tup)
print (tup * 3)
t[2] = "hi"
DATA TYPES IN PYTHON
BOOLEAN
Boolean type provides two built-in values, True and False.
It denotes by the class bool.
True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F‘
Example:
print(type(True))
print(type(False))
print(type(true))
Output: <class 'bool'>
<class 'bool'>
NameError: name 'true' is not defined
DATA TYPES IN PYTHON
SET
Python Set is the unordered collection of the data type.
It is iterable, mutable(can modify after creation), and
has unique elements.
In set, the order of the elements is undefined;
Sets can be created by using the built-in set()
function with an iterable object or
a sequence by placing the sequence inside curly
braces, separated by ‘comma’.
Various mixed-up data type values can also be passed
to the set.
DATA TYPES IN PYTHON
set1 = set()
print("Initial blank Set: ")
print(set1)
set2 = {'James', 2, 3,'Python'}
set2.add(10)
set2.remove(2)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print(set1)
DATA TYPES IN PYTHON
Set using String
set1 = set(“HelloWorld") /// string
Set using List
set1 = set([”Hello", ”World", ”Python"])
DATA TYPES IN PYTHON
Dictionary
Dictionary in Python is an unordered collection of data values ,
used to store data values like a map.
Each data element in dictionary is a key: value pair
Each key-value pair in a Dictionary is separated by a colon : and
each data element is separated by a ‘comma’.
Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable.
DATA TYPES IN PYTHON
# Creating an empty Dictionary
Dict = { }
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary with Integer Keys
Dict = {1: ‘Eng', 2: ‘Maths', 3: ‘Social'}
print("Dictionary with use of Integer Keys: ")
print(Dict)
DATA TYPES IN PYTHON
# Creating a Dictionary with Mixed keys
Dict = {'Name': ‘Java', 1: [1, 2, 3, 4]}
print(“Dictionary with use of Mixed Keys: ")
print(Dict)
Creating a Dictionary with dict() method
Dict = dict({1: ‘Java', 2: ‘C', 3:’Python'})
print("Dictionary with the use of dict(): ")
print(Dict)
DATA TYPES IN PYTHON
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, ‘Welcome'), (2, ‘To')])
print(“Dictionary with each item as a pair: ")
print(Dict)
Accessing the elements of dictionary
colors={ 1:’red’,2:’green’, ‘colornew’:’magenta’}
print(colors[1]) by key
print(colors[‘colornew’])
colors.get(2)
print(colors.keys())
print(colors.values())
UNIT-1 INTRODUCTION TO PYTHON
NUMBERS
Numbers provide literal or scalar storage and direct access.
A number is also an immutable type, meaning that changing
or updating its value results in a newly allocated object.
Python has several numeric types:
• "plain" integers,
• long integers,
• Boolean,
• double-precision floating point real numbers,
• decimal floating point numbers, and
• complex numbers.
UNIT-1 INTRODUCTION TO PYTHON
NUMBERS
Create and Assign Numbers (Number Objects)
Creating numbers is as simple as assigning a value to a
variable:
anInt = 1 anInt=25
aLong = -999999999999L
aFloat = 3.1415926535897932384626433
aComplex = 1.23+4.56J
Updating Number
We can "update" an existing number by (re)assigning a
variable to another number.
UNIT-1 INTRODUCTION TO PYTHON
NUMBERS
In Python, variables act like pointers that point to boxes.
Every time you assign another number to a variable, we are
creating a new object and assigning it.
anInt += 1
aFloat = 2.71828
To delete a reference to a number object, use the del statement
del anInt
del aLong, aFloat, aComplex
UNIT-1 INTRODUCTION TO PYTHON
Integers
Boolean :
The Boolean type was introduced in Python 2.3.
Objects of this type have two possible values,
True and False.
Booleans are sub classed from integers but cannot themselves
be further derived
Python objects typically have a Boolean False value for any
numeric zero or empty set.
If used in an arithmetic context, Boolean values True and False
will take on their numeric equivalents of 1 and 0
UNIT-1 INTRODUCTION TO PYTHON
Integers
Boolean :
Most of the standard library and built-in Boolean functions that
previously returned integers will now return Booleans
Ex: bool(1), returns True
bool(0), returns False
bool(‘1’),returns True
bool(‘0’), returns False
bool([]), retiurns False
UNIT-1 INTRODUCTION TO PYTHON
Using booleans Numerically
>>>foo=42
>>> bar=foo<100
>>> bar
True
>>> print bar +100
101
>>> print ‘%s’ % bar
True
>>> print ‘%d’ % bar
1
UNIT-1 INTRODUCTION TO PYTHON
Standard (plain) Integers
They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
Python integers are implemented as (signed) longs in C
Integers are normally represented in base 10 decimal format,
base 8 or base 16 representation.
Octal values have a "0" prefix, and hexadecimal values have
either "0x" or "0X" prefixes
Ex: 0101 84 -237 0x80 017 -680 -0X92
UNIT-1 INTRODUCTION TO PYTHON
Long Integers
Also called longs, they are integers of unlimited size, written
like integers and followed by an uppercase or lowercase L.
Values can be expressed in decimal, octal, or hexadecimal.
The following are examples of longs:
16384L
-0x4E8L
017L
-2147483648l
052144364L
UNIT-1 INTRODUCTION TO PYTHON
Double Precision Floating Point Numbers
Floats in Python are implemented as C doubles,
Also called floats, they represent real numbers and are
written with a decimal point dividing the integer and
fractional parts.
Floats may also be in scientific notation, with E or e
indicating the power of 10 (2.5e2 = 2.5 x 102 = 250)..
Here are some floating point values:
0.0, 1.6, -4.3e25
9.384e-23 , -2.172818 , float(12)
4.2E-10, 6.022e23 , -1.609E-1
UNIT-1 INTRODUCTION TO PYTHON
Complex Numbers
Complex numbers are made up of real and imaginary
parts
Syntax for a complex number: real + imag j
Both real and imaginary components are floating point
values
Imaginary part is suffixed with letter "J" lowercase (j) or
uppercase (J)
Ex:
64.375+1j , 4.23-8.5j , 0.23-8.55j
UNIT-1 INTRODUCTION TO PYTHON
Complex Numbers
num=34.56 + 76.23 j
Attribute Description
num.real Real component of complex number
num.imag Imaginary component of complex number
num.conjugate() Returns complex conjugate of num
UNIT-1 INTRODUCTION TO PYTHON
Type Conversions in Python
Python defines type conversion functions to directly convert
one data type to another .
There are two types of Type Conversion in Python:
Implicit Type Conversion---
In Implicit type conversion of data types in Python, the
Python interpreter automatically converts one data type to
another without any user involvement.
Ex: x=10 y=10.2
print(type(x)) print(type(y))
<class ‘int’> <class ‘float’>
UNIT-1 INTRODUCTION TO PYTHON
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is
manually changed by the user as per their requirement.
Various forms of explicit type conversion are
1. int(a, base): This function converts any data type to integer.
‘Base’ specifies the base in which string is if the data type is a
string.
Ex: a=“10010”
b=int(a,2)
c=int(a)
UNIT-1 INTRODUCTION TO PYTHON
2.float(): This function is used to convert any data type to
a floating-point number .
3. ord() : This function is used to convert a character to
integer.
4. hex() : This function is to convert integer to
hexadecimal string.
5. oct() : This function is to convert integer to octal
string.
UNIT-1 INTRODUCTION TO PYTHON
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 :”)
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ")
print (e)
UNIT-1 INTRODUCTION TO PYTHON
# printing character converting to integer
c = ord(s)
print (c)
# printing integer converting to hexadecimal string
c = hex(56)
print (c)
# printing integer converting to octal string
c = oct(56)
print (c)
UNIT-1 INTRODUCTION TO PYTHON
6.tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to
set.
8. list() : This function is used to convert any data type to
a list type.
UNIT-1 INTRODUCTION TO PYTHON
# initializing string
s = ‘java'
# printing string converting to tuple
c = tuple(s)
print (c)
# printing string converting to set
c = set(s)
print (c)
# printing string converting to list
c = list(s)
UNIT-1 INTRODUCTION TO PYTHON
9.dict() : This function is used to convert a tuple of order
(key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real
numbers to complex(real,imag) number.
12. chr(number): This function converts number to its
corresponding ASCII character.
# initializing integers
a=1
b=2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
# printing integer converting to complex number
c = complex(1,2)
print (c)
# printing integer converting to string
c = str(a)
print (c)
# printing tuple converting to expression dictionary
c = dict(tup)
print (c)
UNIT-1 INTRODUCTION TO PYTHON
OPERATORS
Operators in general are used to perform operations on
values and variables.
These are standard symbols used for the purpose of
logical and arithmetic operations.
UNIT-1 INTRODUCTION TO PYTHON
OPERATORS
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
UNIT-1 INTRODUCTION TO PYTHON
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations
like addition, subtraction, multiplication, and division.
UNIT-1 INTRODUCTION TO PYTHON
Assignment Operators
Assignment operators are used to assigning values to the
variables.
a+=b, a=a+b
a-=b, a=a-b
UNIT-1 INTRODUCTION TO PYTHON
UNIT-1 INTRODUCTION TO PYTHON
UNIT-1 INTRODUCTION TO PYTHON
Comparison Operators
Comparison operators are used to compare two values.
The result is always a boolean value – True or False.
== returns True if both the values are equal.
!= returns True if both the operands are not equal.
> returns True if the left operand is greater than the right
operand.
< returns True if the left operand is less than the right operand.
>= returns True if the left value is greater than or equal to the right
value.
<= returns True if the left value is less than or equal to the right
value.
UNIT-1 INTRODUCTION TO PYTHON
Logical Operators
There are three logical operators in Python
and- Returns True if both statements are true
ex :x < 5 and x < 10
or--- Returns True if one of the statements is true
ex : x < 5 or x < 4
not --Reverse the result, returns False if the result is true
ex : not(x < 5 and x < 10)
UNIT-1 INTRODUCTION TO PYTHON
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:
is Returns True if both variables are the same
object x is y
is not Returns True if both variables are not the same object x is
not y
UNIT-1 INTRODUCTION TO PYTHON
Membership Operators
Membership operators are used to checking the presence
of a value in a sequence. There are two membership
operators in Python.
in
not in
UNIT-1 INTRODUCTION TO PYTHON
Bitwise Operators
They are also called binary operators and they work on
integers only. The operand values are converted to binary
and then the operation is perform on every bit.
& -Bitwise AND operator
| - Bitwise OR operator
^ - Bitwise XOR operator
~ - Binary ones’ complement operator
<< - Binary left shift operator
>> - Binary right shift operator
UNIT-1 INTRODUCTION TO PYTHON
Input And Output
input()
Python input() function is used to get input from the user.
It prompts for the user input and reads a line. After reading
data, it converts it into a string and returns that.
Syntax : input(‘prompt’) ///python 3.0
raw_input() //// python 2
UNIT-1 INTRODUCTION TO PYTHON
Output
Print() function is used to output data to the standard
output device (screen)
Syntax:
print(*objects, sep=' ', end='\n', file=sys.stdout,
flush=False)
UNIT-1 INTRODUCTION TO PYTHON
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults
into a space character.
After all values are printed, end is printed. It defaults
into a new line.
The file is the object where the values are printed and its
default value is sys.stdout (screen).
UNIT-1 INTRODUCTION TO PYTHON
Examples
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
UNIT-1 INTRODUCTION TO PYTHON
Formatting string output
Two approaches for string formatting,
f-strings and str.format()
f-string syntax : By starting a string with f or F before opening
quotation marks or triple quotation marks.
In this string, we can write Python expressions between
{ and } that can refer to a variable or any literal value.
UNIT-1 INTRODUCTION TO PYTHON
Ex:
name=‘John’
print(f “hello {name} how are you”)
print(f“ Hello, {name}. In 50 years, you'll be {age + 50}.”)
UNIT-1 INTRODUCTION TO PYTHON
str.format()
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
print('I like {0} and {1}'.format('bread','butter'))
print('I like {1} and {0}'.format('bread','butter'))
print('Hello {name}, {greeting}‘
.format(greeting = 'Goodmorning', name = 'John'))
UNIT-1 INTRODUCTION TO PYTHON
Control Statements
Following are the conditional statements used in python:
a. if-statement
b. if-else statement
c. if-elif-else ladder
d. nested-if statements
e. shorthand if statement
f. shorthand if-else statement
UNIT-1 INTRODUCTION TO PYTHON
if statement
It is the most simple decision-making statement. It is
used to decide whether a certain statement or block of
statements will be executed or not based up on the
condition’s truth value.
Syntax:
if condition:
# Statements to execute
# if condition is true
UNIT-1 INTRODUCTION TO PYTHON
if statement
python uses indentation to identify a block. So the block
under an if statement will be identified as shown in the
below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
UNIT-1 INTRODUCTION TO PYTHON
Example of if-stmt
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
UNIT-1 INTRODUCTION TO PYTHON
If-else Statement
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
UNIT-1 INTRODUCTION TO PYTHON
Example of if-else
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
UNIT-1 INTRODUCTION TO PYTHON
nested-if
Nested if statements mean an if statement inside another
if statement.
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
UNIT-1 INTRODUCTION TO PYTHON
Nested-if example
i = 10
if (i == 10):
if (i < 15):
print("i is smaller than 15")
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
UNIT-1 INTRODUCTION TO PYTHON
if-elif-else ladder
The if statements are executed from the top down.
As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed,
and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else
statement will be executed.
UNIT-1 INTRODUCTION TO PYTHON
Syntax:
if (condition):
statement
elif (condition):
statement
..
else:
statement
UNIT-1 INTRODUCTION TO PYTHON
Control Statements
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
UNIT-1 INTRODUCTION TO PYTHON
Short Hand if statement
A single statement to be executed inside the if block can
be represented using shorthand notation. The statement
can be put on the same line as the if statement.
Syntax:
if condition: statement
i = 10
if i < 20: print("i is less than 15")
UNIT-1 INTRODUCTION TO PYTHON
Short Hand if-else statement
This can be used to write the if-else statements in a single line
where there is only one statement to be executed in both if
and else block.
Syntax:
stmnt_when_True if condition else stmnt_when_False
i = 10
print(True) if i < 15 else print(False)
UNIT-1 INTRODUCTION TO PYTHON
Loops
Python For loop is used for sequential traversal i.e. it is used
for iterating over an iterable like string, tuple, list, etc.
Syntax:
for var in iterable:
# statements
l = [“php", “c", “java"]
for i in l:
print(i)
Python for loop with else
Python allows us to use the else condition with for loops.
Note: The else block just after for/while is executed only
when the loop is NOT terminated by a break statement
Example:
for i in range(1, 4):
print(i)
else:
print("No Break\n")
UNIT-1 INTRODUCTION TO PYTHON
While loop
Python While Loop is used to execute a block of
statements repeatedly until a given condition is satisfied.
while expression:
statement(s)
Example:
Count = 0
while (count < 3):
count = count + 1
print(“count is“,count)
UNIT-1 INTRODUCTION TO PYTHON
While loop with else
When the condition becomes false, the statement
immediately after the loop is executed.
The else clause is only executed when your while
condition becomes false. If you break out of the loop, or
if an exception is raised, it won’t be executed.
i=0
while i < 4:
i += 1
print(i)
else:
print("No Break\n")
UNIT-1 INTRODUCTION TO PYTHON
Break statement
Break statement in Python is used to bring the control
out of the loop when some external condition is
triggered. Break statement is put inside the loop body
(generally after if condition).
Continue statement is a loop control statement that
forces to execute the next iteration of the loop while
skipping the rest of the code inside the loop for the
current iteration only
UNIT-1 INTRODUCTION TO PYTHON
Python pass Statement
The pass statement is a null statement.
The pass statement is generally used as a placeholder i.e.
when the user does not know what code to write.
Place pass where empty code is not allowed, like in
loops, function definitions, class definitions, or in if
statements.
Ex: def calcSalary:
pass
UNIT-1 INTRODUCTION TO PYTHON
Example-break statement
for val in "string":
if val == "i":
break
print(val)
print("The end")
Example-continue statement
for val in "string":
if val == "i":
continue
print(val)
print("The end")
UNIT-1 INTRODUCTION TO PYTHON
assert
Assertions in any programming language are the
debugging tools that help in the smooth flow of code.
Assertion is the boolean expression that checks if the
statement is True or False.
If the statement is true then it does nothing and continues
the execution, but if the statement is False then it stops
the execution of the program and throws an error.
UNIT-1 INTRODUCTION TO PYTHON
UNIT-1 INTRODUCTION TO PYTHON
assert Keyword in Python
This statement takes as input a boolean condition, which
when returns true doesn’t do anything and continues the
normal flow of execution, but if it is computed to be
false, then it raises an AssertionError along with the
optional message provided.
Syntax : assert condition, error_message
UNIT-1 INTRODUCTION TO PYTHON
Parameters :
condition : The boolean condition returning true or
false.
error_message : The optional argument to be printed in
console in case of AssertionError
Returns :
Returns AssertionError, in case the condition evaluates
to false along with the error message which when
provided.
UNIT-1 INTRODUCTION TO PYTHON
return
A return statement is used to end the execution of the
function call and “returns” the result to the caller.
The statements after the return statements are not executed.
If the return statement is without any expression, then the
special value None is returned.
UNIT-1 INTRODUCTION TO PYTHON
Return
Syntax :
def fun():
statements
..
return [expression]
UNIT-1 INTRODUCTION TO PYTHON
Returning Multiple Values
Using Object: Similar to C/C++ and Java, we can create a class to hold
multiple values and return an object of the class.
class Test:
msg=“welcome”
age=20
def fun():
return Test()
t = fun()
print(t.msg)
print(t.age)
UNIT-1 INTRODUCTION TO PYTHON
Returning Multiple Values
Using Tuple:
def fun():
str = “helloworld"
x = 20
return str, x;
str, x = fun() # Assign returned tuple
print(str)
print(x)
UNIT-1 INTRODUCTION TO PYTHON
Returning Multiple Values
Using List:
def fun():
str = “helloworld"
x = 20
return [str, x];
list = fun()
print(list)
Using Dictionary
def fun():
d = dict();
d['str'] = “hello world"
d['x'] = 20
return d
# Driver code to test above method
d = fun()
print(d)