Python - Writing Your First Python Code!: (Https://cognitiveclass - Ai/)
Python - Writing Your First Python Code!: (Https://cognitiveclass - Ai/)
ai/)
(https://cocl.us/topNotebooksPython101Coursera)
Table of Contents
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 .
In [2]:
[Tip:] print() is a function. You passed the string 'Hello, Python!' as an argument to instruct
Python on what to print.
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:
In [3]:
import sys
print(sys.version)
[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.
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.
In [4]:
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:
In [5]:
frint("Hello, Python!")
--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
<ipython-input-5-313a1769a8a5> in <module>
1 # Print string as error message
2
----> 3 frint("Hello, Python!")
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:
In [7]:
print("Hello, Python!")
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:
In [11]:
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!
In [13]:
hello, world!
Now, let's enhance your code with a comment. In the code cell below, print out the phrase: Hello, world!
and comment it with the phrase Print the traditional hello world all in one line of code.
In [14]:
Hello world
Python is an object-oriented language. There are many different types of objects in Python. Let's start with
the most common object types: strings, integers and floats. Anytime you write words (text) in Python, you're
using character strings (strings for short). The most common numbers, on the other hand, are integers (e.g.
-1, 0, 100) and floats, which represent real numbers (e.g. 3.14, -42.0).
# Integer
11
In [ ]:
# Float
2.14
In [ ]:
# String
You can get Python to tell you the type of an expression by using the built-in type() function. You'll notice
that Python refers to integers as int , floats as float , and character strings as str .
In [16]:
# Type of 12
int(12)
Out[16]:
12
In [18]:
float(12.2)
Out[18]:
12.2
In [19]:
Out[19]:
In the code cell below, use the type() function to check the object type of 12.0 .
In [21]:
# Write your code below. Don't forget to press Shift+Etypenter to execute the cell
type(12)
Out[21]:
int
Integers
Here are some examples of integers. Integers can be negative or positive numbers:
We can verify this is the case by using, you guessed it, the type() function:
In [ ]:
type(-1)
In [ ]:
type(4)
In [ ]:
type(0)
Floats
Floats represent real numbers; they are a superset of integer numbers but also include "numbers with
decimals". There are some limitations when it comes to machines representing real numbers, but floating
point numbers are a good representation in most cases. You can learn more about the specifics of floats for
your runtime environment, by checking the value of sys.float_info . This will also tell you what's the
largest and smallest number that can be represented with them.
Once again, can test some examples with the type() function:
In [22]:
Out[22]:
float
In [23]:
type(0.5)
Out[23]:
float
In [24]:
type(0.56)
Out[24]:
float
In [25]:
sys.float_info
Out[25]:
You can change the type of the object in Python; this is called typecasting. For example, you can convert an
integer into a float (e.g. 2 to 2.0).
type(2)
Out[26]:
int
In [27]:
# Convert 2 to a float
float(2)
Out[27]:
2.0
In [28]:
type(float(2))
Out[28]:
float
When we convert an integer into a float, we don't really change the value (i.e., the significand) of the number.
However, if we cast a float into an integer, we could potentially lose some information. For example, if we
cast the float 1.1 to integer we will get 1 and lose the decimal information (i.e., 0.1):
In [ ]:
int(1.1)
Sometimes, we can have a string that contains a number within it. If this is the case, we can cast that string
that represents a number into an integer using int() :
In [29]:
int('1')
Out[29]:
But if you try to do so with a string that is not a perfect match for a number, you'll get an error. Try the
following:
In [ ]:
int('1 or 2 people')
You can also convert strings containing floating point numbers into float objects:
In [30]:
float('1.2')
Out[30]:
1.2
[Tip:] Note that strings can be represented with single quotes ( '1.2' ) or double quotes ( "1.2" ), but
you can't mix both (e.g., "1.2' ).
If we can convert strings to numbers, it is only natural to assume that we can convert numbers to strings,
right?
In [31]:
str(1)
Out[31]:
'1'
And there is no reason why we shouldn't be able to make floats into strings as well:
In [32]:
str(1.2)
Out[32]:
'1.2'
Boolean is another important type in Python. An object of type Boolean can take on one of two values:
True or False :
In [ ]:
# Value true
True
Notice that the value True has an uppercase "T". The same is true for False (i.e. you must use the
uppercase "F").
In [ ]:
# Value false
False
When you ask Python to display the type of a boolean object it will show bool which stands for boolean:
In [ ]:
# Type of True
type(True)
In [ ]:
# Type of False
type(False)
We can cast boolean objects to other data types. If we cast a boolean with a value of True to an integer or
float we will get a one. If we cast a boolean with a value of False to an integer or float we will get a zero.
Similarly, if we cast a 1 to a Boolean, you get a True . And if we cast a 0 to a Boolean we will get a False .
Let's give it a try:
In [ ]:
int(True)
In [ ]:
# Convert 1 to boolean
bool(1)
In [ ]:
# Convert 0 to boolean
bool(0)
In [ ]:
float(True)
Exercise: Types
In [ ]:
# Write your code below. Don't forget to press Shift+Enter to execute the cell
What is the type of the result of: 6 // 2 ? (Note the double slash // .)
In [ ]:
# Write your code below. Don't forget to press Shift+Enter to execute the cell
Expressions
Expressions in Python can include operations among compatible types (e.g., integers and floats). For
example, basic arithmetic operations like adding multiple numbers:
In [ ]:
43 + 60 + 16 + 41
We can perform subtraction operations using the minus operator. In this case the result is a negative number:
In [ ]:
50 - 60
In [ ]:
5 * 5
In [ ]:
25 / 5
In [ ]:
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:
In [ ]:
25 // 5
In [ ]:
25 // 6
Exercise: Expression
Let's write an expression that calculates how many hours there are in 160 minutes:
In [ ]:
# Write your code below. Don't forget to press Shift+Enter to execute the cell
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).
In [ ]:
# Mathematical expression
30 + 2 * 60
And just like mathematics, expressions enclosed in parentheses have priority. So the following multiplies 32
by 60.
In [ ]:
# Mathematical expression
(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:
In [ ]:
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:
In [ ]:
We can also perform operations on x and save the result to a new variable:
In [ ]:
# Use another variable to store the result of the operation between variable and value
y = x / 60
y
If we save a value to an existing variable, the new value will overwrite the previous value:
In [ ]:
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:
In [ ]:
In [ ]:
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.
In [ ]:
# Complicate expression
If you'd rather have total hours as an integer, you can of course replace the floating point division with integer
division (i.e., // ).
# Write your code below. Don't forget to press Shift+Enter to execute the cell
In [ ]:
# Write your code below. Don't forget to press Shift+Enter to execute the cell
In [ ]:
# Write your code below. Don't forget to press Shift+Enter to execute the cell
(https://cocl.us/bottemNotebooksPython101Coursera)
Copyright © 2018 IBM Developer Skills Network. This notebook and its source code are released under the
terms of the MIT License (https://cognitiveclass.ai/mit-license/).