You are on page 1of 60

INTRODUTION TO PYTHON

Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands. It is derived from programming
languages such as ABC, Modula 3, small talk, Algol- 68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Characteristics of Python:
 Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte
code can be interpreted by the interpreter.
 Interactive
 Object Oriented Programming Language
 Easy & Simple
 Portable
 Scalable: Provides improved structure for supporting large programs.
 Integrated
 Expressive Language
There are two modes to use the python interpreter:

Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
usually three greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by
default three dots (...).

python interpreter uses to indicate that it is ready. The interactive mode is better when a programmer
deals with small pieces of code.

Script Mode : In this mode source code is stored in a file with the .py extension and use the interpreter
to execute the contents of the file. To execute the script by the interpreter, you have to tell the interpreter
the name of the file.
python program execution

Python uses both compiler and interpreter to generate the native code
Interpreter is simply a software which executes the source code line by line.
Compiler is a software which executes the source code as whole

the source code is translated to byte code , which is then run by the pvm(python virtual
machine) to form machine code

In python code is first complied that is compiler compiles your source code (the
statements in your file) into a format known as byte code.

Byte code is a:
•lower level,
•platform independent,
•efficient and Intermediate

 It is into byte code and this byte code can’t be understood by CPU. So we need actually
an interpreter called the python virtual machine. The python virtual machine executes the
byte codes.

So  source code gets converted to byte code, it is fed into PVM (Python Virtual Machine).
to execute the python program we use the following syntax

>> python filename.py

but even at the Python interactive prompt, your Python is compiled to bytecode, and then the
bytecode is executed.
Variable

Variable Names
Named location that refers to a value and whose value can be used and processed during program execution.
Variables in python do not have fixed locations. The location they refer to changes every time their values change.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

# An integer assignment age = 45                      


# A floating point salary = 1456.8             
# A string   name = "John"      
Assigning value        
a=10
b=20
Print (a+b) o/p 30
a= “Sjc”
b=“Autonomous”
Print(a+b)
Assigning a single value to multiple variables:

1. a = b = c = 10
2. a, b, c = 1, 21.2, “sjc”
print(a)
Print(b)
Print(c)
3. a= “Autonomous” Print(a) o/p Autonomous

4. a= 10
5. b= “sjc”
6. c=10.5
Print (a + b) o/p unsupported operand type for +: ‘int’ and ‘str”
Print ( a + c) o/p 20.2

  

  
If you want to know the type of variable, you can use type( ) function

Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>

If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448

You can delete single or multiple variables by using del statement. Example:
del x
del y, z
Python is a highly object oriented language. In fact, virtually every item of data in a Python program is an
object of a specific type or class.
N=300
When presented with the statement print(300), the interpreter does the following:
•Creates an integer object
•Gives it the value 300
•Displays it to the console

You can see that an integer object is created using the built-in type() function:
type (n) o/p (300) <class 'int’>

A Python variable is a symbolic name that is a reference or pointer to an object


Now consider the following statement:
m=n
Python does not create another object. It simply creates a new symbolic name or reference, m, which points to
the same object that n points to.

Multiple References to a Single Object


m = 400
Now Python creates a new integer object with the value 400, and m becomes a reference to it. Separate reference object is created

n = "foo" Now Python creates a string object with the value "foo" and makes n reference

Orphaned Object
There is no longer any reference to the integer object 300. It is orphaned, and there is no way to access it.

Object Identity
Every object that is created is given a number that uniquely identifies . The identity of an object is an integer, which is
guaranteed to be unique and constant for this object during its lifetime its identifying number becomes available and may be
used again

Id ( n) 60127840 , id (m) 60127480


Data Types in Python:
Python has Two data types –
1. Primitive Data Type (Numbers, String)
2. Collection Data Type (List, Tuple, Set, Dictionary)
Python supports four different numerical types −
int equivalent to C’s long int in 2.x but unlimited in 3.x.
long unlimited in 2.x and unavailable in 3.x.
float equivalent to C’s doubles.
complex (complex numbers) Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part

w = 1 # int
y = 2.8 # float
z = 1j # complex

Complex numbers are written with a "j" as the imaginary part.

x = 3+5j
y = 2+4j
z=x+y
print(z)
5+9j
z.real
5.0
z.imag
9.0
String: Sequence of characters represented in the quotation marks.

 Python allows for either pairs of single or double quotes. Example: 'hello' is the same as "hello" .
 Python does not have a character data type, a single character is simply a string with a length of 1.
 The python string store Unicode characters.
 Each character in a string has its own index.
 String is immutable data type means it can never change its value in place.

For example

mystring= “do not worry about my string”


mystring = ‘do not worry about my string’
mystring = "Don't worry about my string“
Basic Operators in Python:

Arithmetic Operators

Operator Example Meaning Result


+ (unary) +a Unary Positive a
In other words, it doesn’t really do anything. It mostly
exists for the sake of completeness, to
complement Unary Negation.

+ (binary) a+b Addition Sum of a and b


- (unary) -a Unary Negation Value equal to a but opposite in sign
- (binary) a-b Subtraction b subtracted from a
* a*b Multiplication Product of a and b
/ a/b Division Quotient when a is divided by b.
The result always has type float.

% a%b Modulo Remainder when a is divided by b


// a // b Floor Division (also called Integer Division) Quotient when a is divided by b, rounded to the next
smallest whole number

** a ** b Exponentiation a raised to the power of b


Relational Operator

OPERATOR EXAMPLE MEANING RESULT

== a == b Equal to True if the value of a is equal to the value of b


False otherwise

!= a != b Not equal to True if a is not equal to b


False otherwise

< a<b Less than True if a is less than b


False otherwise

<= a <= b Less than or equal to True if a is less than or equal to b
False otherwise

> a>b Greater than True if a is greater than b


False otherwise

>= a >= b Greater than or equal to True if a is greater than or equal to b
False otherwise
Logical Operators

Operator Example Meaning


not not x True if x is False
False if x is True
(Logically reverses the sense of x)

or x or y True if either x or y is True
False otherwise

and x and y True if both x and y are True


False otherwise

Augmented Assignment Standard Assignment


a += 5 is equivalent to a=a+5

a /= 10 is equivalent to a = a / 10
Bitwise operator

Operator Example Meaning Result


& a&b bitwise AND Each bit position in the result is the logical AND of the
bits in the corresponding position of the operands. (1 if
both are 1, otherwise 0.)

| a|b bitwise OR Each bit position in the result is the logical OR of the bits
in the corresponding position of the operands. (1 if either
is 1, otherwise 0.)

~ ~a bitwise negation Each bit position in the result is the logical negation of


the bit in the corresponding position of the operand.
(1 if 0, 0 if 1.)

^ a^b bitwise XOR (exclusive OR) Each bit position in the result is the logical XOR of the
bits in the corresponding position of the operands. (1 if
the bits in the operands are different, 0 if they are the
same.)

>> a >> n Shift right n places Each bit is shifted right n places.


<< a << n Shift left n places Each bit is shifted left n places.
Other Special operators:

There are some special type of operators like


a. Identity operators- is and is not are the identity operators both are used to check if two values are located on the
same part of the memory. Two variables that are equal does not imply that they are identical.
 is True if the operands are identical
 is not True if the operands are not identical
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming’

print(a1 is not b1)


print(a2 is b2)

Output:
False
True
Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
 in True if value is found in the sequence
 not in True if value is not found in the sequence
Example:

x = 'Digital India'
y = ‘3hjhgb7’

print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)

True
True
False
True
False
Boolean literals
A Boolean literal can have any of the two values: True or False.
x = (1 == True) y = (1 == False) a = True + 4 b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
o/p

x is True
y is False
a: 5
b: 10

Number System Prefix


Binary '0b' or '0B’
Octal '0o' or '0O’
Hexadecimal '0x' or '0X’

dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")

o/p

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
user_input = raw_input("Enter a variable name: ") in Python 2.x:

user_input = input("Enter a variable name: ") In Python 3.x:

Receive two input numbers and calculate their power

base = input("Enter a base: ")


exponent = input("Enter an exponent: ")
result = float(base) ** float(exponent)

Type conversion

int(2.3) o/p 2
int(-2.8) -2
float(5) 5.0
complex('3+5j’) (3+5j)
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'

When converting from float to integer, the number gets truncated (integer that is closer to zero).
i Reading a number from a user:
x= int (input(“Enter an integer number”))

OUTPUT using print( ) statement:

print(base,"to the power of",exponent,"=",result)

The return type of eval() function is automatically considered based on what argument is passed to the eval() function.

If the argument represents If you pass an argument as int, float, boolean, it will return the corresponding datatype only.
The eval() function is used as an alternate for typecasting.

input = input("Enter any number of your choice:")


print(input)
print(type(input))

Enter any number of your choice: 10 + 10


10 + 10
<class 'str'>
eval = eval(input("Enter any number of your choice"))
print(eval)
print(type(eval))

Enter any number of your choice: 10 + 10


20
<class 'int'>
Mathematical built in functions

1. ceil() :- This function returns the smallest integral value greater than the number. If
number is already integer, same number is returned.
2. floor() :- This function returns the greatest integral value smaller than the number. If
number is already integer, same number is returned.
3. fabs() :- This function returns the absolute value of the number.
4. factorial() :- This function returns the factorial of the number
5. pi :- This is an inbuilt constant that outputs the value of pi(3.141592).
6.exp(a) :- This function returns the value of e raised to the power a (e**a) .
7.log(a, b) :- This function returns the logarithmic value of a with base b
8.pow(a, b) :- This function is used to compute value of a raised to the power b (a**b).
9. sqrt() :- This function returns the square root of the number.
10. sin() :- This function returns the sine of value passed as argument.
11. cos() :- This function returns the cosine of value passed as argument.
12. trunc() : Returns the truncated integer value of x
 
Strings
Strings are defined either with a single quote or a double quotes.
The difference between the two is that using double quotes makes it easy to include apostrophes whereas these would terminate the string if using single quotes

mystring= “do not worry about my string”


Mystring = ‘do not worry about my string’

mystring = "Don't worry about my string“


mystring = ‘‘‘can be used like this "Don't worry about my string“ end here ’’’

These two operators  + and *  can be applied to strings as well.

1.+ Operator used for concatenates strings


2. * Operator creates multiple copies of a string.

s = 'SJC.’
s*4 O/P 'SJCSJCSJCSJC.' The multiplier operand  must be an integer. TE: it can be zero, negative or positive
4 * s O/P ‘ SJCSJCSJCSJC.’
S*-4 o/p null for negative and zero

3.  in Operator
Python also provides a membership operator that can be used with strings.
The in operator returns True if the first operand is contained within the second, and False otherwise:
s = 'foo s in 'That\'s food for you .' True
s in 'That\'s good for you.' False

4.  not in operator which does the opposite


'z' not in 'abc' True
'z' not in 'xyz' False
Function Description
chr() Converts an integer to a character chr(97)
'a'
ord() Converts a character to an integer ord('a')
97
len() Returns the length of a string s = 'I am a string.' len(s)
14
str() Returns a string representation of an object str(49.2)
'49.2'

String Indexing
String indexing in Python is zero-based:
The first character in the string has index 0, the next has index 1, and so on.
The index of the last character will be the length of the string minus one.
S= ‘foobar’
s[len(s)-1] 'r’
s[-2] ‘a’
len(s) 6
s[- len(s)] 'f'
String Slicing

string slicing that extracts substrings from a string.


If s is a string, an expression of the form s[m:n] returns the portion of s
starting with position m, and up to but not including position n:
will return a substring that is n - m characters in length, in this case, 5 - 2 = 3.
Negative indices can be used with slicing . -1

Note :If the first index in a slice is greater than or equal to the second index, Python returns
an empty string

s = 'foobar’

s[2:5] 'oba’
s[:4] 'foob’
s[0:4] 'foob’
s[2:] 'obar’
s[2:len(s)] 'obar’
s[:4] + s[4:] 'foobar’
s[:4] + s[4:] == s True
s = 'foobar’

s[-5:-2] 'oob'
t = s[:]
id(s) 59598496 Literally. It’s not a copy, it’s a reference to the original string
id(t) 59598496
s is t True

Similarly  1:6:2  specifies a slice

starting with the second character (index 1) and ending with the last character and again the stride value 2 causes every other
character to be skipped

n = 20 m=25
prod = n * m
Print ('The product of', n, 'and', m, 'is', prod) The product of 20 and 25 is 500
String Built in function

1. s.capitalize() returns a copy of s with the first character converted to uppercase and all other characters converted to
lowercase
2. s.swapcase() returns a copy of s with uppercase alphabetic characters converted to lowercase and vice versa
3. s.title() returns a copy of s in which the first letter of each word is converted to uppercase and remaining letters are
lowercase
4. s.upper() returns a copy of s with all alphabetic characters converted to uppercase
5. s.count(<sub>[, <start>[, <end>]]) Counts occurrences of a substring in the target string
6. s.endswith(<suffix>) returns True if s ends with the specified <suffix> and False otherwise
7. use .find() to see if a Python string contains a particular substring. s.find(<sub>) returns the lowest index in s where
substring <sub> is found:
8. use the  .startswith() method returns True if s starts with the specified <suffix> and False otherwise
9. s.isalnum() returns True if s is nonempty and all its characters are alphanumeric (either a letter or a number),
and False otherwise
10. s.lower() returns a copy of s with all alphabetic characters converted to lowercase
11. s.isalpha() returns True if s is nonempty and all its characters are alphabetic, and False otherwise
12. s.isdigit() returns True if s is nonempty and all its characters are numeric digits, and False otherwise
13. s.isidentifier() returns True if s is a valid Python identifier according to the language definition, and False otherwise
Python Collections (Arrays)

There are four collection data types in the Python programming language:
•List is a collection which is ordered and changeable. Allows duplicate members.
•Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
•Set is a collection which is unordered and unindexed. No duplicate members.
•Dictionary is a collection which is unordered, changeable and indexed. No duplicate member

List  : Items separated by commas are enclosed within brackets [ ] . The elements of a list can be same type , variable
type or complex type
Negative indexing  , positive indexing , Range of Indexes is possible
A list with a single object is sometimes referred to as a singleton list:
a = [5,10,15,20,25,30,35,40]
a = [21.42, 'spam', 3, 4, 'egg', False, 3.14159]

1. Negative indexing a[-1] o/p 3.14


2. Positive indexing a[1] o/p spam
3. Range of indexing a[2:5] o/p 3 4
4. value of a specific item can be changed as a[2]=“welcome”
5. Loop through the list
for x in a:
   print(a)
6. Length of list : print(len(a))
slice lists
my_list = ['p','r','o','g','r','a','m']
# elements 3rd to 5th print(my_list[2:5])
# elements beginning to 3th print(my_list[:-5])
# elements 6th to end print(my_list[5:])
# elements beginning to end print(my_list[:])

['o', 'g', 'r']


['p', 'r', 'o']
['a', 'm'
['p', 'r', 'o', 'g', 'r', 'a', ‘m’]

To change or add elements to a list

Lists are mutable, meaning their elements can be changed unlike string or tuple.


odd = [2, 4, 6, 8]
change odd[0] = 1 # Output: [1, 4, 6, 8]
odd[1:4] = [3, 5, 7] # Output: [1, 3, 5, 7]
odd.append(7)
odd.extend([9, 11, 13])
odd.insert(1,3) # Output: [1, 3, 9]
odd[2:2] = [5, 7] # Output: [1, 3, 5, 7, 9]
del odd[2]
delete multiple items del odd[1:3]
# delete entire list del my_list
Tuples
Tuples is an ordered collection of objects
Tuples are identical to lists in all respects, except for the following properties:
 Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
 Tuples are immutable, Lists are mutable
Creating on tuples
t = () print(t) # Output: ()
 1. Tuple having integers
t = (1, 2, 3)
 2. Tuple with mixed datatypes
t = (1, "Hello", 3.4)
 3.Nested tuple
t = ("mouse", [8, 4, 6], (1, 2, 3)) indexing is (0,[[1][0],[1][1],[1][2]],([2][0],[2][1],[2][2]))

4. t = (5) type(t) o/p <class 'int’> precedence operator ()


5. t = (1, 2) type(t) <class 'tuple’>
6. t = ("hello") print(type(t)) o/p <class 'str’>
7. Creating a tuple having one element
t = ("hello",) print(type(t)) o/p <class 'tuple'>
 
8. t = "hello", # Parentheses is optional
print(type(t)) # <class 'tuple'>
t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge’)

 Indexing
Note: index and slice tuples using square brackets, just as for strings and lists.

t[0] o/p 'foo’


t[-1] o/p 'corge’
t[1::2] ('bar', 'qux', 'corge’)

 Immutable

t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge’)


t[2] = 'Bark!' gives error message # tuples are immutable i.e element cannot be changed
t = ("mouse", [8, 4, 6], (1, 2, 3))
t[1][0] = 9 # Output: "mouse", [9, 4, 6], (1, 2, 3)

 Both + and * can used with tuples

 print(1,2,3)+(4,5,6) output (1,2,3,4,5,6)


print(("Repeat",) * 3) Output: ('Repeat', 'Repeat', 'Repeat’)

 deleting tuples
del t[2] error
del t
t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge’)

 slicing
# elements 2nd to 4th print(t[1:4]) # Output: ('bar', 'baz', 'gux')
# elements beginning to 2nd print(t[:-4]) 'foo', 'bar’
# elements 4th to end print(t[3:]) 'qux', 'quux', 'corge'
# elements beginning to end print(t[:])

 Tuple unpacking When we create a tuple, we normally


(a, b, c) = t
assign values to it. This is called
print(a)
print(b) "packing" a tuple:
print(c)

 Tuple Membership Test


t = ('a','p','p','l','e’,)
  1. In operation
print('a' in my_tuple) # Output: True
print('b' in my_tuple) # Output: False

2. Not in operation
print('g' not in my_tuple) # Output: True

3. Iterating Through a Tuple


  for name in ('John','Kate'):
print("Hello",name)
 
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are available.

count(x) Returns the number of items x


index(x) Returns the index of the first item that is equal to x

When to use tuple instead of a list?


 Execution is faster when manipulating a tuple than list. (This is probably not going to be noticeable when the list or tuple is small.)
 When we don’t want data to be modified using a tuple

Lists vs. Tuples


Unlike lists, tuples cannot be modified. You cannot add, remove, or replace an item within a tuple. Using a list may be
more appropriate if you intend to modify the values you want to store

This immutability could be helpful if you're writing a program and want to store data that shouldn't be changed. Possible
examples include:
• credit card information
• birthdate
• birth name
Sets
A set is an unordered collection of items.

 Every element is unique (no duplicates)


 they are mutable
 Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc
 we cannot access items using indexes like we do in lists..

A set is created using curly braces {}, separated by comma


using the built-in function set()
To create sets
s = {1, 2, 3}
S=set([1,2,3])
set of mixed datatypes
s = {1.0, "Hello", (1, 2, 3)}
print(s)
s = {1, 2, [3, 4]} here [3, 4] is a mutable list cannot be part of set // error
To initialize sets

a = {}
print(type(a)) # Output: <class 'dict’>

a = set()
print(type(a)) # Output: <class 'set'>
set operations
A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8}

A.union(B)
print(A | B) Output: {1, 2, 3, 4, 5, 6, 7, 8}

A.intersection(B)
print(A & B) Output: {4, 5}

A.difference(B)
print(A - B) output:{1,2,3}

 to modify sets element


s = {1,3}
 add an element
s.add(2) print(s) Output: {1, 2, 3}
 add multiple elements
s.update([2,3,4]) Output: {1, 2, 3, 4}
 add list to set
s.update([4,5], {1,6,8}) Output: {1, 2, 3, 4, 5, 6, 8}

 to remove elements output: {1, 2,3, 5,


6,8}
s.discard(4)
s.remove(4)
add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

discard() Removes an element from the set if it is a member. (Do nothing if the element
is not in set)
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data
Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to
make it more optimized.
Created by using {} separated by commas,

Value :- any datatype ,it can be repeated, Values can be a list or list within a list, numbers, etc.
Keys:- immutable type and unique, Keys will be a single element

More than one entry per key is not allowed ( no duplicate key is allowed)
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must
be immutable.
Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python
dictionaries.
Eg :- dict={1:`apple`, 2: `ball`} key of integer type
dict ={ `name`: `apple`, 1 : [2,4,5]} key of mixed type
Print (dict[name])
Print( dict.get(1))
Print(dict)
dict[2]=‘cat’ update the dictionary
Dict[2]=`welcome’ adding element with key 2 and value welcome
METHODS DESCRIPTION

copy() They copy() method returns a shallow copy of the dictionary.

clear() The clear() method removes all items from the dictionary.

Removes and returns an element from a dictionary having the


pop() given key.

Removes the arbitrary key-value pair from the dictionary and


popitem()
returns it as tuple.

get() It is a conventional method to access a value for a key.

dictionary_name.values() returns a list of all the values available in a given


Two dimensional sequence

a = [[1, 2, 3], [4, 5, 6]]


print(a[0]) [1, 2, 3]
print(a[1]) [4, 5, 6]
b = a[0]
print(b) [1, 2, 3]
[1, 7, 3]

print(a[0][2]) 3
a[0][1] = 7
print(a) [[1, 7, 3], [4, 5, 6]]
Conditional statement
Syntax of if
if testexpression:
statement

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

Syntax of if...else

if test expression:
statement
else:
statement

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Looping statement
Syntax of for Loop
for val in sequence:
statement
eg:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)

range() function
range(n): generates a set of whole numbers starting from 0 to (n-1).
eg: range(8) = [0, 1, 2, 3, 4, 5, 6, 7]

range(start, stop): generates a set of whole numbers starting from start to stop-1.


eg : range(5, 9) is equivalent to [5, 6, 7, 8]

range(start, stop, step_size) generates a set of whole number starting and ending with
increment or decrement
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

sum = 0
for val in range(1,10,2):
sum = sum+val
print("The sum is", sum)
Syntax of if...elif...else
if test expression:
statement
elif test expression:
statement
else:
statement
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("P ositive number")
else:
print("Negative number")
For loop with else block
for with optional ‘else’ block associated with the loop. The ‘else’ block executes only when the loop has completed all the iterations.
Eg:
for val in range(5):
print(val)
else:
print("The loop has completed execution")

while loop
while condition:
statement
eg:
while num < 10:
print(num)
num = num + 3
while loop with else block
while with optional ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after the loop finished execution

num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")
break statement
for num in [10, 99,16, 90, 88, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break

Continue Statement

for num in [20, 11, 9, 66, 4, 89, 44]:


# Skipping the iteration when number is even
if num%2 == 0:
continue
print(num)

pass statement
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
pass
else:
print(num) o/p 11,9, 89

 we want to declare a function in our code but we want to implement that function in future  
Function
function is a block of code that performs a specific task.

1. Code re-usability:
2. Improves Readability: By using functions for frequent tasks you make your code structured and readable..
3. Avoid redundancy: When you no longer repeat the same lines of code throughout the code and use functions in places of those, you actually avoiding the redundancy

Function declaration:
def function_name(function_parameters):
function_body
return

Calling the function


function_name(parameters)
OR
variable = function_name(parameters)

Types of functions
1. Built-in functions:
2. User defined functions: The functions which we create in our code are user-defined functions. The add() function that we have created in above examples is a user-defined function.
Types of user defined function in Python
There are three types of Python function arguments using which we can call a function.
1.Default Arguments
Sometimes we may want to use parameters in a function that takes default values in case the user doesn’t want to
provide a value for them.
For this, we can use default arguments which assumes a default value if a value is not supplied as an argument while
calling the function. In parameters list, we can give default values to one or more parameters.
An assignment operator ‘=’ is used to give a default value to an argument.

Default value argument


def add(num1, num2=10):
return num1 + num2

sum1 = add(100, 200)


sum2 = add(8)
Sum3=add(200)
print(sum1)
print(sum2)
Print(sum3)

if a value is provide it will overwrite the default value any number of argument in a function can have a default value
Keyword Arguments
In function, the values passed through arguments are assigned to parameters in order, by their position.
With Keyword arguments,
we can use the name of the parameter irrespective of its position while calling the function to supply the values. All the
keyword arguments must match one of the arguments accepted by the function.

def add(num1, num2):


return num1 + num2

sum1 = add(200, 300)


sum2 = add(8, 90)
print(sum1)
print(sum2)

Sum1=add(num2=300,num1=100)
Variable-length Arguments

Sometimes you may need more arguments to process function then you mentioned in the definition. If we don’t
know in advance about the arguments needed in function, we can use variable-length arguments also called
arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded
variable-length arguments and if we use two asterisks (**) before a variable like **var,  then all the positional
arguments from that point till the end are collected as a dictionary called ‘var’.

Arbitary argument
def add( *num):
for I in num:
print(I)
add(1,3,4)
add(4,5,6,7)

If we do not known in advance the no of argument that


Local Variables vs Global Variables
Here are some of the points to list out the difference between global and local variable

• Variables or parameters defined inside a function are called local variables as their scope is limited to the function
only. On the contrary, Global variables are defined outside of the function.
• Local variables can’t be used outside the function whereas a global variable can be used throughout the program
anywhere as per requirement.
• The lifetime of a local variable ends with the termination or the execution of a function, whereas the lifetime of a
global variable ends with the termination of the entire program.
• The variable defined inside a function can also be made global by using the global statement.

def function_name(args):
.............
global x #declaring global variable inside a function
.............
T
Global and local variables

x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
o/p
x inside: global
x outside: global

x= "global"
def foo():
x=x*2
print(x)
foo()
//the output shows an error because Python treats x as a local variable and x is also not defined inside foo().
x= "global"
def foo():
global x
x=x*2
print(x)
foo()
def foo():
y = "local"
foo()
print(y)

NameError: name 'y' is not defined

 Using Global and Local variables in the same code

x= "global "
def foo():
global x
y = "local“
x=x*2
print(x)
print(y)
foo()

Global variable and Local variable with same name


x=5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)

local x: 10
global x: 5
Call/Pass By Value:
In pass-by-value, the function receives a copy of the argument objects passed to it by the caller, stored in a new location
in memory.

Call By Reference:
In pass-by-reference, the function receives reference to the argument objects passed to it by the caller, both pointing to
the same memory location

In Python Neither of these two concepts are applicable, rather the values are sent to functions by means of object
reference.

Pass-by-object-reference:
In Python, (almost) everything is an object
if object is immutable(not modifiable) than the modified value is not available outside the function.
if object is mutable (modifiable) than modified value is available outside the function.

Mutable objects:
list, dict, set

Immutable objects:
int, float, complex, string, tuple
call by value

string = “ sjc"

def test(string):
      
    string = “Sjc Autonomous"
    print("Inside Function:", string)
      
test(string)
print("Outside Function:", string)

call by reference
    
def add_more(list):
    list.append(50)
    print("Inside Function", list)
  
# Driver's code
mylist = [10,20,30,40]
  
add_more(mylist)
print("Outside Function:", mylist)
A function is said to be a recursive if it calls itself.
For example, lets consider a function factorial() and in the body of factorial() there is a call to the factorial().

def factorial(num):
if num == 1:
return 1
else:
return (num * factorial(num - 1))
num = 5
print("Factorial of", num, "is: ", factorial(num))

Note: factorial(1) is a base case for which we already know the value of factorial. The base case is defined in
the body of function with this code:

factorial(5) returns 5 * factorial(5-1)


i.e. 5 * factorial(4)
|__5*4*factorial(3)
|__5*4*3*factorial(2)
|__5*4*3*2*factorial(1)
Print statement

Format

%s - String (or any object with a string representation, like numbers)


%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of
digits to the right of the dot.

name = "John“
print("%s Hello, !" % name)

age = 10
print("%s is %d years old." % (name, age))

print('I love {} for "{}!"'.format('sjc', '123'))

print('{0} and {1}'.format(123, 'sjc'))

print('{1} and {0}'.format('sjc',123))

You might also like