SYildiz
1/25/2019 - 11:00 AM

1.Python 101 - First Code

Welcome! This notebook will teach you the basics of the Python programming language. Although the information presented here is quite basic, it is an important foundation that will help you read and write Python code. By the end of this notebook, you'll know the basics of Python, including how to write basic commands, understand some basic types, and how to perform simple operations on them.

Table of Contents


Say "Hello" to the world in Python

When learning a new programming language, it is customary to start with an "hello world" example. As simple as it is, this one line of code will ensure that we know how to print a string in output and how to execute code within cells in a notebook.


[Tip]: To execute the Python code in the code cell below, click on the cell to select it and press Shift + Enter.

print('Hello, Python!')
Hello, Python!

After executing the cell above, you should see that Python prints Hello, Python!. Congratulations on running your first Python code!


[Tip:] print() is a function. You passed the string 'Hello, Python!' as an argument to instruct Python on what to print.

What version of Python are we using?

There are two popular versions of the Python programming language in use today: Python 2 and Python 3. The Python community has decided to move on from Python 2 to Python 3, and many popular libraries have announced that they will no longer support Python 2.

Since Python 3 is the future, in this course we will be using it exclusively. How do we know that our notebook is executed by a Python 3 runtime? We can look in the top-right hand corner of this notebook and see "Python 3".

We can also ask directly Python and obtain a detailed answer. Try executing the following code:

import sys
print(sys.version)
3.6.6 | packaged by conda-forge | (default, Oct 12 2018, 14:43:46) 
[GCC 7.3.0]

[Tip:] sys is a built-in module that contains many system-specific parameters and functions, including the Python version in use. Before using it, we must explictly import it.

Writing comments in Python

In addition to writing code, note that it's always a good idea to add comments to your code. It will help others understand what you were trying to accomplish (the reason why you wrote a given snippet of code). Not only does this help other people understand your code, it can also serve as a reminder to you when you come back to it weeks or months later.

To write comments in Python, use the number symbol # before writing your comment. When you run your code, Python will ignore everything past the # on a given line.

print('Hello, Python!') # This line prints a string
# print('Hi')
Hello, Python!

After executing the cell above, you should notice that This line prints a string did not appear in the output, because it was a comment (and thus ignored by Python).

The second line was also not executed because print('Hi') was preceded by the number sign (#) as well! Since this isn't an explanatory comment from the programmer, but an actual line of code, we might say that the programmer commented out that second line of code.

Errors in Python

Everyone makes mistakes. For many types of mistakes, Python will tell you that you have made a mistake by giving you an error message. It is important to read error messages carefully to really understand where you made a mistake and how you may go about correcting it.

For example, if you spell print as frint, Python will display an error message. Give it a try:

frint("Hello, Python!")

The error message tells you:

  1. where the error occurred (more useful in large notebook cells or scripts), and
  2. what kind of error it was (NameError)

Here, Python attempted to run the function frint, but could not determine what frint is since it's not a built-in function and it has not been previously defined by us either.

You'll notice that if we make a different type of mistake, by forgetting to close the string, we'll obtain a different error (i.e., a SyntaxError). Try it below:

print("Hello, Python!)

Does Python know about your error before it runs your code?

Python is what is called an interpreted language. Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution. In contrast, Python interprets your script line by line as it executes it. Python will stop executing the entire program when it encounters an error (unless the error is expected and handled by the programmer, a more advanced subject that we'll cover later on in this course).

Try to run the code in the cell below and see what happens:

print("This will be printed")
print("This will cause an error")
print("This will NOT be printed")
This will be printed
This will cause an error
This will NOT be printed

Exercise: Your First Program

Generations of programmers have started their coding careers by simply printing "Hello, world!". You will be following in their footsteps.

In the code cell below, use the print() function to print out the phrase: Hello, world!

# Write your code below and press Shift+Enter to execute 




Double-click here for the solution.

What is the type of the result of: 6 // 2? (Note the double slash //.)


Double-click here for the solution.

Expression and Variables

Expressions

Expressions in Python can include operations among compatible types (e.g., integers and floats). For example, basic arithmetic operations like adding multiple numbers:

43 + 60 + 16 + 41

We can perform subtraction operations using the minus operator. In this case the result is a negative number:

50 - 60

We can do multiplication using an asterisk:

5 * 5

We can also perform division with the forward slash:

25 / 5
25 / 6

As seen in the quiz above, we can use the double slash for integer division, where the result is rounded to the nearest integer:

25 // 5
25 // 6

Let's write an expression that calculates how many hours there are in 160 minutes:


Double-click here for the solution.

Python follows well accepted mathematical conventions when evaluating mathematical expressions. In the following example, Python adds 30 to the result of the multiplication (i.e., 120).

 30 + 2 * 60

And just like mathematics, expressions enclosed in parentheses have priority. So the following multiplies 32 by 60.

(30 + 2) * 60

Variables

Just like with most programming languages, we can store values in variables, so we can use them later on. For example:

x = 43 + 60 + 16 + 41

To see the value of x in a Notebook, we can simply place it on the last line of a cell:

x

We can also perform operations on x and save the result to a new variable:

y = x / 60
y

If we save a value to an existing variable, the new value will overwrite the previous value:

x = x / 60
x

It's a good practice to use meaningful variable names, so you and others can read the code and understand it more easily:

total_min = 43 + 42 + 57 # Total length of albums in minutes
total_min
total_hours = total_min / 60 # Total length of albums in hours 
total_hours

In the cells above we added the length of three albums in minutes and stored it in total_min. We then divided it by 60 to calculate total length total_hours in hours. You can also do it all at once in a single expression, as long as you use parenthesis to add the albums length before you divide, as shown below.

total_hours = (43 + 42 + 57) / 60  # Total hours in a single expression
total_hours

If you'd rather have total hours as an integer, you can of course replace the floating point division with integer division (i.e., //).

Quiz on Expression and Variables in Python

What is the value of x where x = 3 + 2 * 2


Double-click here for the solution.

What is the value of y where y = (3 + 2) * 2?


Double-click here for the solution.

What is the value of z where z = x + y?

Double-click here for the solution.