You are on page 1of 66

UNIT – 4

INTRODUCTION TO PYTHON

FYBTECH Subject : Programming and Problem Solving


Unit-4 Contents
2

Introductions to Python

Python Basics: History, Features, Working with python, Character Set,


Variables in Python, Operators, Input and Output in Python. Built-in Data
Type- Numeric: int, float, complex, Text: String.
Control Structures: Conditional statement, Looping and Iteration, Range
Function.

Functions: In-built and user-defined functions, recursive Functions.


Introduction to Python
3

 Python is a general purpose programming language invented in the


Netherlands ,early 90’s by Guido van Rossum.
 Python was conceived in the late 1980s and its implementation was
started in December 1989.
 Guido van Rossum is fan of famous TV show Monty Python’s
Flying Circus.
 Named after Monty Python.
Introduction to Python

• Multi-purpose (Web, GUI, Scripting, etc.)


• Object Oriented
• Interpreted
• Strongly typed and Dynamically typed
• Focus on readability and productivity

4
Why was Python created

My original motivation for creating Python was the perceived need for
higher level language in the Amoeba (Operating System) project.
I realized that the development of system administration utilities in C
was taking too long. Moreover, doing these things in the Bourne shell
would not work for a variety of reasons.
So there was a need for a language that would bridge the gap between
C and the shell.
-Guido Van Rossum
Why Python

❑ Python is a general purpose, high level object oriented


language.
❑ It is an interpreted language.
❑ It is an open source and free language.
❑ It is a dynamic programming language.
Python Versions

• There are a many version of python started from 1994 current


date.
• “Python” or “CPython” is written in C/C++
- Version 2.7 came out in mid-2010
- Version 3.1.2 came out in early 2010
• “Jython” is written in Java for the JVM
• “IronPython” is written in C# for the .Net environment
• Python 1.0 released in 1994
• Python 2.0 released in 2000
• Python 3.0 released in 2008
• Python 2.7 is the recommended version
• 3.0 adoption will take a few years 7
Development Environments (IDE)

• IDE helps you program in Python by:


➢ colour coding to program/code
➢ debugging
➢ auto-indent

Different IDE’s:
• PyDev with Eclipse
• Komodo
• Emacs
• Vim
• TextMate
• Gedit
• Idle
• PIDA (Linux)
• NotePad++ (Windows)
8
• Pycharm
Web Frameworks

A collection of packages or modules that allow developers to


write Web applications or services.
• Django
• Flask
• Pylons
• TurboGears
• Zope
• Grok

9
Python Features

• No compiling or linking
• Rapid development cycle
• No type declarations
• Simpler, shorter, more flexible
• Automatic memory management
• Garbage collection
• High-level data types and operations

1
0
Python Features

• Fast development
• Object-oriented programming
• Code structuring and reuse, C++
• Embedding and extending in C
• Mixed language systems
• Classes, modules, exceptions,multithreading
• "programming-in-the-large" support

1
1
Uses of Python

• Shell tools
– system admin tools, command line programs
• Extension-language work
• Rapid prototyping and development
• Language-based modules
– instead of special-purpose parsers
• Graphical user interfaces
• Database access
• Distributed programming
• Internet scripting
13
Before writing a program…….

❑ Python is pre-installed on most Unix Systems, including Linux and


MacOS X.

❑ $ where is python

python: /usr/bin/python /usr/bin/python2.7 /etc/python /etc/python2.7


/usr/lib/python2.6 /usr/lib/python2.7 /usr/local/lib/python2.7
/usr/include/python2.6 /usr/include/python2.7 /usr/share/python
/usr/share/man/man1/python.1.gz
Programming basics
15

▪ Code or source code: The sequence of instructions in a program.


▪ Syntax: The set of legal structures and commands that can be used in a
particular programming language.
▪ Output: The messages printed to the user by a program.
▪ Console: The text box onto which output is printed.
◦ Some source code editors pop up the console as an external window, and
others contain their own console window.
Compiling and Interpreting
16

Many languages require to compile (translate) program into a form that the
machine understands.
compile execute
source code byte code output
Hello.java Hello.class

Python is instead directly interpreted into machine instructions.


interpret
source code output
Hello.py
Compiling and Interpreting
17

❑ Write Source code/Program and Compile the Program using Python Compiler
❑ Compiler Converts the Python Program into byte code.
❑ Computer can not understand Byte Code so convert it into Machine Code using
PVM.
❑ PVM uses an interpreter which understands the byte code and convert it into
machine code.
❑ Machine code instructions are then executed by the processor and result are
displayed.
Compiling and Interpreting
18
Python Editors
19

❑ Onlinegdb (Online)
❑ Jupyter

❑ Anaconda

❑ Python IDE
First Python Program

print ("Hello, World! ")


comp197@comp197:~/Desktop$ python ass.py

Hello world
Using variables
#Program #Output

i=5 $ python var.py


print(i) 5
i=i+1 6
print(i) This is a multi-line string.
s ="This is a multi-line string. This is the second line.
This is the second line. "
print(s)
Comments in Python

#!/usr/bin/python
# First comment
‘‘‘ First Comment ’’’
print "Hello, Python!"; # second comment
Indentation-Most Important

i=5
print('Value is ', i) # Error! Notice a single space at the
start of the line
print('I repeat, the value is ', i)
Using Expressions

#Program #Output

#!/usr/bin/python $ python expression.py


# Filename: expression.py Area is: 10
length = 5 Perimeter is: 14
breadth = 2
area = length * breadth
print('Area is:', area)
print('Perimeter is:', 2 * (length + breadth))
Math commands
• Python has useful commands for performing calculations.
• To use math commands, you must write the following at the top of your
Python program:
from math import *
Command name Description
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Character Set
26

 Character set is bunch of identifying elements in the programming


language.
 A character represents any letter, digit or any other symbol. Python
has the following character sets:
 Letters – A to Z, a to z ·
 Digits – 0 to 9 ·
 Special Symbols - + - * / etc. ·
 Whitespaces – Blank Space, tab, carriage return, newline.
 Other characters – Python can process all ASCII and Unicode
characters as part of data or literals.
Variables
variable: A named piece of memory that can store a value.
◦ Compute an expression's result,
◦ store that result into a variable,
◦ and use that variable later in the program.
assignment statement: Stores a value into a variable.
◦ Syntax: name = value
◦ Examples: x = 5 gpa = 3.14

x 5 gpa 3.14

◦ A variable that has been given a value can be used in expressions.


x + 4 is 9
Exercise: Evaluate the multiplication of three numbers for a given a, b,
and c.
Variable Rules

❑ Can contain letters, numbers, and underscores


❑ Must begin with a letter
❑ Cannot be one of the reserved Python keywords:
and, as, assert, break, class, continue, def, del, elif, else, except, exec,
finally, for, from, global, if, import, in, is, lambda, not, or, pass, print,
raise, return, try, while, with, yield
Variable types

#Program #Output

$ python types.py
pi = 3.1415926
message = "Hello, world" <type 'float'>
i = 2+2 <type 'str'>
<type 'int‘>
print (type(pi))
print (type(message))
print (type(i))
Variable types

#Program #Output

$ python types.py
print (1.0/2.0) 0.5
print (1/2)
0.5
print (float(1)/float(2))
print (int(3.1415926)) 0.5
print (str(3.1415926)) 3
print (bool(1)) 3.1415926
print (bool(0)) True
False

⚫ int(), float(), str(), and bool() convert to integer, floating point,


string, and boolean (True or False) types, respectively
print (display on console)

#Program #Output

$ python p1.py
print ("Hello, world!”)
age = 45 Hello, world!
print ("You have", 65 - age, "years You have 20 years until
until retirement”) retirement

print : Produces text output on the console.

Syntax:
print "Message"
print Expression
◦ Prints the given text message or expression value on the console, and moves the
cursor down to the next line.
print Item1, Item2, ..., ItemN
input (read)
#Program #Output
Example: $ python p1.py
age = input("How old are you? ")
i = raw_input("Enter a math expression: ") How old are you? 53
print ("Your age is", age ) Enter a math expression: 2+5
Your age is 53
print ("You have", 65 - age, "years until
retirement”) You have 12 years until retirement

a = input("Enter the number: ") Enter the number:123


print(type(a)) <class ‘str’>
print(a) 123
<class ‘int’>
a = int(a) 123
print(type(a))
print(a)
input : Reads a number from user input.
◦ You can assign (store) the result of input into a variable.
Exercise: Write a Python program to accept the marks of three subjects from
user and display its average.
Taking input in Python
33

 Often have a need to interact with users, either to get data or to provide
some sort of result. Most programs today use a dialog box as a way of
asking the user to provide some type of input. While Python provides us
with two inbuilt functions to read the input from the keyboard.

• input ( prompt )
• raw_input ( prompt )

 input ( ) : This function first takes the input from the user and then
evaluates the expression, which means Python automatically identifies
whether user entered a string or a number or list. If the input provided is
not correct then either syntax error or exception is raised by python.
Basic Operations

• Assignment:
size =40
a =b =c = 3
• Numbers
– integer, float
– complex numbers: 1j+3, abs(z)
• Strings
– 'hello world', 'it\'s hot’
– ""bye world””
String operations

• concatenate with + or neighbours


– word = 'Help' + x
– word = 'Help' 'a'
• subscripting of strings
–'Hello’[-2] 'l'
– slice: 'Hello'[1:2] 'e'
– word[-1] last character
– len(word) 5
– immutable: cannot assign to subscript
Numbers: Integers

• Integer – the equivalent of a C long


• Long Integer – an unbounded integer value.

>>> 132224
132224
>>> 132323 ** 2
17509376329L
>>>
Numbers: Floating Point

• int(x) converts x to an >>> 1.23232


integer 1.2323200000000001
• float(x) converts x to a >>> print 1.23232
floating point 1.23232
>>> 1.3E7
• The interpreter shows a lot
13000000.0
of digits
>>> int(2.0)
2
>>> float(2)
2.0
Numbers: Complex

• Built into Python


• Same operations are supported as integer and float

>>> x = 3 + 2j
>>> y = -1j
>>> x + y (3+1j)
>>> x * y (2-3j)
Numbers are immutable

x 4.5
>>> x = 4.5
>>> y = x y
>>> y += 3
x 4.5
>>> x
4.5 y 7.5
>>> y
7.5
String Literals

• Strings are immutable


• There is no char type like in C++ or Java
• + is overloaded to do concatenation

>>> x = 'hello'
>>> x = x + ' there'
>>> print(x)
'hello there'
String Literals: Many Kinds
• Can use single or double quotes, and three double quotes for a
multi-line string

>>> 'I am a string'


'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)‘
>>> print(s)
And me too!
though I am much longer
than the others :)‘
Substrings and Methods

•len(String) – returns the •str(object) – returns a String


number of characters in the representation of the object
String

>>> s = '012345'
>>> s[3] >>> len(s)
'3' 6
>>> s[1:4] >>> str(10.3)
'123' '10.3'
>>> s[2:]
'2345'
>>> s[:4]
'0123'
>>> s[-2]
'4'
42
String Formatting

❑ Similar to C programming language printf statement


❑ <formatted string> % <elements to insert>
❑ Can usually just use %s for everything, it will convert the object to its
String representation.
❑ %s is used to inject strings similarly %d for integers, %f for floating-
point values.

#Output

print("One, %d, three" % 2 ) One, 2, three


print("%d, two, %s" % (1,3)) 1, two, 3
print("%s two %s" % (1, 'three')) 1 two three
Do nothing

• pass does nothing


• syntactic filler Interpreter

while 1:

pass

def add():

pass # Pass statement

add(2,2)
Operators

• Arithmetic

Python has incorporated operators like +=,


but ++ (or --) do not work in Python 45
String Manipulation

46
Logical Comparison
Identity Comparison
Arithmetic Comparison
Control Structures: Conditional statement
50

 Python if Statement
 It will use to create decisions in a Python
program using different forms of if.
statement.

 Python if Statement Syntax


if test expression:
statement(s)
Example: Python if Statement
# If the number is positive, we print an appropriate message
51

#Program #Output

num = 3
3 is a positive number
if num > 0: This is always printed
print(num, "is a positive number.") This is also always printed.
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
Control Structures: Conditional statement
52

Python if...else Statement


Syntax of if...else
if test expression:
Body of if
else:
Body of else
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
53

#Program #Output

num = 3
Positive or Zero
# Try these two variations as well.
# num = -5
# num = 0

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
What is for loop in Python?
54

The for loop in Python is used to iterate over a


sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called
traversal.
Syntax of for Loop
for itarator_variable in sequence_name:
Statements . . .
Ex:
for val in sequence:
Body of for
Here, val is the variable that takes the value of the
item inside the sequence on each iteration i.e
keep tracks the individual item each iteration is
viewing and referring to each list, tuple, string
entry in sequence as the loop executes.
What is for loop in Python?
55

list1 = ['PPS', 'LADC', 'BEEE', 'MECH']


for name in list1:
print(name) # for each iteration print the value of list1
print(list1)

#Output
PPS
LADC
BEEE
MECH
['PPS', 'LADC', 'BEEE', 'MECH']

• name points to 'PPS' on the first iteration of the loop…


• …then 'LADC' on the second iteration of the loop…
• …and so on.
What is for loop in Python?
56

#Program #Output

p = 'PPS' P
for l in p: P
S
print(l)
0
1
for i in range(5): 2
print(i) 3
4
5

1
for i in range(1,5): 2
3
print(i)
4
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
57

#Program
#Output
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] The sum is: 48
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers: 6
sum = sum+val 5
print("The sum is: ", sum) 3
8
4
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] 2
for val in numbers: 5
print(val) 4
print(numbers)
11
[6, 5, 3, 8, 4, 2, 5, 4, 11]
The range() function
58

 We can generate a sequence of numbers using range() function.


range(10) will generate numbers from 0 to 9 (10 numbers)
 We can also define the start, stop and step size as range(start,
stop, step_size). step_size defaults to 1 if not provided.
 The range object is "lazy" in a sense because it doesn't generate
every number that it "contains" when create it.
 This function does not store all the values in memory; it would
be inefficient. So it remembers the start, stop, step size and
generates the next number on the go.
 To force this function to output all the items, we can use the
function list().
The range() function
59

#Output

 print(range(10))
range(0, 10)
 print(list(range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[2, 3, 4, 5, 6, 7]
 print(list(range(2, 8)))
[2, 5, 8, 11, 14, 17]
 print(list(range(2, 20, 3)))
What is while loop in Python?
60

 The while loop in Python is used to


iterate over a block of code as long as
the test expression (condition) is true.

 Generally use this loop when we don't


know the number of times to iterate
beforehand.

 Syntax of while Loop in Python


while test_expression:
Body of while
Example: Python while Loop
# Program to add natural
# numbers up to # sum = 1+2+3+...+n
61

#Program #Output

# To take input from the user Enter n: 10


n = int(input("Enter n: ")) The sum is 55
#n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Functions in Python
62

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• A function can return data as a result

Syntax:
#Function definition
def my_function():
print("Hello from a function")
my_function() #Function call
Example: Functions in Python
63

#Program #Output

def my_function(fname): EmilJohnson


print(fname +"Johnson") HarrisJohnson
NancyJohnson
#Function call
my_function("Emil")
my_function("Harris")
my_function("Nancy")

def my_function1(fname,lname):
Emil Johnson
print(fname + " " + lname)

#Function call
my_function1("Emil", "Johnson ")
Example: Functions in Python-Passing parameter
64

#Program #Output

def sum(a,b): Sum is: 100


c=a+b Sum is: 179

return(c)
#Function call inside print
print("Sum is: ",sum(90,10))

k=90
m=89
print("Sum is: ", sum(k,m))
Example : Functions in Python-Passing list
65

#Program #Output

def my_function(fruits): Fruits are:


for x in fruits: Apple
Banana
print(x) Cherry

fruits = ["Apple", "Banana", "Cherry"]


print("Fruits are:")
my_function(fruits) #function call
Example : Functions in Python-Recursion
66

#Program #Output

def factorial(n): Enter any number: 5


if n == 1: The factorial of 5 is 120
return n
else:
return n*factorial(n-1)
# taking input from the user
num = int(input("Enter any number: "))
if num < 0:
print("Factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is",
factorial(num)) #Function call

You might also like