M1-Python Basic Concepts and Programming
M1-Python Basic Concepts and Programming
Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a script. By convention,
Python scripts have names that end with .py.
SOME FUNDAMENTALS
Whitespace is significant in Python. Where other
languages may use {} or (), Python uses indentation to
denote code blocks.
Comments:
• Single-line comments denoted by #.
• Multi-line comments begin and end with three ‘’’.
• Typically, multi-line comments are meant for
documentation.
• Comments should express information that cannot be
exp
PYTHON TYPING
Python is a strongly, dynamically typed language.
Strong Typing
Obviously, Python isn't performing static type checking, but
it does prevent mixing operations between mismatched types.
Explicit conversions are required in order to mix types.
Example: 2 + "four" not going to fly
Dynamic Typing
All type checking is done at runtime.
No need to declare a variable or give it a type before use.
* Numeric
int: equivalent to C's long int in 2.x but unlimited in 3.x.
float: equivalent to C's doubles.
long: unlimited in 2.x and unavailable in 3.x.
complex: complex numbers..
Supported operations include constructors (i.e. int(3)), arithmetic,
negation, modulus, absolute value, exponentiation, etc.
SEQUENCE DATA TYPES
There are seven sequence subtypes: strings, Unicode
strings, lists, tuples, bytearrays, buffers, and xrange objects.
All data types support arrays of objects but with varying
limitations.
The most commonly used sequence data types are strings,
lists, and tuples. The xrange data type finds common use in
the construction of enumeration-controlled loops. The
others are used less commonly.
range() – takes more memory as it keeps the entire lists of
elements in memory. xrange functionality is implemented
range() in 3.x
xrange() – takes less memory as it keeps only one element at
a time in memory. Exist only in 2.x
SEQUENCE TYPES: UNICODE STRINGS
Unicode strings can be used to store
and manipulate Unicode data.
As simple as creating a normal string (just put a 'u' on it!).
Use Unicode-Escape encoding for special
characters.
Also has a raw mode, use 'ur' as a prefix.
To translate to a regular string, use the
encode() method.
To translate from a regular string to
Unicode, use the unicode() function.
myunicodestr1 = u"Hi Class!"
myunicodestr2 =
"Hi\u0020Class!“
print myunicodestrl,
myunicodestr2
newunicode =u'\xe4\xf6\xfc'
print newunicode Output:
newstr = Hi Class! Hi Class!
newunicode.encode('utf-8') äöu
print newstr äöü
print unicode (newstr, 'utf-8') äöü
SEQUENCE TYPES: LISTS
Lists are an incredibly useful compound data type.
Output:
(42. 'apple', u'unicode apple, 5234656)
(42, 'apple', banana, 5234656)
(42, apple, banana', [[item1", item21, [item, tem
[42, [[item1", "item2] [item3, item4] apple banana)
SEQUENCE TYPES: STRINGS
Created by simply enclosing characters in either
single-or double-quotes.
It's enough to simply assign the string to a variable.
Strings are immutable.
There are a tremendous amount of built-in string-
methods (listed here)
mystring "Hi, I'm a string!“
List , Tuple, Set, Dictionary
T=[] t=() b=set(a) d={}
Variables, Expressions and Statements
A variable is a named place in the memory.
Stores data.
Data is used using the variable “name”.
An assignment statement creates new variables.
The type of it will be decided by the value assigned to it.
Values and types :
A value is basic things, like a letter or a number.
i.e, 1, 2, and 'Hello, World!'.
These values belong to different types:
2 is an integer,
'Hello, World!' is a string,
Cont.
Rules to follow when naming the variables.
Variable names can contain letters, numbers, and the underscore.
Variable names cannot contain spaces and other special characters.
Variable names cannot start with a number.
Case matters—for instance, temp and Temp are different.
Keywords cannot be used as a variable name.
Valid variable names are: Spam, eggs, spam23 ,_speed
Underscore character (_) can appear in a name. Ex:
my_first_variable .
As Python is case-sensitive, variable name sample is different
from SAMPLE .
invalid variable
>>> 76trombones = 'big parade‘ >>> more@ = 1000000
>>> class = 'Advanced'
Variables
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932
The type of a variable is the type of the value it refers to.
>>> type(message)
<type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
Python 2 has 31 keywords:
and global yield in for
del or break raise lambda
from with except continue try
not assert import finally
while else print is
as if class return
elif pass exec def
print("a","b","c","d",sep=";")
a;b;c;d
Expressions
combination of values, variables, and operators
legal expressions
print("A“)
>>> x=5 print("B")
>>> x+1 print("C", end=" ")
print("E")
6
O/P:
A
B
CE
Operators, Precedence and
Associativity
It represent computations like addition and multiplication.
The values the operator is applied to are called operands.
Relational or Comparison Operators:
Less than, Greater than etc, between two operands.
It return a Boolean value either True or False.
Assignment Operators:
Assignment operator =, is used for assigning values to
variables.
Logical Operators:
and, or, not are used for comparing or negating the logical values
And:
Ex1 :>>> x=5
>>> x>0 and x<10
True
Ex2: >>> x= -5
>>> x>0 and x<10
False
Or :
>>> n=2
>>>n%2==or n%3==0
True
Not:
>>> x=5
>>> x> 0 and x<10
True
>>> not x
False
Precedence and Associativity
(Order of operations)
Operators are special symbols that represent computations
like addition and multiplication.
The values the operator is applied to are called operands.
The operators +, -, *, / and ** perform addition,
subtraction, multiplication, division and exponentiation,
as in the following examples:
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
Order of operations:
PEMDAS easy to remember rules:
Parentheses have the highest precedence and can be
used to force an expression to evaluate in the order you
want
Exponentiation has the next highest precedence
Multiplication and Division have the same
precedence, which is higher than Addition and
Subtraction,
Operators with the same precedence are evaluated
from left to right (except exponentiation).
Data Types, Indentation,
Comments
Basic data types of Python are
Numbers
Boolean
Strings
list
tuple
dictionary
None
Number:
Integers, floating point numbers and complex numbers
They are defined as int, float and complex class in Python
Boolean
conditional statements
Boolean value is, either True or False
Strings
A sequence of one or more characters
Include letters, numbers, and other types of characters.
Multiline strings
denoted using triple quotes, ''' or " " “
>>> s = 'This is single quote string'
>>> s = "This is double quote string"
>>> s = '''This
is Multiline
string'''
Lists
All the items (elements) inside square brackets [ ]
Separated by commas
Tuple
An ordered collection of Python objects.
Immutable , can’t be modified after it’s created
we can represent tuples using parentheses ( )
Dictionary
An unordered collection of data values.
consists of key-value pair
Key-value is provided within the dictionary to form it
more optimized.
Each key-value pair is separated by a colon(:),whereas
each key’s separated by a ‘comma’.
Example: Dict1 = {1 : 'Hello' , 2 : 5.5, 3 : 'World' }
None
None is another special data type in Python.
None is frequently used to represent the absence of a value.
For example, >>> money = None
Indentation
Programs get structured through indentation
In Python it is a requirement and not a matter of style.
Any statements written under another statement with
the same indentation is interpreted to belong to the
same code block
Nested statements need to be indented further to the
right.
Comments
Ex1. #This is a single-line comment
Ex2. ''' This is a multiline
comment '''
Reading Input
Built-in function called input
Gets input from the keyboard
\n at the end of the prompt represents a newline
>>> inp = input()
Welcome to world of python
>>> print(inp)
Welcome to world of python
>>>x=input('Please enter some text:\n')
Please enter some text:
Roopa
>>> print(x)
Roopa
user to type an integer,
try to convert the return value to int using the int() function
>>> x=int(input('enter number\n'))
enter number
12
Print Output
Format operator
The following example uses “%d” to format an integer, “%g” to
format a floating point number, and “%s” to format a string:
camels = 42
'%d' % camels
'I have spotted %d camels.' % camels'I have spotted 42 camels.'
Format function : string formatting methods string formatting
methods
positional_argument :
It can be integers, floating point numeric constants, strings,
characters and even variables.
keyword_argument :
A variable storing some value, which is passed as parameter.
bugs = 'roaches'
count = 13
area = 'living room'
print(f'Debugging {bugs=} {count=} {area=}')
Positional argument :
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
print('{} and {}'.format('spam', 'eggs'))
Keyword argument:
print('This {food} is {adjective}.'.format(food='spam',
adjective='absolutely horrible'))
for i in "Hello":
print(i, end=‟\t‟)
Syntax of for loop with range( ) function:
for variable in range( start, end, steps):
statements to be repeated
for i in range(5):
print(i, end= “\t”) 01234
for i in range(3,0,-1):
print(i) 3
print('Blast off!!') 2
1
Blast off!!
Ex:
words=[“John”,”Sam”,”Sham”]
for w in words:
print(w) # for len of words print(len(w))
OR
for w in words.items:
print(w)
def add(a,b):
sum=0
sum=a+b
return sum
Function call
Function name
Arguments and parameters
Functions
A sequence of instructions intended to perform a
specific independent task is known as a function.
You can pass data to be processed, as parameters
to the function. Some functions can return data as a
result.
In Python, all functions are treated as objects, so it is
more flexible compared to other high- level languages.
In this section, we will discuss various types of built-in
functions, user-defined functions, applications/uses of
functions etc.
Ex:
def print_greeting():
print “Hello!”
print “How are you today?”
if __name__ == “__main__”
print (even_fib())
Function types
Built in functions
Commonly Used Modules
Math functions
Function Definition and
Calling the Function
Python facilitates programmer to define his/her own functions.
The function written once can be used wherever and whenever required.
The syntax of user-defined function would be:
def fname(arg_list):
statement_1
statement_2
……………
statement_n
return value
def myfun():
print("Hello everyone")
print("this is my own function")
Function calls
A function is a named sequence of instructions for performing a task.
Whenever we want to do that task, a function is called by its name
>>> type(33)
<class 'int'>
The return Statement and void Function
A function that performs some task, but do not return any value to the
calling function is known as void function
The function which returns some result to the calling function after
performing a task is known as fruitful function.
def addition(a,b): #function definition
sum=a + b
return sum
Output:
addition of 2 numbers:6
Conti.
Fruitful functions:
a functions returns a value.
Void functions:
a function that always returns None.
Types of arguments in function
Required arguments
Keyword arguments
Default arguments
Variable length arguments
Required arguments
Same and order
Example:
#example for required arguments
def display(num1,num2):
print(num1,num2)
display(100,200)
Keyword arguments
Oder or position is not required
Initialization done base of keywords
Example:
#expample for keyword arguement
def display(num1,num2):
print(num1,num2)
display(num2=10, num1=20)
Default arguments
Number of argument need not be same
Some of arguments will be consider as default
Example:
#example for default arguments
display(name="robert", course="BCA")
display(name="rishab")
Ex:
def print_message():
print(“Hi, how are you\n”)
print(“Have a nice day\n”)
def repeat_message():
print_message()
print_message()
repeat_message()
# Python code to demonstrate call by value
string = "Geeks"
def test(string):
string = "GeeksforGeeks"
print("Inside Function:", string)
# Driver's code
test(string)
print("Outside Function:", string)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
def swap(s1, s2):
tmp = s1
s1 = s2
s2 = tmp
return s1,s2
s1 = 1
s2 = 2
print(“Before Swap :”, s1,s2)
s1,s2=swap0(s1, s2)
print(“After Swap :”, s1,s2)
Default Parameters
parameters optional and use default values
If user does not want to provide values for some arg. This is done with the
help of default argument values
Parameters by appending to the parameter name in the function
definition the assignment operator ( = ) followed by the default
value.(Constant value)
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5)
Keyword Arguments
Some functions with many parameters
To specify only some of them, then you can give values for such parameters
by naming them.
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Global vs. Local variables
Local variables can be accessed only inside the function in which they are
declared.
Global variables can be accessed throughout the program body by all
functions.
Output :
Inside the function local total : 30
Outside the function global total : 0
*args and **kwargs, Command Line Arguments
pass a variable number of arguments to the calling function
*args -allows you to pass a non-keyworded variable length
tuple
**kwargs - you to pass keyworded, variable length dictionary
total(10,1,2,3,Jack=1123,John=2231,Inge=1560)
Cont.
Command Line Arguments
The sys module provides a global variable named argv
C:\Code>python sqrtcmdline.py 2 5
from sys import argv
for n in range(int(argv[1]), int(argv[2]) + 1):
print(n, sqrt(n))
Ex:
import sys
def cmdarg():
print("sys.argv print all the arguments at the command
line including file name", sys.argv)
print("len(sys.argv) prints the total number of command
line arguments including file name", len(sys.argv))
print("You can use for loop to traverse through sys.argv")
for arg in sys.argv:
print(arg)
cmdarg()
Assignment Questions
Define python? Write a short note on data types in
Python.
Explain the syntax of the conditional statements and
for loop with an example
Explain the fruitful and void functions? Give examples.
Create a python program for calculator application
using functions.
Define function. Explain the built-in functions and
commonly used functions
Differentiate between local and global variables with
suitable examples.
Encapsulation for data
public class UserMasterDTO
{
private Int32 _ USER_ID; Table : UserMaster
private String _ USER_NAME; Name Type
private Int32 _MENU_ID; USER_ID int
USER_NAME Varchar(50)
[DataMember] USER_ADDRESS Varchar(MAX)
public Int32 USER_ID
{
get { return _ USER_ID; }
set { _ USER_ID = value; }
}
[DataMember]
public String USER_NAME
{
get { return _ USER_NAME; }
set { _ USER_NAME = value; }
}
}
Access the data from user and
store same to database
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
UserMasterDTO objUserMasterDTO = new UserMasterDTO();
objUserMasterDTO.USER_NAME = txtUserName.Text;
objCountryMasterDTO.USER_Address= txtUserAddress.Text;
int intCountryID=new
UserMasterService().InsertUserMaster(objUserMasterDTO , "SampleDB");
}
catch
{
throw;
}
}
View data from database using
Objects
protected void btnView_Click(object sender, EventArgs e)
{
try
{
UserMasterDTO objUserMasterDTO = new UserMasterDTO();
objUserMasterDTO
=UserMasterService().GetUserMasterById(intUSERID, "SampleDB");
txtUserId.Text= objUserMasterDTO.USER_NAME;
txtUserName.Text= objUserMasterDTO.USER_NAME;
txtUserAddress.Text= objUserMasterDTO.USER_ADDRESS;
}
catch
{
throw;
}
}
View data from database using
Objects
protected void btnView_Click(object sender, EventArgs e)
{
try
{
List<UserMasterDTO> lstobjUserMasterDTO = new UserMasterDTO();
lstobjUserMasterDTO =UserMasterService().GetUserMasterById(intUSERID, "SampleDB");
foreach i in lstobjUserMasterDTO
{
lstobjUserMasterDTO[i].USER_NAME;
lstobjUserMasterDTO[i].USER_NAME;
lstobjUserMasterDTO[i].USER_NAME;
;
}
}
catch
{
throw;
}
}
Practice Program:
Develop a python program to calculate the area of square,
rectangle, and circle using function
Solution:
Example:
Input: shape name = "Rectangle"
length = 10
breadth = 15