Skip to content

Commit

Permalink
Functions completed
Browse files Browse the repository at this point in the history
  • Loading branch information
stalj committed Sep 30, 2024
1 parent 9e3acb6 commit f4fa646
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 181 deletions.
Binary file modified 01-CourseIntroduction/CourseIntroduction.pptx
Binary file not shown.
162 changes: 50 additions & 112 deletions 04-Functions/Functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ [email protected]

For example, if you want to display information on the screen, you use the print() function, using its name and, in parentheses, the function's arguments, if any are required.

```python
print('Hello World')
```python
print('Hello World')
```

## 2. Built-in Functions

Expand All @@ -37,6 +38,9 @@ [email protected]
* absolute value of -17

```python
###
# Program for testing built-in functions
#
max_number = max(7,5,6,3,8,2)
print('Max number of 7,5,6,3,8,2 is', max_number)

Expand Down Expand Up @@ -78,6 +82,15 @@ [email protected]
...
```

1. Write a program that generates and displays a random number between 1 and 6, similar to rolling a dice. Use one of the functions from the **random** module to generate a random integer within a given range.

```python
import random

...
...
```

## 4. Defining a Function

1. Watch the videos on defining a function:
Expand Down Expand Up @@ -113,6 +126,32 @@ [email protected]
print(sum_value) # Output: 8
```

1. Define a function **triangle_area** that calculates and returns the area of ​​a triangle with sides a, b, and c. Use Heron's formula:

<https://en.wikipedia.org/wiki/Heron%27s_formula>

Write a program that calculates the area of ​​a triangle based on the lengths of the triangle's sides read from the keyboard. Use the defined function. Then calculate the area of ​​the triangle for the following dimensions of sides a, b, and c:

* 3, 4, 5 (result is 6)
* 5, 12, 13 (result is 30)
* 7, 24, 25 (result is 84)

1. Define a function that calculates and returns the sum of the digits in a number. Then write a program that reads a number from the keyboard and displays the sum of its digits.

```python
###
# Calculates the sum of the digits in a number
#
def digit_sum(number):
...
...
return ...

any_number = int(input('Enter integer number: '))
result = digit_sum(...)
print('The sum of the digits in the number ... is ...')
```

1. Define a function that calculates the final grade for a test based on the number of points obtained, according to the rules:

* Less than 10 points, final grade: Fail
Expand All @@ -126,7 +165,7 @@ [email protected]
# on the number of points obtained
#
def pts_to_grade(points):
grade = 0
grade = ''
if points >= 18:
grade = 'Excellent'
...
Expand Down Expand Up @@ -162,133 +201,32 @@ [email protected]
print('The name of day 7 in the week is', day_name(7))
```

1. The ICAO (International Civil Aviation Organization) phonetic alphabet is used internationally for spelling out letters in radio communication.

The icao.py program contains a function that returns the corresponding word for a given letter. Complete the program do spell out a name entered from the keyboard.

1.

## Passing and Returning Values

1. Define a function product(x, y) that displays a product of two numbers. Then, call the function.

def product(x,y):\
return x\*y\
\
a = 3\
b = 4\
print(f\"The product of {a} and {b} is {product(a,b)}\")

1. Define the function different(n1,n2,n3), which returns True if all three numbers n1,n2,n3 are different or False otherwise. Then, write a program that reads three integers from the keyboard. Checks whether the numbers are different. Sample result:

Enter first number: ...\
Enter second number: ...\
Enter third number: ...\
Numbers ..., ..., and ... are different

1. Define a function numbers(n) that returns a string containing integer numbers from 1 to n, separated by a single space character. Then, call the function and display numbers from 1 to 15 and from 1 to 7. Sample result:

Numbers \<1,15\>: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\
Numbers \<1,7\>: 1 2 3 4 5 6 7

## Anonymous Functions

<https://youtu.be/25ovCm9jKfA?feature=shared>

1. Define an anonymous function that calculates the body mass index
(BMI) for the given weight in kg and height in cm. Then, calculate
the BMI for Peter (81kg, 182cm). Sample result:
1. The ICAO (International Civil Aviation Organization) phonetic alphabet is used internationally for spelling out letters in radio communication. The icao.py program contains a function that returns the corresponding word for a given letter. Complete the program to spell out a name entered from the keyboard.

Peter's BMI is ...

## Global and Local Variables

1. If you use a function in a program, variables can appear both inside
and outside the function. Variables defined inside a function are
usually not visible and cannot be used outside the function. On the
other hand, variables defined outside the function are visible and
can be used inside the function. Familiarize yourself with the
concepts of \'global variable\' and \'local variable\' and how to
use them.

<https://youtu.be/QYUbLevwgDQ?feature=shared>


## Dividing Program Code into Modules
## 5. Dividing Program Code into Modules

1. Familiarise yourself with dividing a program code into modules:

<https://www.w3schools.com/python/python_modules.asp>

<https://docs.python.org/3/tutorial/modules.html>

1. Create the following two modules:
1. The converters.py file defines two functions for converting length units (cm-->m and m-->cm). The test_converters.py file uses these functions to convert values.

**converters.py**
Define the following functions in the converters.py file that allow you to:

def m_to_cm(n):\
return n\*100\
\
def cm_to_m(n):\
return n/100\
\
if \_\_name\_\_ == \"\_\_main\_\_\":\
\# only execute when you run this module\
print(f\'2m = {m_to_cm(2)}cm\')\
print(f\'532cm = {cm_to_m(532)}m\')
* convert centimeters to inches
* convert feet and inches to centimeters

**myprogram.py**

import converters\
print(\'## Test converters\')\
print(f\'Three meters is {converters.m_to_cm(3)}cm\')

First, run converters.py and see what information is displayed.
Then, run myprogram.py, paying attention to the information that is
displayed. Do you know why the information displayed is different?

1. In a separate module, define a function that calculates the sum of digits. Use the function to calculate the sum of digits entered from the keyboard. To do it, copy the following modules. Then, run the programs digits.py and myprogram.py separately. Try to analyze the results. Do you understand how to import a module and how to call the functions contained in the module?

**digits.py**

def sum_digits(n):\
    sum = 0\
    while n \> 0:\
        sum += n % 10\
        n //= 10\
    return sum\
\
if \_\_name\_\_ == \"\_\_main\_\_\":\
    \# check if function works\
    print(sum_digits(7182))\
    print(sum_digits(0))\
    print(sum_digits(333))

**myprogram.py**

import digits\
\
number = int(input(\"Enter a number: \"))\
sum_d = digits.sum_digits(number)\
msg = f\"Sum of digits {number} is {sum_d}\"\
print(msg)
YThen complete the main program to test the added functions.

1. In the module mykeyboard.py, define a function read_number() that returns an integer number entered from the keyboard. The function should print a text prompting user to enter data \'Enter a number: \'. Then, use the function to read two numbers from the keyboard. To test the function, use the \_\_name\_\_ variable. Display the sum of two entered numbers. Sample result:

Enter a number: 34\
Enter a number: 7\
34 + 7 = 41

## Main Function

1. Sometimes we want certain statements contained in a module to execute only when the module is run, and not to execute when the module is imported. Check how this can be achieved.

<https://youtu.be/NB5LGzmSiCs?feature=shared>

<https://docs.python.org/3/library/__main__.html>


## Practice Makes Perfect
## 7. Practice Makes Perfect

1. In the module mymath.py, define the function generate_number() that creates and returns random integer number in the range of \<1,9\>. Then create a main program, in which, first import modules mymath.py and mykeyboard.py, you created earlier. The program is a simple guessing game. The user enters a one-digit number from the keyboard. The computer then generates a random one-digit number. If the numbers match, the user wins the game. Sample result:

Expand Down
12 changes: 12 additions & 0 deletions 04-Functions/converters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def m_to_cm(n):
return n*100

def cm_to_m(n):
return n/100

if __name__ == "__main__":
# only execute when you run this module
print(f'2m = {m_to_cm(2)}cm')
print(f'532cm = {cm_to_m(532)}m')


6 changes: 6 additions & 0 deletions 04-Functions/test_converters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import converters

print('### Test converters')
print(f'Three meters is {converters.m_to_cm(3)}cm')


Binary file added __pycache__/converters.cpython-312.pyc
Binary file not shown.
69 changes: 0 additions & 69 deletions test.py

This file was deleted.

0 comments on commit f4fa646

Please sign in to comment.