❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Python - Functions

By: ABYS
19 July 2024 at 11:24

FUNCTIONS, an awesome topic I learnt today. It's a shortcut for all lazy i.e., smart people who don't wanna waste their time typing inputs for several times.

What Is a Function?

In programming, rather than repeatedly writing the same code , we write a function and use it whenever and whereever it is needed.
It helps to improve modularity, code organization and reusability.

So, now let's see how to create a function.
A function contains,

  • function name - an identifier by which a function is called
  • arguments - contains a list of values passed to the function
  • function body - this is executed each time the function is called function body must be intended
  • return value - ends function call and sends data back to the program
def function_name(arguments): # key function name(arguments)
  statement                   # function body
  statement

  return value                # return value

Some examples of how to use functions.

#Write a function greet that takes a name as an argument and prints a greeting message.

def greet(name):
    return(f"Hello, {name}!")
greet("ABY")

Hello, ABY!

Here, we can replace return by print too.

#Write a function sum_two that takes two numbers as arguments and returns their sum.

def sum_two(a,b):
    return a+b

result = add(3,7)
print(result)

10

#Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.

def is_even(num):
    return num % 2 == 0

num = 5
print(is_even(num))

False

#Write a function find_max that takes two numbers as arguments and returns the larger one.

def find_max(a,b):
    if a > b:
      return a
    else:
      return b

print(find_max(7,9))

9

#Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.

def multiplication_table(n):
    for I in range (1,11)
    result = n * i 

print(f"{n} * {i} = {result}")
n = multiplication_table(int(input("Enter a no: ")))

and the result is,

Enter a no: 5 # I've entered 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

#Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.

This is how we normally do it..

celsius1 = 27
fahrenheit1 = (celsius1 * 9/5) + 32
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 37
fahrenheit2 = (celsius2 * 9/5) + 32
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 47
fahrenheit3 = (celsius3 * 9/5) + 32
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

27Β°C is 80.6Β°F
37Β°C is 98.6Β°F
47Β°C is 116.6Β°F

It's cumbersome right??
Soo, what's the shortcut? Ofc using a function.

def celsius_to_fahrenheit(celsius):
  return (celsius * 9/5) + 32

celsius = float(input("Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}Β°C is {fahrenheit}Β°F")

Celsius: 37.5
37.5Β°C is 99.5Β°F

I've used input function to make it more compact...

#Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

def pow(num,exp = 2):
  return num ** exp


result = pow(5,exp = 2)
print(f"The number {num} raised to power 2 is ",{result})

You can opt to use input fns and variables as well..

By now, it's understandable that for one problem we can use multiple
programs to solve it. It depends which we prefer to use.

.....

Functions()

26 July 2024 at 14:11

hi, everybody
I am s. kavin
today we gone a see functions.

Functions

Think of a function as a little helper in your code. It’s like a recipe that you can use over and over again.

Why do need functions

1.Reusability
2.Organization
3.Avoiding Repetition
4.Simplifying Complex Problems
eg:

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

celsius1 = 25
fahrenheit1 = celsius_to_fahrenheit(celsius1)
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 30
fahrenheit2 = celsius_to_fahrenheit(celsius2)
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 15
fahrenheit3 = celsius_to_fahrenheit(celsius3)
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

Uses of functions

1. Greet People

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

2. Adding Two Numbers

def add(a, b):
    return a + b

result = add(5, 3)
print(f"The sum is: {result}")

3. Checking if a Number is Even or Odd

def is_even(number):
    return number % 2 == 0

print(is_even(4))  # True
print(is_even(7))  # False

04. Finding the maximum of Three numbers

def max_of_three(a, b, c):
    max = None
    if a > b:
        max = a
    else:
        max = b

    if max > c:
        return max
    else:
        return c

5. Calculating Factorial of a number

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

6. Calculating Area of a Circle

import math

def area_of_circle(radius):
    return math.pi * radius ** 2

print(area_of_circle(5))  # 78.53981633974483

Tasks – Python Function()

17 July 2024 at 11:09
  1. Write a function greet that takes a name as an argument and prints a greeting message.
  2. Write a function sum_two that takes two numbers as arguments and returns their sum.
  3. Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.
  4. Write a function find_max that takes two numbers as arguments and returns the larger one.
  5. Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.
  6. Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.
  7. Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

Python – Functions()

17 July 2024 at 10:11

Think of a function as a little helper in your code. It’s like a recipe that you can use over and over again.

Instead of writing the same steps every time you cook a dish, you write down the recipe once and follow it whenever you need to make that dish.

In programming, instead of writing the same code over and over, you write a function and use it whenever needed.

Why Do We Need Functions?

Here are some everyday examples to show why functions are awesome:

  1. Reusability:
    • Imagine you love making dosa. You have a great recipe, and every time you want dosa, you follow that recipe.
    • You don’t reinvent dosa each time! Similarly, in programming, if you have a piece of code that works well, you put it in a function and reuse it whenever you need it.
  2. Organization:
    • Think about how a recipe book organizes different recipes. One section for breakfast, another for lunch, etc.
    • Functions help you organize your code into neat sections, making it easier to read and understand.
  3. Avoiding Repetition:
    • Let’s say you need to chop vegetables for several different dishes. Instead of writing down β€œchop vegetables” each time in every recipe, you have a single β€œchop vegetables” recipe. In programming, functions help you avoid writing the same code multiple times, reducing mistakes and making your code cleaner.
  4. Simplifying Complex Problems:
    • If you have a big dinner to cook, breaking it down into simpler tasks like chutneys, tiffins, and sweets makes it manageable. In programming, you break a big problem into smaller functions, solve each one, and then combine them.

Let’s say you’re writing a program to convert temperatures from Celsius to Fahrenheit. Without functions, your code might look like this:


# Converting temperatures without functions
celsius1 = 25
fahrenheit1 = (celsius1 * 9/5) + 32
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 30
fahrenheit2 = (celsius2 * 9/5) + 32
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 15
fahrenheit3 = (celsius3 * 9/5) + 32
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

This works, but it’s repetitive. Now, let’s add a function:


# Define a function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

# Use the function to convert temperatures
celsius1 = 25
fahrenheit1 = celsius_to_fahrenheit(celsius1)
print(f"{celsius1}Β°C is {fahrenheit1}Β°F")

celsius2 = 30
fahrenheit2 = celsius_to_fahrenheit(celsius2)
print(f"{celsius2}Β°C is {fahrenheit2}Β°F")

celsius3 = 15
fahrenheit3 = celsius_to_fahrenheit(celsius3)
print(f"{celsius3}Β°C is {fahrenheit3}Β°F")

Some of the examples demonstrating how to use functions to accomplish different tasks.

1. Greet People


def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

2. Adding Two Numbers


def add(a, b):
    return a + b

result = add(5, 3)
print(f"The sum is: {result}")

3. Checking if a Number is Even or Odd

def is_even(number):
    return number % 2 == 0

print(is_even(4))  # True
print(is_even(7))  # False


4. Finding the maximum of Three numbers


def max_of_three(a, b, c):
    max = None
	if a > b:
		max = a
	else:
		max = b
	
	if max > c:
		return max
	else:
		return c

5. Calculating Factorial of a number


def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

6. Calculating Area of a Circle


import math

def area_of_circle(radius):
    return math.pi * radius ** 2

print(area_of_circle(5))  # 78.53981633974483

❌
❌