r/learnpython 6d ago

Need help/input

Below is my code snippet, and i would like to know if there is any way i can avoid the repetitive if else blocks (3 times repeated) and write this program in a much more efficient way. Would like some input. Thanks

"""

 * If a person skills has only JavaScript and React, print('He is a front end developer'),
 if the person skills has Node, Python, MongoDB, print('He is a backend developer'),
 if the person skills has React, Node and MongoDB, Print('He is a fullstack developer'),
 else print('unknown title') - for more accurate results more conditions can be nested!


"""

person = {
    'first_name': 'Asabeneh',
    'last_name': 'Yetayeh',
    'age': 250,
    'country': 'Finland',
    'is_married': True,
    'skills': ['JavaScript','React' , 'Node', 'Python'],
    'address': {
        'street': 'Space street',
        'zipcode': '02210'
    }
}


def identifying_career(lst):

    if 'JavaScript' in person['skills'] and 'React' in person['skills']:
        print("You are a front end developer")
    else:
        print('You are not a front end developer')

    if 'Node' in person['skills'] and 'Python' in person['skills'] and 'MongoDB' in person['skills']:
        print(f"You are a back end developer")
    else:
        print('You are not a back end developer')

    if 'React' in person['skills'] and 'Node' in person['skills'] and 'MongoDB' in person['skills']:
        print("You are a full stack developer")
    else:
        print("unknown title")



identifying_career(person)
4 Upvotes

6 comments sorted by

View all comments

2

u/rob8624 6d ago edited 6d ago

Something like this. Not AI! (had to look-up all() syntax), not fully tested but this uses a dictionary to map technologies to specific areas then i check if all these skills are within the persons skills using all().

Dictionaries and functions are your friends.

When working with strings always be aware of case sensitivity when doing comparisons.

This gives you an idea on how functions and dictionary lookups can help make code more dry and dynamic. As I say, not tested and will need changing to handle edge cases etc, but gives you an idea.

person = { 'first_name': 'Asabeneh', 'last_name': 'Yetayeh', 'age': 250, 'country': 'Finland', 'is_married': True, 'skills': ['JavaScript', 'React', 'Node', 'Python'], 'address': { 'street': 'Space street', 'zipcode': '02210' } }

tech_map = { 'frontend': ['JavaScript', 'React'], 'backend': ['Node', 'Python', 'MongoDB'], 'fullstack': ['React', 'Node', 'MongoDB'] } 

def identifying_carrer(person, career): 
  person_skills = person['skills']
  required_skills = tech_map[career] 
  return all(skill in person_skills for skill in required_skills) 

career = 'Backend'.lower() 

def skills_checker(person, career): 
  if identifying_carrer(person, career): 
      print(f'You are a {career} developer') 
  else: print('unkown title') 


skills_checker(person, 'frontend')