Home > Enterprise >  How can I implement existing code into a fuction?
How can I implement existing code into a fuction?

Time:05-24

I found out that this is what I am struggling the most. I know how to write a function:

     def test(a,b):
        for x in range(20):
        if x == 15:
            return
    print("test")
    test()

but I don't know how to create a function with something already written:

contacts = {"Alice": " 1554", "Bob": " 1885", "Carol": " 1006", "Felix":" 1604", "Max":" 1369","Chris":" 1882","Lea":" 1518","Linn":" 1742","Julia":" 1707"}

def phone_book(name,book):
    if name in contacts:
        return book

while True:
    print('Enter a name: (blank to quit)')
    name = input()
    if name == '':
        break
    if name in contacts:
        print(contacts[name]   ' is the number of '   name)

I cannot bring to this code to work if I try to utilize a function. Can you explain me how to do this? You don't need to write the code. I really want to understand it.

CodePudding user response:

A function is a way that allows you to automate a certain process in your code.

In your test function, you define 2 parameters so that means you have to provide those 2 variables in order for that function to work. A simple function could be as well as

def test(a,b):
        c = a   b
        print("The sum of  number "   str(a)   "   "   str(b)   " is "   str(c))
test(5, 5)

if you pay attention to the last line I provide the function name along with those 2 variables, only that now they have values (they are now called arguments)

Hopefully the links below can give you more clarifications

https://www.w3schools.com/python/python_functions.asp

Basic explanation of python functions

CodePudding user response:

You can have the function return the formatted string. Then the main code calls the function and prints what it returns.

def phone_book(name,book):
    if name in book:
        return f'{book[name]} is the number of {name}'
    else:
        return f'{name} is unknown'

while True:
    print('Enter a name: (blank to quit)')
    name = input()
    if name == '':
        break
    print(phone_book(name, contacts))

CodePudding user response:

Please Just structure it in a class.

class contact_book:
  def __init__(self):
    self.contacts = {"Alice": " 1554", 
                     "Bob": " 1885", 
                     "Carol": " 1006"}

  def add(self, name, value): self.contacts[name] = value
  def phone(self, name): return self.contacts[name]
  def do_i_know_you(self, name): return name in self.contacts
  def __str__(self): return f"Known contacts are: {list(self.contacts.keys())}"

Usage:

myBook = contact_book()
myBook.add('brian', '4411')
print(myBook) 
print(myBook.do_i_know_you('Martin'))

Result:

Known contacts are: ['Alice', 'Bob', 'Carol', 'brian']
False
  • Related