fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Checking if the key is in the dict

    When adding and accessing elements to dictionaries, we might accidentally try to access a key that hasn’t been added to the dictionary yet. In that case, Python will tell us that a KeyError occurred and there isn’t such a key in the dictionary. To check if the key is in the dictionary, we can use the in keyword (exactly as we would do in lists, tuples, or sets).
    costs = {
    	'Living room': 200,
    	'Bathroom': 400,
    	'Kitchen': 500,
    	'Balcony': 100,
    }
    print(costs['Bedroom'])   # KeyError: 'Bedroom'
    
    if 'Bedroom' in costs:
    	print(costs['Bedroom'])
    else:
    	costs['Bedroom'] = 150
    
    print(costs)
    # {'Living room': 200, 'Bathroom': 400, 'Kitchen': 500, 'Balcony': 100, 'Bedroom': 150}

    Challenge

    You are asked to calculate the most frequent word in the essay and output it. You know that words are separated by a space and that you should ignore uppercase/lowercase difference. It is guaranteed that there is only a single most common word.
    The input contains a single line of text, where words are separated by a space.
    The output should contain the most frequent word of the input.
    Input
    Output
    Bob is a great person! He is an engineer.
    is
    Anna is awesome, call Anna
    anna
    To check your solution you need to sign in
    Sign in to continue