Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

Welcome!: Python - Writing The First Python Code!

The document provides an introduction to writing the first Python code. It discusses printing "Hello World" as the simplest Python program. It also covers writing comments in Python, common errors, and different data types like integers, floats, strings, and Booleans. The document introduces variables and expressions, and provides examples of basic math operations in Python.

Uploaded by

Jeevan TP
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Welcome!: Python - Writing The First Python Code!

The document provides an introduction to writing the first Python code. It discusses printing "Hello World" as the simplest Python program. It also covers writing comments in Python, common errors, and different data types like integers, floats, strings, and Booleans. The document introduces variables and expressions, and provides examples of basic math operations in Python.

Uploaded by

Jeevan TP
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python - Writing the First Python Code!

Welcome!
By the end of this notebook, you will have learned the basics of Python, including writing some basic
commands, understanding object types, and some simple operations!

Table of Contents

First Program in Python


Object Types
Expressions and Variables

In [ ]:

First Program in Python

A statement or expression is an instruction the computer will run or execute. Perhaps the simplest program you
can write is to print a statement in Python.

**Tip**: To *execute* the Python code in the grey code cell below, **click on it and press Shift + Enter**.

In [ ]:

print('Welcome to python tutorial')

After executing the cell above, you should see that Python return the string, Hello World! .

**Tip:** **`print()`** is the **function** that you **executed**, and you *passed in* an **argument** of `'Hello
World!'`.

Python 3

How do we know that Python 3 is running? Take a look in the top-right hand corner of this notebook. You should
see "Python 3"!

Writing comments in Python

In addition to writing code, note that it is customary to comment your code to help describe what it does. Not
only does this help other people understand your code, it can also serve as a reminder to you of what your
code does. (This is especially true when you write some code and then come back to it weeks or months later.)

To write comments in your Python code, use the hash symbol (#) before writing your comment. When you run
the code Python will ignore everything after the # in that line.

In [ ]:

print('Hello Python 101') # this is my comment


# print('Hi')

Great! After executing the cell above, you should notice that "this is my comment did not appeared 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 a hash symbol (#) as well!

Errors in Python

Before continuing, it's important to note when things go wrong in Python, and we cause errors.

There are many kinds of errors, and you do not need to memorize the various types of errors. Instead,
what's most important is know what the error messages mean.

For example, if you spell print as frint, you will get an error message.

In [ ]:

frint("Hello World!")

The error message tells you (1) where the error occurred, and (2) what kind of error it was. Here, Python
attempted to run the function frint , but could not determine what frint -- since it is undefined.

Does Python know the error in the script before you run it?
No, Python is naive! Python will try to run the code line-by-line, and it will stop if it runs into an error.

In [ ]:

print("This will be printed")


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

More on errors later on in this course!


Exercise: Your First Program

Using the print() function, print out the phrase: "hello world"

In [ ]:

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

Click here for the solution

Print out the phrase: "Hello World" and comment it with the phrase "printing Hello World" all in one line
of code

In [ ]:

# Write your code below

Click here for the solution

Types of objects in Python

We can have many different object types in Python, let's start with strings, integers and floats.

Anytime you write words (text) in Python, you're using character strings (strings for short). Numbers, on the
other hand, depend: numbers can be integers (like -1, 0, 100) or floats, which are real numbers (like 3.14,
-42.0).

The following chart summarizes three data types for the last examples, the first column indicates the expression
the second column indicates the data type
In [ ]:

11 #integer

In [ ]:

2.14 #float

In [ ]:

"Hello Python 101" #character string

We can see the actual data type in python by using the type() command

In [4]:

type(11)

Out[4]:

int

In [5]:

type(2.14)

Out[5]:

float

In [6]:

type("Hello Python 101")

Out[6]:

str

Using the type() function, check the object type of 12.0 ?

In [ ]:

# Write your code below

Integers

Here are some integers, integers can be negative or positive:


We can verify some of the above examples using the type command:

In [ ]:

type(-1)

In [ ]:

type(4)

In [ ]:

type(0)

Floats

Floats are real numbers; they include the integers but also "numbers in-between the integers". Consider the
numbers between 0 and 1 we can select numbers in-between them, these numbers are floats.

Similarly, consider the numbers between 0.5 and 0.6. We can select numbers in-between them, these are floats
as well. We can continue the process, zooming in for different numbers, of course, there is a limit, but it is quite
small.

We can verify some of the above examples using the type command:

In [ ]:

type(1.0)

In [ ]:

type(0.5)

In [ ]:

type(0.56)

Converting from one object type to a different object type

You can change the type of the object in Python; this is called typecasting.

For example, you can convert an integer into a float, as in 2 to 2.0.


In [3]:

type('2.2') #verify that this is an integer

Out[3]:

str

Converting to float:

In [7]:

float(2)

Out[7]:

2.0

In [8]:

type(float(2))

Out[8]:

float

Converting to integer:

Nothing really changes. If you cast a float to an integer, you must be careful. For example, if you cast the float
1.1 to 1 but we will lose some information :

In [9]:

int(1.1)

Out[9]:

Converting from strings to integers/floats:

If a string contains an integer value, you can convert it to an integer:

In [ ]:

type('1')

In [ ]:

int('1')
You can also convert strings containing float values into float objects

In [ ]:

float('1.2')

However, if we attempt to convert a string that contains a non-numerical value, we get an error:

In [ ]:

int("A")

Converting to strings:

You can convert an int to a string:

In [ ]:

str(1)

You can convert a float to a string

In [ ]:

str(1.2)

Boolean

Boolean is another important type in Python; a Boolean can take on two values. The first value is true, just
remember we use an uppercase T:

In [ ]:

True

Boolean values can also be false, with an uppercase F:

In [ ]:

False

Using the type command on a Boolean value we obtain the term bool, this is short for Boolean

In [ ]:

type(True)
In [ ]:

type(False)

If we cast a Boolean true to an integer or float we will get a 1, if we cast a Boolean false to an integer or float. If
we get a zero if you cast a 1 to a boolean, you get a true similarly, if you cast a 0 to a Boolean you get a false.

In [ ]:

int(True)

In [ ]:

bool(1)

In [ ]:

bool(0)

In [ ]:

float(True)

Quiz on types

What is the type of the result of: 6 / 2

In [ ]:

type(6/2)

Click here for the solution

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

In [ ]:

14//5

Click here for the solution

Expression and Variables

Expressions
Expressions are operations that Python performs. For example, basic arithmetic operations like adding multiple
numbers.

In [ ]:

43 + 60 + 16 + 41

We can perform operations such as subtraction using the subtraction sign. In this case the result is a negative
number.

In [ ]:

50 - 60

We can use multiplication using an asterisk:

In [ ]:

5 * 5

We can also perform division with the forward slash

In [ ]:

25 / 5

In [10]:

25 / 6

Out[10]:

4.166666666666667

We can use the double slash for integer division, where the result is rounded

In [11]:

25//5

Out[11]:

In [12]:

d = 25//6
d

Out[12]:

What is 160 min in hours?


at s 60 ou s

In [ ]:

Click here for the solution

Python follows mathematical conventions when performing mathematical expressions. The following operations
are in different order. In both cases Python performs multiplication, then addition to obtain the final result.

In [ ]:

2 * 60 + 30

The expressions in the parentheses are performed first. We then multiply the result by 60, the result is 1920.

In [ ]:

(30 + 2) * 60

[Tip] Summary

You can do a variety of mathematical operations in Python including:


addition: **2 + 2**
subtraction: **5 - 2**
multiplication: **3 \* 2**
division: **4 / 2**
exponentiation: **4 \*\* 2**

Variables

We can also store our output in variables, so we can use them later on. For example:

In [ ]:

x = 43 + 60 + 16 + 41

To return the value of x , we can simply run the variable as a command:

In [ ]:

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

y = x / 60
y

If we save something to an existing variable, it will overwrite the previous value:

In [ ]:

x = x / 60
x

It's good practice to use meaningful variable names, so you don't have to keep track of what variable is what:

In [ ]:

total_min = (43 + 42 )
total_min

In [ ]:

total_hr = total_min / 60
total_hr

You can put this all into a single expression, but remember to use round brackets to add together the album
lengths first, before dividing by 60.

In [ ]:

total_hr = (43 + 42 + 57) / 60 # get total hours in a single expression


total_hr

[Tip] Variables in Python

As you just learned, you can use **variables** to store values for repeated use. Here are some more
**characteristics of variables in Python**:
variables store the output of a block of code
variables are typically assigned using **=** (as in **x = 1**)

Quiz on Expression and Variables in Python

What is the value of x ?


x=3+2*2

In [ ]:

Click here for the solution

What is the value of y ?


y = (3 + 2) * 2

In [ ]:

Click here for the solution

What is the value of z ?


z=x+y

In [ ]:

Click here for the solution

[Tip] Saving the Notebook

Your notebook saves automatically every two minutes. You can manually save by going to File > Save
and Checkpoint. You can come back to this notebook anytime by clicking this notebook under the
"Recent Notebooks" list on the right-hand side.

[Tip] Notebook Features

Did you know there are other notebook options? Click on the > symbol to the left of the notebook:

You might also like