Book Image

Python Fundamentals

By : Ryan Marvin, Mark Ng’ang’a, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Ng’ang’a, Amos Omondi

Overview of this book

<p>After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions.</p> <p>As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation.</p> <p>By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.</p>
Table of Contents (12 chapters)
Python Fundamentals
Preface

Chapter 2: Data Types


Activity 7: Order of Operations

Solution:

>>> 5 * (4 - 2) + 100 / ( 5/2 ) * 2
90.0

Activity 8: Using Different Arithmetic Operators

Solution:

  1. Create a file named convert_days.py.

  2. On the first line, let's declare the user input. It's an integer, so we cast the string we get from the input function:

    days = int(input("Number of days:"))
  3. We can then calculate the number of years in that set of days. We floor divide to get an integer:

    years = days // 365
  4. Next, we convert the remaining days that weren't converted to years into weeks:

    weeks = (days % 365) // 7
  5. Then, we get any remaining days that weren't converted to weeks:

    days = days - ((years * 365) + (weeks * 7))
  6. Finally, we'll print everything out:

    print("Years:", years)
    print("Weeks:", weeks)
    print("Days:", days)
  7. We can then save and run the script by using the python convert_days.py command.

Activity 9: String Slicing

Solution:

  1. 'g'

  2. '9'

  3. 'fright'

  4. ' 1, 2, 3'

  5. 'A man, a plan, a canal: Panama'

Activity 10: Working with Strings

Solution:

  1. Create a file named convert_to_uppercase.py.

  2. On the first line, we'll request the user for the string to convert:

    string = input("String to convert: ")
  3. On the next line, we'll request the number of last letters to convert:

    n = int(input("How many last letters should be converted? "))
  4. Next, we'll get the first part of the string:

    # First part of the string
    start = string[:len(string) - n]
  5. Then, we'll get the last part of the string, that is, the one we'll be converting:

    # last part of the string that we're converting.
    end = string[len(string) - n:]
  6. Then, we will concatenate the first and last part back together with the last substring transformed:

    print(start + end.upper())
  7. Finally, we can run the script with the python convert_to_uppercase.py command.

Activity 11: Manipulating Strings

Solution:

  1. Create a file named count_occurrences.py.

  2. We'll take in the user inputs for the sentence and the query:

    sentence = input("Sentence: ")
    query = input("Word to look for in sentence: ")
  3. Next, we'll sanitize and format our inputs by removing the whitespace and converting them to lowercase:

    # sanitize our inputs
    sentence = sentence.lower().strip()
    query = query.lower().strip()
  4. We'll count the occurrences of the substring by using the str.count() method:

    num_occurrences = sentence.count(query)

    Then, we will print the results:

    print(f"There are {num_occurrences} occurrences of '{query}' in the sentence.")
  5. You can run the script by using the python count_occurrences.py command.

Activity 12: Working with Lists

Solution:

  1. Create a file named get_first_n_elements.py.

  2. On the first line, we'll create the array:

    array = [55, 12, 37, 831, 57, 16, 93, 44, 22]
  3. Next, we'll print the array out and fetch user input for the number of elements to fetch from the array:

    print("Array: ", array)
    n = int(input("Number of elements to fetch from array: "))
  4. Finally, we'll print out the slice of the array from the first element to the nth element:

    print(array[0: n])
  5. Then, we'll run the script by using the python get_first_n_elements.py command.

Activity 13: Using Boolean Operators

Solutions:

  1. The code block with the missing Boolean operator is added:

    n = 124
    if n % 2 == 0:
        print("Even")
  2. The code block with the missing Boolean operator is added:

    age = 25
    if age >= 18:
        print("Here is your legal pass.")
  3. The code block with the missing Boolean operator is added:

    letter = "b"
    if letter not in ["a", "e", "i", "o", "u"]:
      print(f"'{letter}' is not a vowel.")