Sunday, May 14, 2023

#PYTHON(DAY18)recurssion,lambda,filter and map functions

 

#PYTHON(DAY18)

recurssion function

  • recurssion func is a function which calls up on itself
  • Note: this kind of fun needs a base case to stop, if not the execution stack will reaches max depth and exhaust the memory( if you are using jupyter notebook the kernel will be dead)
recurssion function
# factorial with using recurssion
def fact(n):
fact = 1
for i in range(1,n+1):
fact = fact*i
n-=1
return fact
fact(4)

And the output is:

24

lambda functions

  • these functions are called as anonymous functions
  • these are defined in a single line
  • syntax for lambda functions:
  • ‘lambda’ var_name: <’statement/s using these var/s’>
  • these functions by default will return a value, no need to write a return statement
  • there is no cap on no of vars one can use to define a lambda function
lambda function
# normal func
def powAB(a,b):
return a**b
powAB(4,5)

And the output is:

1024

filter()

  • filter function is used to filter the elements based on user’s logic
  • this user’s logic is written as function, which gives a boolean output, True when it meets the user’s logic, or else it will return False
  • filter function will return an iterator of cls=ass filter, we can typecast this to a list
  • filter function accepts 2 parameters 1) function 2) iterator/container
  • syntax of filter function:
  • filter(func,container/iterator)
filter function
nums = [i for i in range(1,51)]
even = filter(lambda num: num%2 == 0,nums)
odd = filter(lambda num: num%2 !=0, nums)
print(type(even),type(odd))
even,odd = list(even),list(odd)
print(type(even),type(odd))
print(even,odd,sep = '\n')

And the output is:

<class 'filter'> <class 'filter'>
<class 'list'> <class 'list'>
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

map

  • we use ‘map’ function to apply our function on each element of an iterator
  • syntax of ‘map’ function:
  • map(func,iterator)
  • output of map function is a map object, we need to type cast it to a list or other data types to see the output
map function
nums = [ele for ele in range(1,11)]
cube_nums = map(lambda x : x**3, nums)
print(cube_nums, type(cube_nums), sep = '\n')
cube_nums = list(cube_nums)
print(cube_nums, type(cube_nums),sep = '\n')

And the output is:

<map object at 0x00000230D2B6B700>
<class 'map'>
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
<class 'list'>

Saturday, May 13, 2023

#PYTHON(DAY17)Args and Kwargs

 

#PYTHON(DAY17)

args and kwargs

We use args and kwargs as an argument when we are unsure about the number of arguments to pass in the functions.

Special Symbols Used for passing arguments in Python:

  • *args (positional Arguments)
  • **kwargs (Keyword Arguments)

What is Python *args?

The special syntax *args in function definitions in Python is used to pass a variable number of arguments to a function. It is used to pass a positional argument, variable-length argument list.

  • The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
  • What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
  • For example, we want to make a multiply function that takes any number of arguments and is able to multiply them all together. It can be done using *args.
  • Using the *, the variable that we associate with the * becomes iterable meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.

Example:

def myFun(*argv):
for arg in argv:
print(arg)


myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

And the output is:

Hello
Welcome
to
GeeksforGeeks

What is Python **kwargs?

The special syntax **kwargs in function definitions in Python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

  • A keyword argument is where you provide a name to the variable as you pass it into the function.
  • One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))


# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

And the output is:

first == Geeks
mid == for
last == Geeks

return

  • if our intention is to capture and reuse the value given by our user defined function, then we need to use ‘return’ statement
  • ‘return’ will return the value/s passed to it and comes outside the function block with the value given to it
# using return
def foo(x,y,z):
return (x+y)*z

a = foo(2,3,4)
print(a)

And the output is:

20

Friday, May 12, 2023

#PYTHON(DAY16)functions

 

#PYTHON(DAY16)

functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

We may call the function and reuse the code contained within it with different variables rather than repeatedly creating the same code block for different input variables.

Advantages of Functions in Python

Python functions have the following Perks.

  • By including functions, we can prevent repeating the same code block repeatedly in a program.
  • Python functions, once defined, can be called many times and from anywhere in a program.

Syntax of Python Function

# An example Python Function
def function_name( parameters ):
# code block

Creating a function

def my_function():
print("Hello from a function")

calling a function

To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()

How the position of argument matters?

def greet(name, greeting):
print(greeting+' '+name)
greet('good mrng','x')

And the output is:

x good mrng

As, here the greeting is good mrng we get name as good mrng instead of x

so, here we discuss about the arguments

Arguments

positional arguments

  • while passing the argument/s, the value/s of arg/s will be assigned to parameters based on the order of parameters at time of defining function
  • while calling ‘greet’ function, we inter changed the order and this resulted in a different o/p
  • these kind of passing the arguments based on positions are called as positional arguments

Example for positional arguments

def abc(x,y,z):
print(x+y+z)
abc(1,2,3)

And the output is:

6

keyword arguments

  • at the time of calling the func, if we pass the arguments by using the parameter name, these kind of arguments are called as keyword arguments
  • func_name(para1=arg1, para2=arg2)

Example for keyword arguments

def greet(greeting,firstname,lastname):
print(greeting+' '+firstname+' '+lastname)
greet(greeting ='hi', firstname='bhavitha',lastname='cherukuri')

And the output is:

hi bhavitha cherukuri

Thursday, May 11, 2023

#PYTHON(DAY15)loop and loop control statements

#PYTHON(DAY15)

loop statements

Looping means repeating something over and over until a particular condition is satisfied.

for loop

  • for loop keeps executing the block of code till it reaches the end of the iterator
  • iterator: is an object which has some value, and next time we execute the loop, this value will be taken/considered

syntax

for var_name in iterator:
block of code
x = [1,2,3]
for ele in x:
print(ele)
print('outside the loop')

And the output is:

1
2
3
outside the loop

while

  • while is a ‘looping statement’ in python which uses ‘c.e’ to determine whether to execute the loop or not
  • if the given c.e turns out to be ‘True’, the code within the ‘while’ block will be executed
  • in order to exit the loop, we need to alter or change the o/p of the given c.e to ‘False’
  • if not, the code within the ‘while’ block will be executed till the memory is exhausted
  • we can change the given c.e o/p to ‘False’ by using a statements like ‘assignment’, ‘if-block’ or a ‘control-flow’

syntax

while expression:
statement(s)

Note: if our while loop doesnot have the statement that alters the o/p of ‘conditional execution’ to ‘False’, the loop keeps running till the memory runs out

Example

x = 1
while x <=10:
print(x, end =',')
x+=1

And the output is:

1,2,3,4,5,6,7,8,9,10,

Using else statement with While Loop in Python

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.

Syntax of While Loop with else statement:

while condition:
# execute these statements
else:
# execute these statements

Example

count = 0
while (count < 3):
count = count + 1
print("Hello world")
else:
print("In Else Block")

And the output is:

Hello world
Hello world
Hello world
In Else Block

loop control statements

  • these statements are used to alter the way execution of our loop statements.
  • there are three control flow statements
  • ‘pass’: it acts like a place holder for your code
  • ‘continue’: it terminates the current loop iteration and runs the loop with next value
  • ‘break’: it abruptly ends and exits the loop.

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.

if True:
pass # for escaping the value

Continue Statement

the continue statement in Python returns the control to the beginning of the loop.

for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)

And the output is:

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Break Statement

The break statement in Python brings control out of the loop.

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break

print('Current Letter :', letter)

And the output is:

a = 0
b = 3
while a <=b:
print(a)
while b>=a:
print(b)
b-=1
a+=1

And the output is:

0
3
2
1
0

 

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...