0% found this document useful (0 votes)
2 views30 pages

Unit 2

The document covers fundamental concepts of Python, including variables, data types, and user-defined functions. It explains how to declare variables, the rules for naming them, and the various data types such as numbers, strings, lists, tuples, booleans, and dictionaries. Additionally, it discusses user-defined functions, including parameterized, recursive, and lambda functions, with examples for each type.

Uploaded by

vishparekh1509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Unit 2

The document covers fundamental concepts of Python, including variables, data types, and user-defined functions. It explains how to declare variables, the rules for naming them, and the various data types such as numbers, strings, lists, tuples, booleans, and dictionaries. Additionally, it discusses user-defined functions, including parameterized, recursive, and lambda functions, with examples for each type.

Uploaded by

vishparekh1509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Python Variables ,

Python Datatypes ,
User Defined Function
MRS. H H DESAI[NARANLALA COLLEGE ,NAVSARI ]
Python Variable
❑Variable is the name of memory location, where are can
stored different types of values.
❑Python has no command for declaring a variable.
❑A variable is created the moment you first assign a value to
it.

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Variable
❖Naming of variables:-
•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)
•A variable name cannot be any of the Python keywords.

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Variable
Example:- O/P:-
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Mrs. H H Desai [ Naranlala college, Navsari ]
Python Variable
Illegal Example:- O/P:-
2myvar = "John"
my-var = "John"
my var = "John"

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Variable
❖Assigning value to multiple variables:-
•In Python we can write multiple variables and values in a single line. Which is called multiple
assignment.
•Multiple assignments can be assigned in two ways.
1:- Assigning Single value to multiple variables
Example:-
>>>amit = sachin = sandeep = “red”
>>>print(amit)
>>>print(sachin)
>>>print(sandeep)

Output::- red Mrs. H H Desai [ Naranlala college, Navsari ]


Python Variable
❖Assigning value to multiple variables:-
2 :- Assigning Multiple value to multiple variables
Example:-
>>> name,age,salary="amit",20,20000.00
>>>print(name)
>>>print(age)
>>>print(salary)

Output::- amit
20
20000.00

Mrs. H H Desai [ Naranlala college, Navsari ]


Comments in Python
- Comments can be used to explain Python code.
- Comments can be used to make the code more readable.
- Comments can be used to prevent execution when testing code.
▪Creating comments:-
-Comments starts with a #, and python will ignore them:
Example:-1 Multiline Comments:-
#This is a comment
Print(“Hello, World!”)

Mrs. H H Desai [ Naranlala college, Navsari ]


Local and Global variable in Python
•Global variables are those variables which are accessible from anywhere, means, after
defining, they can be accessed anywhere in the entire script file or can be accessed even
inside a function.
•Example:-
a = 390 O/P:-
b = 90 Addition is: 480
def get_adition() :
print('Addition is :', a+b)
get_adition() Mrs. H H Desai [ Naranlala college, Navsari ]
Local and Global variable in Python
•Local Variables are those variables which are defined inside a code block (eg: function) and are
accessible only inside that function, but these variables will not be accessible outside that
function.
•Example:- O/P:-
def get_adition() :
def get_adition(): Addition is: 480
a = 390
b = 90
print('Addition is :', a+b)
get_adition()
Mrs. H H Desai [ Naranlala college, Navsari ]
Python Data Type:-
•There are different types of data types:
•Number
•String
•List
•Tuples
•Boolean
•Dictionaries
1. Number:- Number data type is also of three types.
1.Int data type
2.Float data type
3.Complex data type
Mrs. H H Desai [ Naranlala college, Navsari ]
Python Data Type:-
1. int data type:- int data type contains simple numeric values. This value is of
both negative and positive types.
Example:- O/P:-
a= 14582 positive int no . = 14582
print(“positive int no .= “, a)
b= -1345
print(“negative int no .= “, b) negative int no . = -1345

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Data Type:-
2. Float data type:- Float data type contains decimal values. This is also of both
negative and positive types.
Example:- O/P:-
a= 2525.5455 positive int no . = 2525.5455
print(“positive float no .= “, a)
b= -2165.13155
print(“negative float no .= “, b) negative int no . = -2165.13155

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Data Type:-
3. Complex data type:-
Example:- O/P:-
a= 3+5j Complex no = (3+5j)
print(“Complex no = “, a)

[Note: 3 = real part & 5j=imaginary part]

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Data Type:-
2. String:- Python string is a sequence of characters or text. It handles
textual data. The string is written inside single (‘ ‘) or double (“ “) quotes.
• Forward indexing of Python string starts from 0,1,2,3…… while
• Backward indexing starts from -1, -2, -3…….
Example:- O/P:-
a=“hi” hi
b=‘Hello Python’ Hello Python
Print(a)
Print(b)

Mrs. H H Desai [ Naranlala college, Navsari ]


Python Data Type:-
3. List:- Python list is an important data type of Python.
• Many values are kept in it. Each value is separated with comma (,).
• And all the values are kept inside a square bracket ([ ]).
Example:- O/P:-
List=[‘mca’,123,7.68] [‘mca’,123,7.68]
Print(List)
4. Tuples:- Tuples are also like lists which hold many different values, in this also each value is separated with comma (,). And
all the values are kept inside parentheses ( ).
• Cannot change the value of tuples.

Example:- O/P:-

tuple = (“python”, 25, 12.23 ,”a”) (‘python’, 25, 12.23, ‘a’)

print (tuple)
Mrs. H H Desai [ Naranlala college, Navsari ]
Python Data Type:-
5. Boolean:- Boolean is a common data type of all programming languages.
• Boolean returns two values.
• True
• False
Example:- O/P:-
a=(“learn python”) 12
len(a)
Example:- O/P:-
len(a)==12 True
Example:- O/P:-
len(a)!=12 False
◦ len() is a method. Which is used to find the length of the String.
Mrs. H H Desai [ Naranlala college, Navsari ]
Python Data Type:-
6. Dictionaries:- It contains pairs of key and value. Each key and its value are separated
with a colon (:) and the pair of key and value is separated with a comma (,). And all
the keys and values are kept inside curly braces { }.
Example:- O/P:-
dict={1:”H”, 5:”e”, 7:”l”, 8:”l”, 9:”o”} e
Print(dict[5]) o
Print(dict[9])

Mrs. H H Desai [ Naranlala college, Navsari ]


Type Conversion:-
•When that String data type has to be converted into Number (int, float, complex number),
then Type Conversion functions have to be used.
Example:- O/P:-
a = input("Enter Number : ")
print("Entered input's type is", a) Enter Number : 4
b = int(a) Entered input's type is 4
print("Entered input's type is", b) Entered input's type is 4
print("Entered input's type is", type(b))
Entered input's type is
c = float(a)
print("Entered input's type is", c) Entered input's type is 4.0
print("Entered input's type is", type(c)) Entered input's type is
d = complex(a) Entered input's type is (4+0j)
print("Entered input's type is", d) Entered input's type is
print("Entered input's type is", type(d))
Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• All the functions that are written by any of us come under the category of user-defined
functions. Below are the steps for writing user-defined functions in Python.
• In Python, a def keyword is used to declare user-defined functions.
• These are also of many types.
1. Parameterized Function
2. Recursive Function
3. Lambda Function
• SYNTAX:-
def function_name():
statements
….
Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• EXAMPLE:- O/P:-
Inside function
# Declaring a function
def fun():
print("Inside function")
# Driver's code
# Calling function
fun()

Mrs. H H Desai [ Naranlala college, Navsari ]


User Defined Function in Python:-
• Parameterized Function:- Parameterized functions are those functions which accept parameters, while defining these
functions we also define parameters which ensure how many arguments we are going to pass while calling.

• We can pass any number of parameters in the function as per our need. And these parameters work as a variable for that
function.

• SYNTAX:-

def function_name(param1,param2,…,paramN):
#function body
#what the function does goes here
#write some action
return something. #optional

Mrs. H H Desai [ Naranlala college, Navsari ]


User Defined Function in Python:-
• Example:-
def calculate(num1,num2):
return num1+num2
Print(‘Addition of 23 , 45655 is :’,calculate(23,45655))
#now pass different values.
Print(‘Addition of 234334 , 45655 is :’,calculate(234334 , 45655))
O/P:-
Addition of 23 , 45655 is : 45678
Addition of 234334 , 45655 is : 279989 Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• Function with Default Parameter:- In Python you can also set default parameters in
Functions,
• If the value of that parameter is passed then the passed value will be used otherwise the default
value will be used.
• Example:- O/P:-
def calculate(num1, num2=2) : #function definition 5 to the power 2 : 25
return pow(num1, num2) 5 to the power 5 : 3125
#pass only one value. 5 to the power 5 : 3125
print('5 to the power 2 :', calculate(5))
#now change values.
print('5 to the power 5 :', calculate(5, 5))
print('2 to the power 5 :', calculate(5, 5)) Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• Recursive Function:- Calling a function till a specified condition inside the same
function is called recursive function, and this process is called recursion.
• Use Of Recursive Function:-

- Recursive Functions are most used in tree structure (reading or creating tree structure), where
we do not know whether the node has any children or not, then call the function.

- Secondly, to read file directories, because we do not know whether there will be all the files
inside a directory or a sub directory, and then sub-directories inside it and then inside that etc..

- Recursive function can also be used for data sorting.


Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• Example:- •O/P:-
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
num = 0 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
def print_number(num) : 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
num += 1 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
print(num, end=',') 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,

if(num < 100) : - An example of a simple recursive function is given


above, in the example the same function is called
print_number(num) 100 times.

#call the function. - A condition is given that the function is called only
if the value of the variable is less than 100.
print_number(num)

Mrs. H H Desai [ Naranlala college, Navsari ]


User Defined Function in Python:-
• Example:-

def find_fact(num) :
if (num == 0) : •O/P:-
5*4*3*2*1*= 120
return 1 3*2*1*= 6
- In the example, code has been implemented
simply to find the factorial of a number.
print(num, end='*')
- In the example, a condition has been given that if
# Recursion. the value of the variable is less than 1, only 1 is
returned, otherwise the same function will be called.
result = (num*find_fact(num - 1) )
return result

print('=', find_fact(5))
print('=', find_fact(3))
Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• Lambda Function:- A lambda function is a small anonymous function.
• Lambda functions are very sort functions, means when we have to write a single line statement
function, instead of defining a complete function, we use lambda functions.

• Predefined keyword lambda is used to define lambda function.

• SYNTAX:-

var = lambda argument : expression


• These functions automatically return the value according to the expression, we do not need to
write a return statement.
Mrs. H H Desai [ Naranlala college, Navsari ]
User Defined Function in Python:-
• EXAMPLE:- O/P:-

do_square = lambda num : num * num Square of 10 : 100 Square of 20 : 400

#call the function.


print('Square of 10 :', do_square(10))
#change value.
print(‘Square of 20 :', do_square(20))

Mrs. H H Desai [ Naranlala college, Navsari ]


User Defined Function in Python:-
IMPORTANCE:-
• As you read above, we do not need to write return in lambda function. But if you write then error will be
generated.
• Never use print() statement in lambda function, it does not mean that print function will not work. But in
that case None will be returned. because it automatically returns a value, and the print() function returns
None after printing a value.
• In lambda function you can also access external variables (which are defined outside the function) like a
normal function.

Mrs. H H Desai [ Naranlala college, Navsari ]

You might also like