Chat with us, powered by LiveChat
Module 1: Python Basics

WELCOME

In this module, you’ll learn about Python basics such as variables, types, printing, expressions, and debugging. These are some of the most fundamental principles of programming in Python. Some of the things you’ll learn here are common to many languages, whereas some are specific to Python. Regardless, the things you’ll learn in this module are going to enable you to craft more complex, multistep programs later on.

Go Slow To Go Fast

Take time to allow yourself to master these basic concepts, as they will show up again and again as you dive into more intermediate and advanced Python concepts later.

Being a new programmer is hard — there’s so much to learn, so many different languages and countless resources to get started. As a new coder, it can be difficult to stay focused. Sometimes, all it takes is an unfamiliar error message to prevent a new coder from sticking with it. Be persistent!

Topics We’ll Cover

  • Introduction to syntax
  • Data types
  • Printing
  • Calling built-in functions
  • Lesson

    What is syntax?

    Programming languages provide a vocabulary for instructing computers to do something. As with any language, computer programming languages have a certain syntax, or a correct ordering of words in order to convey meaning.

    As a programming language, Python syntax is particularly succinct and human-readable. In order to print a message from Python, the syntax is:

    >>> print "Hello, world"
    Hello, world
    

    If you’d like to print two things using Python, each separated by a space, execute the following code:

    >>> print "Thing 1", "Thing 2"
    Thing 1 Thing 2
    

    Try it out!

    As a programmer, it’s important to be curious. Open a new Python repl session and navigate to the console on the right. Next, find out what happens when you use the print keyword without anything to print. So, once you’re in the console simply type:

    >>> print
    

    And then press enter. What happens?

    It might look like nothing, but note that Python actually did print something. It was a blank line! Python prints out a something called a newline character after every statement it prints. Without anything to print, Python just prints a newline character, all by itself.

    Keywords and strings

    Let’s break those print statements down a bit. First, we’ll start with the word print.

    Python allocates special meaning to certain words in its syntax, such as print. The special words are called keywords in Python– words that, when evaluated as part of the syntax, will cause something to happen. In this case, what ever comes after the print keyword will appear as output in the terminal. The print keyword can be a useful tool for interacting with users of a Python program, but it’s also a useful debugging tool, as we’ll see later.

    The second part of the print statement is called a string. This is one of many data types in Python. A string is a group of characters, usually composing phrases, sentences, or even paragraphs of human-readable language.

    Strings aren’t strings unless they’re wrapped in quotes.

    In order for Python to recognize a string, you must wrap it in quotation marks. Otherwise, Python will try to evaluate your word, sentence, paragraph, etc. like something else.

    This is very easy to forget. While we can simply type words on our computer and know that these represent human language, Python won’t assume something is a string unless you make it clear.

    Strings must be wrapped in quotation marks, but these can be either double quotes, or single quotes. For example, the following two print statements result in the same string being printed as output.

    print "Hello, world"
    
    print 'Hello, world'
    

    Even though the first has double quotation marks, and the second has single quotes, in both cases, Python will print the string Hello, world as output.

    Strings have some interesting and useful behaviors that can help us use them. These behaviors are called string methods. There are many string methods that you’ll learn as you write more Python. As a first example, you can replace any letter in a string with another letter, using the following syntax:

    >>> "Howdy!".replace("H", "B")
    'Bowdy!'
    

    Other Datatypes

    Besides strings, Python has many other datatypes. The next most common datatype is an integer, or, as it’s more often referred to, int. Integers in Python are essentially just whole numbers. They don’t require any special notation, like strings. If you type a number, Python will simply evaluate it as an integer. For example:

    >>> print 5
    5
    

    The last datatype we’ll cover in this module is a Boolean. The Boolean datatype has only two possible values– True and False. We’ll see lots of uses of boolean types later, but for now, you should understand how to print them:

    >>> print True
    True
    >>> print False
    False
    

    Booleans are not strings.

    It’s important to note that while Boolean values look like strings, since they’re composed of many characters to form a human readable word, they are not the same datatype as strings. We could make a string that, when printed, looks very similar to a Boolean:

    >>> print "True"
    

    True

    Even though the word True was printed as output, the string "True" and the Boolean value True are two completely different values in Python. Read on to learn about a way to prove this difference in between datatypes.

    Calling functions

    Aside from keywords, Python has many other things that it knows how to evaluate in a meaningful way. One such thing is the built-in function called type. Similar to a keyword, a function is something that can produce output. However, unlike keywords, functions require parentheses in order to be evaluated correctly. Functions can also have parameters– variable values that change the function’s output in some way.

    The type function will give you information about the datatype of some value in Python. If you pass a string into the type function, the output is the datatype of the value– a string! If you pass an integer into the type function, the output is the datatype of integer. I bet you can guess the output of the type function when you pass in a Boolean value.

    The type function is nice when you’re not sure when type of thing you have. Knowing a value’s type can be incredibly important, as we’ll see later. Here are some examples of using the type function:

    >>> type("Hello, world")
    <type 'str'>
    
    >>> type(5)
    <type 'int'>
    
    >>> type(53)
    <type 'int'>
    
    >>> type(True)
    <type 'bool'>
    
    >>> type(False)
    <type 'bool'>
    

    Another function

    There’s one more function you should be familiar with- the len function. This function can tell you how long a string is. Check it out:

    >>> len("Hello, world")
    12
    
    >>> len("Time to learn Python!")
    21
    

    Interestingly, you can’t just pass any value into the len function. For example, if you pass a Booelan value in, here’s what happens:

    >>> len(True)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: object of type 'bool' has no len()
    

    A similar thing happens if you pass in an integer:

    >>> len(54)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: object of type 'int' has no len()
    

    Check out the debugging section for more information on Python error messages.

    Practice Section

    Directions

    Create an account on repl.it and start a new coding session here.

    Complete the practice problems below in this repl console. If you’d like to work through the practice in several sittings and save your work in between, make sure you are logged in and saving your work into the repl editor on the left.

    1. Print each of the following strings:
    • "hello world"
    • 'hi there world'
    • "Greetings, world!"
    • "World?? Is it really you? Hi!!!!!!"
    1. Print each of the following integers:
    • 5000
    • 5
    • 7
    1. Print a sentence that says what you had for breakfast this morning.
    2. Print a sentence that about something that you plan to do tomorrow.
    3. Call the type function, passing the string "Howdy, partner" as an argument.
    4. Call the type function, passing the boolean True as an argument.
    5. Call the type function, passing the boolean False as an argument.
    6. Call the type function, passing the integer 88 as an argument.
    7. Call the type function, passing the string "775" as an argument.
    • Notice something interesting about the result?

    Types in Python

    Even if a string contains or is solely composed of a numeric value, it’s still a string!

    1. Print the each of the following strings on the same line, separated by spaces: "apple", "berry", and 'cherry'.
    2. Print the string "Hi, I have", the integer 8, and the string "cats", separated by spaces.
    3. Use the len function in Python to print the length of the following string: "supercalifragilisticexpealidocious".

    Debugging Section

    Directions

    As a programmer, debugging is a fact of life. There are times you write code that Python doesn’t understand. In these cases, Python will display an error message. The more familiar you are with Python’s many error messages, the faster you’ll be at debugging code. But there’s good news: Python’s error messages are incredibly descriptive and helpful in figuring out what the problem is.

    In the following problems, you’ll find code that is invalid or not allowed in some way. Read the code, and see if you can predict what is wrong. When you’re ready, hover over the solution area to reveal the error message that Python shows, along with an explanation of what is going wrong.

    1) What’s wrong with this code?

    >>> len(True)
    

    Not everything has a length.

    While it’s completely valid to use a string as an argument for the len function, as in:

    >>> len("Hello")
    5
    

    it’s not valid to pass a Boolean type into the len function.

    Since there’s no obvious answer for Python to give you for the length of a Boolean, it gives you a helpful message essentially stating that the Boolean thing you passed to len as no length associated with it.

    It’s important to note that even though there are 4 characters that make up the value True, len doesn’t return the integer 4 here. The Boolean type represents True in Python– it’s not simply the string containing the letters "True". It’s a magical, built-in value that has meaning without quotation marks around it.

    So, without further ado, here’s the error message:

    >>> len(True)
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    TypeError: object of type 'bool' has no len()
    

    This is one example of a TypeError– an error that’s raised as a result of data type you’re trying to manipulate in an incorrect way (in this case, you’re trying to treat a Boolean like a string).

    Next time you see a TypeError, make sure you know what kind of thing you’re manipulating in your code. Are you trying to treat an integer like a string? A string like a integer? A boolean like a string? The type function is always there to help if you’re not sure what type of thing you’re working with.

    2) What’s wrong with this code?

    >>> print hello world
    

    Strings need quotes around them.

    In order to print a string, there must be quotes around the string. When you don’t wrap words in quotation marks, Python tries to evaluate the word like it’s a variable, keyword, or a built-in function. In this case, Python is trying to figure out what hello and world mean.

    Here is the error message:

    >>> print hello world
      File "<stdin>", line 1
        print hello world
                        ^
    SyntaxError: invalid syntax
    

    3) What’s wrong with this code?

    >>> print "hi" print "whats up"
    

    One print statement per line

    You can’t put two print statements on the same line. In Python, whitespace (or the space around the actual words that make up your code) is meaningful. Python needs only the right amount of code to be on each line. Similarly, indentation is also meaningful in Python. You’ll see this in action in the next module. For now, note that too much code on the same line results in a SyntaxError, since the syntax that Python is trying to parse is not able to be understood.

    >>> print "hi" print "whats up"
      File "<stdin>", line 1
        print "hi" print "whats up"
                     ^
    SyntaxError: invalid syntax
    

    Final Assignment

    Create a new repl session called module_1_printing.py. In it, print a sentence of your choosing. Then, print the length of that sentence. Do this 3 more times. Next, print the only two boolean values that exist. Lastly, print the integer 54321, and then print its Python type.

    See below for an example of the desired output for the code that you will write.

    Balloonicorn is going to a party this weekend!
    46
    It's a birthday party.
    22
    Balloonicorn needs to make a cake for her friend.
    49
    It will be red velvet.
    22
    True
    False
    54321
    <type 'int'>
    

    Explore

    Do some research about one additional Python string method. Then, create a new repl session called module_1_string_method.py. In it, use a new string method of your choosing. Refer to the .replace() string method if you need to review before conducting your research.

    Check out this section of the Python documentation to get started.