From 8ef5219159732d776da07312e56d5cd71b15c3f2 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Sat, 30 Nov 2019 00:45:22 +0200 Subject: [PATCH] day 11 --- readme10-12.md | 454 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 449 insertions(+), 5 deletions(-) diff --git a/readme10-12.md b/readme10-12.md index f816b2d..9d94b41 100644 --- a/readme10-12.md +++ b/readme10-12.md @@ -8,11 +8,33 @@ - [While Loop](#while-loop) - [Break and continue](#break-and-continue) - [For Loop](#for-loop) - - [Break and Continue](#break-and-continue) - - [The range function](#the-range-function) - - [Nested for loop](#nested-for-loop) - - [For Else](#for-else) - - [Pass](#pass) +- [syntax](#syntax) +- [syntax](#syntax-1) +- [Declaring a function](#declaring-a-function) +- [Calling function](#calling-function) +- [Function can also return values, if a function doen't return values the value of the function is None](#function-can-also-return-values-if-a-function-doent-return-values-the-value-of-the-function-is-none) +- [Lets rewrite the above functions using return](#lets-rewrite-the-above-functions-using-return) +- [From now on, we return value to a function instead of priting it](#from-now-on-we-return-value-to-a-function-instead-of-priting-it) +- [syntax](#syntax-2) +- [Declaring a function](#declaring-a-function-1) +- [Calling function](#calling-function-1) +- [syntax](#syntax-3) +- [Declaring a function](#declaring-a-function-2) +- [Calling function](#calling-function-2) +- [syntax](#syntax-4) +- [Declaring a function](#declaring-a-function-3) +- [Calling function](#calling-function-3) +- [syntax](#syntax-5) +- [syntax](#syntax-6) +- [syntax](#syntax-7) +- [syntax](#syntax-8) +- [syntax](#syntax-9) +- [syntax](#syntax-10) +- [Declaring a function](#declaring-a-function-4) +- [Calling function](#calling-function-4) +- [syntax](#syntax-11) +- [Declaring a function](#declaring-a-function-5) +- [Calling function](#calling-function-5) - [Exercises: Day 10](#exercises-day-10) # Day 10 ## Loops @@ -355,6 +377,428 @@ In python after semicolon, it requires some code to run but we don't like to exe ``` 1. Go to the data folder and use the countries.py file. Loop throught the countries and extract all the contries containing the word *land*. 1. This is the fruit list, ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop. +# Day 11 +## Import module in Python +Like other programming languages we can also import modules from by importing the file/function using the key word *import*. Lets import the common module we will use most of the time. +```py +import math +print(math.pi) +``` +Now, we have imported the math module which contains lots of function which can help us to mathematical calculations.To check what functions the module has you can use *help(math)*, or dir(math) and this will display the available functions in the module. If we want to import only a specific function from a module we import as follow: +```py +from math import pi +print(pi) +``` +It is also possible to import multiple functions at once +```py +from math import pi, sqrt, pow, abs, floor, ceiling +from math import pi, sqrt, pow, floor, ceil +print(pi) # 3.141592653589793 +print(sqrt(2)) # 1.4142135623730951 +print(pow(2, 3)) # 8.0 +print(floor(9.81)) # 9 +print(ceil(9.81)) # 10 + +``` +But if we want to import all the function in math module we can use * . +```py +from math import * +print(pi) # 3.141592653589793 +print(sqrt(2)) # 1.4142135623730951 +print(pow(2, 3)) # 8.0 +print(floor(9.81)) # 9 +print(ceil(9.81)) # 10 +``` +When we import we can also rename the name of the function. +```py +from math import pi as PI +print(PI) # 3.141592653589793 +``` +By now you are familiar with importing modules. Lets do another more import to be very familiar with importing. Let's import *random* module which can gives random number between 0 and 0.9999.... The *random* module has lots of functions but in this section we will only see *random* and *randin*. +```py +from random import random, randint +print(random()) # it doesn't take argument and return 0 to 0.9999 +print(randint(5, 20)) # it returns a random number between 5 and 20 +``` + +## Functions +So far we have seen many builtin python functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets understand what function is and why we need function? +### Defining a Function +A function is a reusable block of code or programming statements designed to perform a certain task. To define a function, Python provides the *def* keyword. The following is the syntax of defining a function. The function block of code only executed only if we call the function. +### Declaring and calling a function +When we make a function we call it declaring a function. When we start using the function we call it calling or invoking a function. Function can be declared with or without a parameter. +```py +# syntax +# Declaring a function +def function_name(): + codes + codes +# Calling function +function_name() +``` + +### Function without parameters +Function can be declared without a parameter. +**Example:** +```py +def generate_full_name (): + first_name = 'Asabeneh' + last_name = 'Yetayeh' + space = ' ' + full_name = first_name + space + last_name + print(full_name) + +generate_full_name () # calling a function + +def add_two_numbers (): + num_one = 2 + num_two = 3 + total = num_one + num_two + print(total) +add_two_numbers() # call the functionK + +# Function can also return values, if a function doen't return values the value of the function is None +# Lets rewrite the above functions using return +# From now on, we return value to a function instead of priting it + +def generate_full_name (): + first_name = 'Asabeneh' + last_name = 'Yetayeh' + space = ' ' + full_name = first_name + space + last_name + return full_name +print(generate_full_name()) + +def add_two_numbers (): + num_one = 2 + num_two = 3 + total = num_one + num_two + return total +print(add_two_numbers()) +``` + +### Function with parameters +In a function we can pass different data types(number, string, boolean, list, tuple, dictionary or set) as a parameter +* Single Parameter: If our function takes a parameter we should call our function with an argument +```py +# syntax +# Declaring a function +def function_name(parameter): + codes + codes +# Calling function +function_name(parameter) +```` +**Example:** +```py +def greetings (name): + message = name + ', welcome to Python for Everyone!' + return message + +print(greetings('Asabeneh')) + +def add_ten(num): + ten = 10 + return num + ten + +print(add_ten(90)) + + +def square_number(x): + return x * x + +print(square_number(2)) + +def area_of_circle (r): + PI = 3.14 + area = PI * r ** 2 + return area + +print(area_of_circle(10)) + +def sum_of_numbers(n): + total = 0 + for i in range(n+1): + total+=i + print(total) +sum_of_numbers(10) # 55 +sum_of_numbers(100) # 5050 +``` +* Two Parameter: If our function takes parameters we should call our function with arguments +```py +# syntax +# Declaring a function +def function_name(para1, para2): + codes + codes +# Calling function +function_name(arg1, arg2) +```` +**Example:** +```py +def generate_full_name (first_name, last_name): + space = ' ' + full_name = first_name + space + last_name + return full_name +print('Full Name: ', generate_full_name('Asabeneh','Yetayeh')) + +def sum_two_numbers (num_one, num_two): + sum = num_one + num_two + return sum +print('Sum of two numbers: ', sum_two_numbers(1, 9)) + +def calculate_age (current_year, birth_year): + age = current_year - birth_year + return age; + +print('Age: ', calculate_age(2019, 1819)) + +def weight_of_object (mass, gravity): + weight = str(mass * gravity)+ ' N' # the value has to be changed to string first + return weight +print('Weight of an object in Newton: ', weight_of_object(100, 9.81)) + +``` +### Passing arguments with key and value +If we pass the arguments with key and value, the order of the arguments does not matter. +```py +# syntax +# Declaring a function +def function_name(para1, para2): + codes + codes +# Calling function +function_name(para1='John', para2='Doe') # the order of argument now does not matter +```` +**Example:** +```py +# syntax +def print_fullname(firstname, lastname): + space = ' ' + full_name = firstname + space + lastname + print(full_name) +print_fullname(firstname='Asabeneh', lastname='Yetayeh') + +def add_two_numbers (num1, num2): + total = num1 + num2 + print(total) +add_two_numbers(num2=3, num1=2) # Order does not matter + +``` +### Returning a value from a function +If we do not return a value from a function, then our function is returning *None* by default. To return a value from a function we use the key word *return* followed by the data type we are returning. We can return any kind of data types from a function. +* Returning string: + +**Example:** +```py +# syntax +def print_name(firstname): + return firstname +print_name('Asabeneh') # Asabeneh + +def print_full_name(firstname, lastname): + space = ' ' + full_name = firstname + space + lastname + return full_name +print_full_name(firstname='Asabeneh', lastname='Yetayeh') +``` +* Returning Number: + +**Example:** +```py +# syntax +def add_two_numbers (num1, num2): + total = num1 + num2 + return total +print(add_two_numbers(2, 3)) + +def calculate_age (current_year, birth_year): + age = current_year - birth_year + return age; + +print('Age: ', calculate_age(2019, 1819)) +``` +* Returning Boolean: +**Example:** +```py +# syntax +def is_even (n): + if n % 2 == 0: + print('even') + return True + return False +print(is_even(10)) # True +``` +* Returning List: +**Example:** +```py +# syntax +def find_even_numbers(n): + evens = [] + for i in range(n+1): + if i % 2 == 0: + evens.append(i) + return evens +print(find_even_numbers(10)) +``` +### Function with default parameters +Sometimes we pass default values to parameters, when we invoke the function if we do not pass an argument the default value will be used. +```py +# syntax +# Declaring a function +def function_name(param = value): + codes + codes +# Calling function +function_name() +function_name(arg) +```` +**Example:** +```py + message = name + ', welcome to Python for Everyone!' + return message + +print(greetings()) +print(greetings('Asabeneh')) + +def generate_full_name (first_name = 'Asabeneh', last_name = 'Yetayeh'): + space = ' ' + full_name = first_name + space + last_name + return full_name + + +print(generate_full_name()) +print(generate_full_name('David','Smith')) + +def calculate_age (birth_year,current_year = 2019): + age = current_year - birth_year + return age; +print('Age: ', calculate_age(1819)) + +def weight_of_object (mass, gravity = 9.81): + weight = str(mass * gravity)+ ' N' # the value has to be changed to string first + return weight +print('Weight of an object in Newton: ', weight_of_object(100)) # 9.81 gravity at the surface of Earth +print('Weight of an object in Newton: ', weight_of_object(100, 1.62)) # gravity at surface of Moon +``` +### Arbitrary number of arguments +If we do not know the number of arguments we pass to our function we can create a function which can take arbitrary number of arguments by add * before the parameter name. +```py +# syntax +# Declaring a function +def function_name(*args): + codes + codes +# Calling function +function_name(param1, param2, param3,..) +``` +**Example:** +```py +def sum_all_nums(*nums): + total = 0 + for num in nums: + total += num + return total +print(sum_all_nums(2, 3, 5)) + +``` +### Function with default parameter and arbitrary number of parameters +```py +def generate_groups (team,*args): + print(team) + for i in args: + print(i) +generate_groups('Team-1','Asabeneh','Brook','David','Eyob') +``` +### Function as parameter of other function +```py +#You can pass functions around as parameters +def square_number (n): + return n * n +def do_something(f, x): + return f(x) + +print(do_something(square_number, 3)) +``` + + +## Exercises: Day 10 +1. Declare a function *add_two_numbers* and it takes two two parameters and it returns sum. +1. Area of a circle is calculated as follows: area = π x r x r. Write a function which calculates *area_of_circle*. +1. Write a function called add_all_nums which take arbitrary number of arguments and sum all the arguments. Check if all the list items are number types. If not give return reasonable feedback. +1. Temperature in oC can be converted to oF using this formula: oF = (oC x 9/5) + 32. Write a function which converts oC to oF, *convert_celcius_to-fahrenheit*. +1. Write a function called check-season, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer. +1. Write a function called calculate_slope which return the slop of a linear equation +1. Quadratic equation is calculated as follows: ax2 + bx + c = 0. Write a function which calculates solution set of a quadratic equation, *solve_quadratic_eqn*. +1. Declare a function name _print_list. It takes list as a parameter and it prints out each element of the list. +1. Declare a function name _reverse_list. It takes array as a parameter and it returns the reverse of the array (dont’ use method). + ```py + print(reverse_list([1, 2, 3, 4, 5])) + # [5, 4, 3, 2, 1] + print(reverse_list1.(["A", "B", "C"])) + # ["C", "B", "A"] + ``` +1. Declare a function name _capitalize_list_items. It takes list as a parameter and it returns the capitalized list of the elements +1. Declare a function name _add_item. It takes an item parameter and it returns a list after adding the element +Declare a function name remove_item. It takes an index parameter and it returns a list after removing an element +1. Declare a function name _sum_of_numbers. It takes a number parameter and it adds all the numbers in that range. +1. Declare a function name _sum_of_odds. It takes a number parameter and it adds all the odd numbers in that - range. +1. Declare a function name _sum_of_even. It takes a number parameter and it adds all the even numbers in that - range. +Declare a function name evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number. + ```py + print(evens_and_odds(100)) + # The number of odds are 50. + # The number of evens are 51. + ``` +1. Writ a function which generates a six digit random_user_id. + ```py + print(random_user_id()); + '1ee33d' + ``` +1. Modify question number above . Declare a function name _user_id_gen_by_user. It doesn’t take any parameter but it takes two inputs using input(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. + ```py + user_id_gen_by_user() + "kcsy2 + SMFYb + bWmeq + ZXOYh + 2Rgxf + " + user_id_gen_by_user() + "1GCSgPLMaBAVQZ26 + YD7eFwNQKNs7qXaT + ycArC5yrRupyG00S + UbGxOFI7UXSWAyKN + dIV0SSUTgAdKwStr + " + ``` +1. Write a function name _rgb_color_gen and it generates rgb colors. + ```py + print(rgb_color_gen()) + # rgb(125,244,255) + ``` +1. Write a function list_of_hexa_colors which return any number of hexadecimal colors in an array. +1. Write a function list_of_rgb_colors which return any number of RGB colors in an array. +Write a function generate_colors which can generate any number of hexa or rgb colors. + ```py + generate_colors('hexa', 3) + # ['#a3e12f','#03ed55','#eb3d2b'] + generate_colors('hexa', 1) + # '#b334ef' + generate_colors('rgb', 3) + # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80'] + generate_colors('rgb', 1) + # 'rgb(33,79, 176)' + ``` +1. Call your function _shuffle_list, it takes a list as a parameter and it returns a shuffled list +1. Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number +Call your function _isempty, it takes a parameter and it checks if it is empty or not +1. Write different functions which take lists and it calculate_mean, calculate_median, calculate_mode, calculate_range, calculate_variance, calculate_std. +1. Write a function called is_prime, which checks if a number is prime number. +1. Write a functions which checks if all items are unique in the list. +1. Write a function which checks if all the items of the list are the same data type. +1. Write a function which check if variable if valid python variable +1. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique. [<< Part 3 ](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme7-9.md) | [Part 5 >>](#) ***