본문 바로가기
Study Note/Python

4. Function [Def]

by jhleeatl 2024. 3. 26.

Def(ine)

 

The purpose of using Def function.

If you frequently use lengthy code that you'd like to abbreviate into a single word, you can do so by defining it as a function.

 

 

Example 1

def bus_rate (age):
       if age > 65:
              print('Its Free')
       elif age > 20 :
              print ('Adult')
       else:
              print('youth')

bus_rate(36)

 

Result

 

Example 2

def bus_rate (age):
       if age > 65:
              return 0
       elif age > 20 :
              return 1200
       else:
              return 750

my_rate = bus_rate(35)
print(my_rate)

Result

 

Practice 

 

Question.

Create a function to find males and females.

def check_gender(pin):
       print()

check_gender('150101-1012345')
check_gender('150101-3012345')
check_gender('150101-4012345')

 

 

 

Answer

def check_gender(pin):
       num=pin.split('-')[1][:1]
       if int(num) % 2 == 0:
              print('Femle')
       else:
              print('Male')

check_gender('150101-1012345')
check_gender('150101-3012345')
check_gender('150101-4012345')

 

"In order to make this query, I had to convert the dictionary to a number using int() function.

 

While I tried to solve this question, I realized that I am still confused with using ':' and the formula. Therefore, I think I may need to practice more. Before moving to the next step, I believe I should repeat the class again to absorb all the information."

'Study Note > Python' 카테고리의 다른 글

6. Set & tuples and list  (0) 2024.03.27
5. Uses of [] {} ()  (0) 2024.03.26
3. IF & loop  (0) 2024.03.25
2. List & dictionary  (0) 2024.03.25
1. Variable declaration and data types  (0) 2024.03.25