Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

10/10/2020 Day-6 [ Functions and Strings]

In [ ]: #Agenda of Today Session:


1. Continue with Loop oof while
2. Functions in Python
3. Strings in Python
Problem solving

In [ ]: #while loop:
while loop i used to iterate over a block of code as long as the test condition (expression) is True.
#Note : when we use while loops?
when we dont know the number of iterations for the looping of our code.

In [ ]: #How implement of the while loop:


#Syntax:
while test_expression:
body of while loop

In [7]: #example: (Program to print the sum of first N Natural numbers)


n= int(input("enter n value"))
i =1
sum =0
while i <=n:
sum = sum+i
i=i+1
print("The Sum is ",sum)

enter n value10
The Sum is 55

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 1/10


10/10/2020 Day-6 [ Functions and Strings]

In [8]: #While with else statement


count = 1
while count <5:
print("iam in while loop")
count = count+1
else:
print("Im Outside while Loop")

iam in while loop


iam in while loop
iam in while loop
iam in while loop
Im Outside while Loop

In [7]: #Break and continue with while loop:


s = "Python Programming"
for letter in s:
if letter =="g":
break
print(letter)

P
y
t
h
o
n

P
r
o

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 2/10


10/10/2020 Day-6 [ Functions and Strings]

In [13]: var =int(input("enter value"))


while var >0:
print("current value :",var)
var = var-1
if var ==5:
break
print("End loop")

enter value10
current value : 10
current value : 9
current value : 8
current value : 7
current value : 6
End loop

In [ ]: #Functions in Python:
what are functions?
A function is a group of related statements that performs a specific task.
why we use functions?
(i) function can help to break our large or complex project into smaller parts.
(ii) Functions make the code as more organized and manageable.
(iii) Its avoids the repetition and makes the code reusable.

In [ ]: #Syntax of Function:
def function_name(parameters): #called parameters or formal parameters
"""doc string"""
statements
return expression
function_name(arguments)- #Calling parameters or actual parameters

In [20]: #How to implement the functions:


def display_name(name):
"""This function is used to display the given name"""
print("Hello "+ name + " Good Evening")
display_name(input("enter a name"))

enter a nameStudents
Hello Students Good Evening

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 3/10


10/10/2020 Day-6 [ Functions and Strings]

In [27]: #function attributes:


print(display_name.__doc__)
print(display_name.__name__)
print(display_name.__dir__)
print(display_name.__format__)
print(display_name.__code__)

This function is used to display the given name


display_name
<built-in method __dir__ of function object at 0x000002033EDEB488>
<built-in method __format__ of function object at 0x000002033EDEB488>
<code object display_name at 0x000002033EC7C540, file "<ipython-input-20-65a311c1d5cc>", line 2>

In [24]: print(dir(display_name),end=" ")

['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dic


t__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '_
_name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__s
izeof__', '__str__', '__subclasshook__']

In [ ]: #return statement:
The return statement is used to exit a function and go back to the place from where it was called.
#syntax:
return [expression_list]

In [28]: def abs_value(n):


"""This function get the absolute of number of given number"""
if n>=0:
return n
else:
return -n
print(abs_value(5))
print(abs_value(-9))

5
9

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 4/10


10/10/2020 Day-6 [ Functions and Strings]

In [29]: #Scope and life time of variable in a function:


def local_var():
x = 20 #inside variable
print("im in inside the function",x)
x = 50 #Out side variable
local_var()
print("im in ouside the function",x)

im in inside the function 20


im in ouside the function 50

In [ ]: #Type of functions:
we have 2 types of functions
1. Built-in Functions
2. User-defined functions

In [33]: #with muilple parameters:


def add_3(a,b,c):
x = a+b
y = b+c
z = c+a
print(x,y,z)
a = int(input("enter a value"))
b = int(input("enter b value"))
c = int(input("enter c value"))
add_3(a,b,c)

enter a value10
enter b value20
enter c value30
30 50 40

In [41]: #square of given number:


def square(x):
return x+x**3+x**5+10
square(int(input("enter x value")))

enter x value3

Out[41]: 283

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 5/10


10/10/2020 Day-6 [ Functions and Strings]

In [45]: #Built-in functions:


#1. dir() - to list out all directories and methods , attributes of the particular function,module,data struc
ture
print(dir(list),end=" ")

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__for


mat__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init_
_', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce
__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__
str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

In [47]: len("python")
len([1,2,4,4,5,6,7,8,888,"apssdc","abc"])

Out[47]: 11

In [ ]: input()- to take the input from the user at run time


print() - to display the statements on the rum time console

In [51]: abs(-5)
abs(500)
abs(-40.55)

Out[51]: 40.55

In [54]: li = [1,2,3,4,5]
all(li)

Out[54]: True

In [60]: any([0,0,1])

Out[60]: True

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 6/10


10/10/2020 Day-6 [ Functions and Strings]

In [64]: #bin()- method converts and returns the binary equilvalent string of given integer.
bin(2)
bin(10)
bin(7)
bin(100)

Out[64]: '0b1100100'

In [67]: bool(6) # this method convers a value to boolean (True or False)

Out[67]: True

In [68]: bool(None)

Out[68]: False

In [79]: #chr : this function get the ascii chracter of given interger
print(chr(97))
print(chr(100))
print(chr(122))
print(chr(65))
print(chr(85))
print(chr(1200))

a
d
z
A
U
Ұ

In [85]: print(ord("a"))
print(ord("A"))
print(ord("z"))
print(ord("E"))

97
65
122
69

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 7/10


10/10/2020 Day-6 [ Functions and Strings]

In [ ]: #enumerate(): The method adds counter to an iterable and return it.


#syntax:
enumerate(iterable,start=0)

In [86]: names = ["karthik","kalyan","priya","divya","Raj"]


for name in names:
print(name,end=" ")

karthik kalyan priya divya Raj

In [88]: for name in enumerate(names):


print(name,end=" ")

(0, 'karthik') (1, 'kalyan') (2, 'priya') (3, 'divya') (4, 'Raj')

In [93]: #eval() function: its parses the expression passed to this method and returns the value.
#syntax: eval(expression)
x = 100
eval("x+x**2+x*3+100")

Out[93]: 10500

In [1]: help(eval)

Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)


Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression


or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 8/10


10/10/2020 Day-6 [ Functions and Strings]

In [3]: #filter(function,iterable)
letters = ["p","y","t","h","o","n","i","d","l","e"]
def filtervowels(letter):
vowels = ["a","e","i","o","u"]
if letter in vowels:
return True
else:
return False
filtered= filter(filtervowels,letters)
for vowel in filtered:
print(vowel,end=" ")

o i e

In [ ]: #Type of arguments:
There are 3 types of arguments:
1. default arguments
2. keyword arguments
3. arbitary arguments

In [7]: #default arguments:


def information(place,program="Python Programming "): #here value of the program argument fixed at function
declaration
print("Apssdc is conducting "+program+"workshops in "+place)
information("Online")

Apssdc is conducting Python Programming workshops in Online

In [10]: #Keyword arguments:


def parrot(color,action):
print("Parrot bird is like in " + color+ " color and it can "+action+" in the sky")
parrot(action="fly",color="green") #here values of arguments fixed at function calling.

Parrot bird is like in green color and it can fly in the sky

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 9/10


10/10/2020 Day-6 [ Functions and Strings]

In [12]: #arbitary arguments: this arguments are represented by astrick symbol "*".
def IPL_Players(*names):
return names
IPL_Players("Dhoni","Kohli","K L Rahul","Dhavan","Iyer")

Out[12]: ('Dhoni', 'Kohli', 'K L Rahul', 'Dhavan', 'Iyer')

In [13]: #5. Using Nested if conditions make a logic for Username and password validation and prints the display
#message for successfully logged users.
username = input("enter the username:")
password = input("enter the password: ")
if username == "iamsurya93@gmail.com":
if password=="987654321":
print("Welcome to ",username)
else:
print("Invalid Password")
elif username=="karanam.s@apssdc.in":
if password=="12345":
print("Welcome to",username)
else:
print("Invalid Password")
else:
print("invalid usename")

enter the username:iamsurya93@gmail.com


enter the password: 987654321
Welcome to iamsurya93@gmail.com

In [ ]: #6. Find the grade of students marks and percentage upto 5 members and prints the grade of highest percentag
e:

localhost:8888/nbconvert/html/Desktop/Python_Online_Programmingg/Day-6 (Functions and Strings)/Day-6 %5B Functions and Strings%5D.ipynb?download=false 10/10

You might also like