Python Programming
Python
• Python is a general purpose, dynamic, high-level, and interpreted
programming language.
• It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-
level data structures.
• Used for:
• web development (server-side)
• software development
• mathematics
• system scripting
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify
files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.
Why Python?
• Python works on different platforms
• 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.
Python Syntax
• Python program can be executed by writing directly in the Command Line:
• >>> print("Hello, World!")
• O/P:- Hello, World!
• Run file through Command Line:
• >python [Link]
• Python Indentation:
• Python uses indentation to indicate a block of code.
• Use the same number of spaces in the same block of code, otherwise
Python gives an error:
if 5 > 2:
print("Fiveis greater than two!")
print("Fiveis greater than two!")
Python Variables
• Python variables do not need explicit declaration to reserve memory space.
• The declaration happens automatically when you assign a value to a
variable.
• Example:
counter=100
miles=1000.90
name=“John”
print(counter)
print(miles)
print(name)
Python Variables
• Multiple Assignments:
• a=b=c=1
• a,b,c = 1,2,"john“
• Data Types:
• Numbers
• String
• List
• Tuple
• Dictionary
Python Variables
• Numbers:
• var1 = 1
• var2 = 10
• del var1, var2
• int :- 10, 100
• long :- 0122L
• float :- 32.3+e18, -21.9
• complex :- 3.14j, -0.6545+0J
Python Variables
• Strings:
• str = 'Hello World!'
• print(str)
• print(str[0])
• print(str[2:5])
• print(str[2:])
• print(str + "TEST")
Python Variables
Lists:
• All the items belonging to a list can be of different data type.
• Values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0.
• list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
• tinylist = [123, 'john']
• print(list1)
• print(list1[0])
• print(list1[1:3])
• print(list1[2:])
• print(tinylist * 2) # Prints list two times
• print(list1 + tinylist)
Python Variables
Tuples:
• Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
• Tuples can be thought of as read-only lists.
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tinytuple = (123, 'john')
• print(tuple)
• print(tuple[0])
• print(tuple[1:3])
• print(tuple[2:])
• print(tinytuple * 2) # Prints the contents of the tuple twice
• print(tuple + tinytuple)
Python Variables
Dictionary:
• It consists of key-value pairs.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
• dict = {}
• dict['one'] = "This is one"
• dict[2] = "This is two"
• tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
• print(dict['one']) # Prints value for 'one' key
• print(dict[2]) # Prints value for 2 key
• print(tinydict) # Prints complete dictionary
• print([Link]()) # Prints all the keys
• print([Link]()) # Prints all the values
Operators
• Arithmetic:- +, -, *, /, %, ** (exponent)
• Comparison:- ==, != (or <>), >, <, >=, <=
• Assignment:- =, +=, -=, *=, /=, %=, **=
• Bitwise:- &, |, ~ (ones complement), ^ (XOR), <<, >>
• Logical:- and, or, not
• Membership:- in , not in
Decision Making
• if
• if else
• Nested if
• elif
• Example:-
var = 100
if ( var == 100 ) :
print (“Value of expression is 100”)
print (“Good bye!”)
Loops
• While loop:-
• Example:
count = 0
while (count < 9):
print (“The count is:", count)
count = count + 1
Loops
• For loop:-
• Example:
for letter in 'Python': # First Example
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print ('Current fruit :', fruit)
Loops
• Nested loop:-
• Example:
i=2
while i < 100:
j=2
while j <= i // j:
if not (i % j):
break
j=j+1
if j > i // j:
print(i, " is prime")
i=i+1
print("Good bye!")
Number Data Type
Type Conversion:
• int(x):- to convert x to a plain integer.
• long(x):- to convert x to a long integer.
• float(x):- to convert x to a floating-point number.
• complex(x):- to convert x to a complex number with real part x and
imaginary part zero.
• complex(x, y):- to convert x and y to a complex number with real part
x and imaginary part y
Number Data Type
• Mathematical Functions:
• Some examples:-
• abs(x)
• exp(x)
• max(x1, x2,...)
• min(x1, x2,...)
• sqrt(x)
• More functions, visit:-
[Link]
String Data Type
• Escape characters:
• \n, \t, \b (backspace), etc.
• String Operators:
• str = "Hello"
• str1 = " world"
• print(str*3)
• print(str+str1)
• print(str[4])
• print(str[2:4])
• print('w' in str) # prints false as w is not present in str
• print('wo' not in str1) # prints false as wo is present in str1.
• print("The string str : %s"%(str)) # prints the formatted string
using %s format specifier #print(f"The string str : {str}") or
print("The string str :", str)
String Data Type
• String Formatting Operators: • Example:
• Format Symbol Conversion
long_str = """this is a long string that is made up of
• %c character
several lines and characters such as
• %s string conversion via str()
prior to formatting TAB ( \t ) and they will show up that way when
• %i signed decimal integer displayed.
• %d signed decimal integer NEWLINEs within the string, whether explicitly
• %f floating point real number given like
• Example: this within the brackets [ \n ], or just a NEWLINE
• print ("My name is %s and weight is %d kg!" within
% ('ABC', 50)) the variable assignment will also show up.
• Triple Quotes:- """
• Allow strings to span multiple lines. Triple
quotes consists of three consecutive single
or double quotes.
String Data Type
• String Functions:
• [Link]
List Data Type
• Updating List:
• list = ['physics', 'chemistry', 1997, 2000];
• print (“Value at index 2 : “)
• print (list[2])
• list[2] = 2010;
• print (“New value at index 2 : “)
• print (list[2])
• del list[2]
List Data Type
• Basic List Operations:
• len([1, 2, 3])
• [1, 2, 3] + [4, 5, 6]
• ['Hi!'] * 4
• 3 in [1, 2, 3]
• for x in [1, 2, 3]: print x
• List Functions and Methods:
• [Link]
Tuple Data Type
• Updating Tuples:
• tup1 = (12, 34.56);
• tup2 = ('abc', 'xyz');
• tup3 = tup1 + tup2;
• print tup3;
• del tup1;
• Basic Tuple Operations:
• len((1, 2, 3))
• (1, 2, 3) + (4, 5, 6)
• ('Hi!',) * 4
• 3 in (1, 2, 3)
• for x in (1, 2, 3): print x
Tuple Data Type
• Built-in Tuple Functions:
• [Link]
Dictionary Data Type
• Updating Dictionary:
• dict = {'Name': 'Sara', 'Age': 10, 'Class': 'Third'}
• dict['Age'] = 8;
• dict['School'] = "DPS School";
• print "dict['Age']: ", dict['Age']
• print "dict['School']: ", dict['School’]
• del dict['Name'];
• del dict ;
Dictionary Data Type
• Properties of Dictionary Keys:
• More than one entry per key not allowed.
• Keys must be immutable.
• Built-in Dictionary Functions & Methods:
• [Link]
Functions
• Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
• Example:
def printme( str ):
"This prints a passed string into this "
print (str)
return
• Function call:
printme(“First call to user defined function!")
printme(“Second call to the same function")
Functions
• Pass by Value Vs Reference:
• All parameters (arguments) in the Python language are passed by reference.
• It means if you change what a parameter refers to within a function, the change also
reflects back in the calling function.
• Example:
def changelist( mylist ):
print("Change a passed list into this function")
fun_list = [1,2,3,4]
[Link](fun_list);
print("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changelist(mylist);
print ("Values outside the function: ", mylist)
Function Arguments
• Types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
• 1. Required arguments:
def printme(str):
"This prints a passed string into this function"
print(str)
printme("hello world")
Function Arguments
• 2. Keyword arguments:
def printinfo(name, age):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
printinfo(age=50, name="Anna")
Function Arguments
• 3. Default arguments:
def printinfo(name, age=35):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return
printinfo(age=50, name="Anna")
printinfo(name="Anna")
Function Arguments
• 4. Variable-length arguments:
• Syntax:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
Function Arguments
• 4. Variable-length arguments:
• Example:
def printinfo(arg1, *vartuple):
"This prints a variable passed arguments"
print("Output is: ")
print(arg1)
for var in vartuple:
print(var)
return
printinfo(10)
printinfo(70, 60, 50)
Function Arguments
• 4. Variable-length arguments:
• Example:
def my_function(formal_arg, *var_args_tuple):
"This function demonstrates the use of variable positional arguments"
print("Formal argument:", formal_arg)
for arg in var_args_tuple:
print("Variable argument:", arg)
return formal_arg + sum(var_args_tuple)
result = my_function(1, 2, 3, 4, 5)
print("Result:", result)
Input in python
Python provides us with two inbuilt functions to read the input from the keyboard.
1) input ( prompt ): input will be taken in string format. Type casting is required for numeric input.
2) raw_input ( prompt ) (used in version 2)
input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <class ‘str’>. It does not evaluate the expression it just returns the complete
statement as String.
Example 1 : inp = input(‘enter your name’)
print(‘Your name is ‘, inp)
Example 2: name = input("Enter your name: ") # String Input
age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input
print("The name is:", name)
print("The age is:", age)
print("The marks is:", marks)
Taking multiple Inputs in python
Example:
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of passed student : ", y)
print("Number of failed student : ", z)
print()
# taking four inputs at a time
a, b, c, d = input("Enter four values: ").split()
print("First number is {}, second number is {} third is {} and fourth is {}".format(a, b, c, d))
print()
Taking multiple Inputs in python
Example:
We can also take values and convert them into the list using the map() method along with
the split() method.
Example:
# Taking multiple inputs in a single line separated with whitespaces
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)