Day 1
Date: 01/06/2020
Time: 12:00 PM - 3:00 PM
Location: Hostos Community College - A-534
Introductions
Hi everyone! This is Day 1 of the Python Boot Camp. So we can just kind of jump right into it. Based on the results from assignment #0, it looks like everyone
has had at least some programming experience which is great. Most of you have programmed in C++, which is awesome. I'll likely be making some comparisons to C++
a little later on since that's the language most of you are familiar with.
Hopefully by now you've downloaded both Python and Git. I'll likely make a seperate walk through for Git sometime over the weekend, but the notes on this site will
mostly focus on Python for now.
A little bit about Python
So Python is a high level programming language that was released back in 1991. This makes the language almost 30 years old (wow, time really flies).
It's an interpretted language meaning that it executes the code directly (without needing to compile). Python executes the program and translates each line
into a sequence of small subroutines, then into machine code for your computer to read. C++ is a compiled language, which means that the code has to be compiled into a
program (.exe for windows, .out for linux, etc). This program is already written in machine code.
The differences don't stop there! Usually interpretted language are slower than compiled languages. This difference in speed used to be a pretty big deal back in the day, however,
with processor speeds increasing dramatically within the last 10-15 years, the speed of the languages are beginning to become irrelevant in many use cases.
Interpretted languages are often much easier to debug as the interpreter often shows you exactly which line an error occured and what the exact error is. Sometimes, a compiled language
can output a somewhat comfusing compilation error. I'm sure you've asked yourself (probably more than once): "what the hell does this mean?" when hitting a compilation error in C++.
So what makes Python so popular? Well there are several things: it's easy to learn, and there is a massive amount of packages, modules and libraries available.
These packages are often very well defined and documented. A lot of these packages are also very funny. I mean let's take the package silverware
as an example. It provides
additional functionality for another package called BeautifulSoup
. These names are not random, as we'll see later on in the course (we'll be using BeautifulSoup
to build a
web-scrapper). In additional to this, there's also PIP
(pip installs packages) that makes it very easy to obtain packages at any time.
So enough about Python, let's talk about how to use Python.
Console Input/Output and Variables
Outputting in Python is really easy. There's a built in function to python called print()
that just allows you to print anything you want into
the console. As we go through the boot camp, we'll see different ways that it can help us, and format out print outs. But for now, let's try our first python script:
hello_world.py
.
# Hello world script in Python (this is a comment by the way)
print("hello world!")
There's really nothing to it! For those who come from Python 2.x, in Python 3.x, you need the parenthesis.
Taking user input from the console is just as simple, there's a built in function in Python called input()
. The argument of the input function is the
prompt that you want to include. The input function must be assigned to a variable
to do anything useful with it (unless you're asking a rhetorical question).
So let's take an example: let's say you want to ask the user for their name, and age. This is how you would use the input()
function to do so.
# User inputs
user_name = input("Enter your name:") # asking for the user's name
user_age = input("Enter your age:") # asking for the user's age
input()
function takes the user input as a string
type. Which means that if you
want to perform any type of mathematical operation with the user's age, you must first make it into a numerical type. We'll talk about how to do that in the next section.
Python is a dynamically-typed language (sometimes referred to as loosely-typed). This means that when declaring variables, you do not have to declare the variable type
before assigning it a value. It also means that you can change the variable definition as you please.
Let's look at the following example:
# Variable assignment
x = 5 # this is an integer
x = "hello" # you can easily reassign it to a string
x = True # now it's a boolean
x
, without any issues despite assigning/reassigning it to different data types. Let's talk about data types next.
Data Types
There are many data types supported by Python, but in this section we're going to focus on only 4 of the basic ones. As the boot camp goes on, we'll be introducing more advanced data types. So the 4 that we're going to focus on today are:
- Integers (
int
) - Floating Point Numbers (
float
) - Strings (
str
) - Booleans (
bool
)
Integers - int
- These have the same definition across all programming languages, and mathematics: They are positive and negative whole numbers and zero. Integers are a numeric type.
Floating Point Numbers - float
- These are positive and negative numbers that have the decimal point. When a floating point number is converted to an integer, the number is truncated
at the decimal point. floats
are a numeric type.
Strings - str
- These are non-numeric types of any alphanumerical, and special characters. You can see the full list by looking at an ASCII table. str
types are NOT a numerical type.
Booleans - bool
- These are logical types representing: True
or False
. Note that the first letter is capitilized. True
can be represented by the
value of 1, False
can be represented by the number 0. However, usually it is more clear to write True
or False
.
If you're ever in doubt about the data type of any variable you can easily find out by using the type()
function. The input to the type()
function is a variable or value, and it returns the data type
of the variable or value in question. It even works with instances
. We'll talk about that later on in the boot camp when we reach object oriented programming.
For now, let's take a quick example and see how we can use the type()
function.
# Using the type() function
x = 5
print(type(x)) # this will print int
x = "hello"
print(type(x)) # this will print str
x = True
print(type(x)) # this will print bool
Python allows us to cast some data types to another. In other words, we can easily change the data type of a variable or value and change it to fit the shape of another. This process is called type conversion
(in C/C++, this is called type casting
, but it's the same concept).For example, let's convert a floating point number to an integer. Remember that when converting a float
to an int
that the number will truncate at the decimal point.
# type conversion
g = 9.81
print(type(g)) # this will print float
g = int(g)
print(g) # this will print 9 (the .81 was truncated)
print(type(g)) # this will print int
str
. However, not all str
can be converted to a numerical type. For example,
you can convert the number string
"5", into an int
or float
. However, if your string was "Python boot camp is fun"
you can not convert it to a string.
Below is a small table of some possible type conversion combinations between
str
, int
and float
types.
Operators
Operators in Python are pretty much the same as they are in C++, there are very few differences in the basic operations. Instead of going through each of the basic operators individually, I made a small table of the basic ones for now. We may use different operators we go, but I'll explain them to you as we use them.
Conditional Statements
Since many of you have programmed before, you understsand the importance of conditonal statements. Unlike C++ and many languages, tabbing in Python is extremely
important. The form of the if-else
statement below is how it should be written always. The tab after the if
statement tells the Python interpreter that the
code is within that if
. This is the same for else
, while
, for
and even function definitions as we will see later.
# Basic if-else statement format
if
expression :
do something
else:
do something else
else
.
Boolean logic is also very important. By now, you probably understand a bit of boolean logic. The difference in and
and or
.
In C++, if you recall, the symbol for and was &&
and the symbol for or was ||
.
Well, luckily for us, Python decided that was awkward and confusing, so we can literally just wrote and
for and and we can use or
for or.
Python makes things pretty straight foward.
Let's do a quick example just to hammer it home. Let's say we have a variable, x
. If x
is divisible by 2 and 3, we will add 1. Else, we will subtract 1.
To write this code, we can simply write the following code:
if x % 2 == 0 and x % 3 == 0:
x += 1
else:
x -= 1
The else-if statement is equally as easy, it is denoted by elif
. THe general structure of this is as follows:
# Basic if/else-if/else statement format
if
expression 1 :
do thing 1
elif
expression 2 :
do thing 2
else:
do something
Loops
Let's talk about while
loops first. They are slightly easier to use and we will be using them a lot. They the same structure across most programming languages,
the only thing you have to worry about when using loops in Python are the tabs and the colon (don't forget those)!
Here is the general format of a while loop:
while
expression is true :
do something
x
that starts at 0. Then you want to keep incrementing the value of x
until it reaches say ... 100. We can use a while loop to achieve this!
x = 0
while x < 100:
x += 1
Let's build off this while we're here. Let's make a timer for us. Nowadays, we use the timer on our phones but let's just pretend for a minute. Let's pretend we don't have a phone just a computer with Python installed. Python has a package called
time
that allows us to use the system time (on our computers). Let's build a timer that counts down from
10 seconds then exits. Let's create a file and call it
10s_timer.py
. To import any package in function, we can use import
name of the package. There are different
ways of accomplishing this, and we will go over them in more detail later on. Then we can use a while
loop for the rest of it.
# 10s_timer.py
import time
counter = 10
while counter >= 0:
counter -= 1
time.sleep(1) # sleep for 1 second
print(counter)
There's also the for
loop! The for
loop is also very important, and we will be writing for
loops differently based on what we are doing.
Before we can talk about the for loop, we have to talk about the range()
function in Python.
The range()
function allows us to specify well ... a range of numbers. The range()
function has up to 3 inputs:
start, stop
and increment
. The only one that is required is the stop
number. The default value of start
is 0 and the default
value of increment
is 1. The range()
function will give you numbers from start to stop - 1. For example, if you specify range(5,10)
it will give you
the values: 5,6,7,8,9.
Here it is in code:
range(10) # returns 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(2,5) # returns 2, 3, 4
range(2,12,2) # returns 2, 4, 5, 6, 8, 10
range(5,0) # returns 5, 4, 3, 2, 1
Now let's loop back around to for
loops. It's often nice to use the range()
function to tell your for
where to start and stop.
The best way to show this is by example, so let's write our timer script again. Let's have a for loop that prints out the numbers from 0 to 9.
for number in range(0,10):
print(number)