Introduction to Python

Introduction to Python

In this course, you will learn the basics of variables, strings, loops, functions, expressions, and statements, and how to use Boolean logic to generate and execute conditional statements. You will also learn the fundamentals of object-oriented programming and gain a preliminary understanding of objects, classes, and modules.

By the end of this course, you should be able to:

Lesson 1 - Python Basics

What is Python?

  • Python is a programming language developed in the 1990s by a Dutch programmer named Guido van Rossum
  • Van Rossum named it after Monty Python’s Flying Circus, a British comedy show from the 1970s
  • Python is known for readability and simpler syntax. This means you can express concepts in fewer lines of code than in Java or C++
  • NASA, Google, YouTube, and Dropbox use Python. Part IV of the popular computer game Civilization was written in Python. 
  • Biotech and other life science companies often use Python to run Big Data projects
  • Guido van Rossum has worked at Dropbox in San Francisco since 2013

Setting up Python

Getting Started

Let’s get started

In Windows 8 or 10, go to the Start menu and either type IDLE (Python 3.6.2 or latest version) in the search box or browse to find the program in the Start Menu.

In Mac, navigate to Go => Applications and open the IDLE (Python 3.6.2 or latest version) folder.

A coding text box (IDLE, the standard Python shell) should pop up. This will be our work space for the entire Introduction to Python course. You should be able to keep the small Python shell window open as you move through this course.

Later, as you develop your skills as a coder and want to run large-scale projects, you would select a bigger and more powerful workspace, an integrated development environment, called IDE for short. There are many IDEs available, some free and some costly. PyCharm is one popular free downloadable IDE.  

Running Code

Running your first line of code

Begin writing at the prompt: >>>

In Python, we use the word print to give a command, or call. 

Using the IDLE Editor, tell your computer to say "hello world" like this:

>>> print (“hello world”)

Try a few other phrases. The text between the parentheses and in quotes is called the expression.

Strings

What are strings?

A string is simply a sequence of characters. These characters can be text or symbols.  

Do you remember how we asked the computer to say "hello world"? 

That is a string - a literal string, a string without variables or values.

Let's write a string that makes your computer say its name:

>>> print ("my name is  Maria")

Enter the name you'd like to give your computer.  

Rules for Writing Strings

How to write strings

When writing strings, make sure to always include the following:

1) the command (print)

2) the parentheses

3) quotes, which can be single, double, or triple as long as you're consistent

Multiple Strings

Using Multiple Strings

We use computer commands to tell our computer to do something for us, essentially to run a program that accomplishes some task. This program can be as simple as using literal strings to make your computer tell a joke.

Type this into your IDLE Editor:

>>> question = "What do you call an alligator in a vest?"

>>> answer = "An investigator"

Now, run your program:

>>> print (question)

>>> print (answer)

What happens?

Variables

What are variables?

Variables are names that refer to values located in the computer’s memory. You use = to assign a value to a variable. 

Variables are just names. Assignment just attaches a name to the information that is one of the data types. It is a reference to the information rather than the information itself – like a label, or a sticky note!

What happens when you type the following?

>>> a = 7

>>> print(a)

We are assigning the value 7 to the name a.

Now what happens when you type this?

>>>  b=a

>>> print(b)

We are making the b also stick to the data type integer with a value of 7. The value of b is the same as a, and both are sticky notes that assign values to the information in memory – which is basically a name (a or b) with a value attached to it (7 or 7).

Rules for Variables

Defining variables

In our alligator joke, what are the variables and what are the values?

>>> question = "What do you call an alligator in a vest?"

>>> answer = "An investigator"

>>> print (question)

>>> print (answer)

Variables - question, answer

Values = "What do you call an alligator in a vest?", "An investigator."


Rules for variables

Variable names cannot begin with a digit, only with a letter or an underscore.  

And variable names can only contain these characters:

Lowercase letters (a – z)

Uppercase letters (A – Z)

Digits (0 – 9)

Underscore (_)


Working with Variables

Using variables

Let’s say we have 50 quarters we found, 30 quarters that our grandmother gave us for good luck, and 20 quarters that magically disappear every time we sneeze. 

How would we write a program that changes the total number of quarters every time we sneeze?


Try writing this program in IDLE Editor:

>>> found_quarters = 50

>>> good_luck_quarters = 30

>>> disappearing_quarters = 20

Our equation looks like this:

>>> found_quarters + good_luck_quarters – disappearing_quarters

Understanding Variables

Understanding variables

What are the variables (names) in our Quarters program?

What are the values?

Why do we need to use underscores when working with variables?

Syntax Errors

Understanding variables

variables =  found quarters, good luck quarters, disappearing quarters

values = 50, 30, 20

Why underscores?

Python didn't know what to do with the two words "found quarters" - they are not linked together as a single variable. We made a syntax error.

Syntax is the correct arrangement of words and symbols in a program. 

Reserved Words

Keywords

In Python, there are keywords or "reserve" words that cannot be used as ordinary identifiers, meaning that Python will try to process the information as a command or function rather than a descriptive value. The following is a list of "reserved" words in Python.

Reserve words in Python

False, none, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.

Strings and Variables

Using strings with variables

So far we’ve talked about strings without variables - literal strings.

Now let’s incorporate variables inside the strings.

We do this by inserting - or "embedding" - values and changing the structure of the code to incorporate multiple outcomes.

Assigning values

Let’s say we want to create a program that calculates the score we got in a video game.  

First, we need a variable.

What is the variable we are assigning a value to?

In this example, the variable is the score we got in a video game.  

Let's call the variable myscore.

What is the value we should assign to the variable, to start? How about 50?

>>> myscore = 50

Using strings with variables

So far we’ve talked about strings without variables - literal strings.

Now let’s incorporate variables inside the strings.

We do this by inserting - or "embedding" - values and changing the structure of the code to incorporate multiple outcomes.

Assigning values

Let’s say we want to create a program that calculates the score we got in a video game.  

First, we need a variable.

What is the variable we are assigning a value to?

In this example, the variable is the score we got in a video game.  

Let's call the variable myscore.

What is the value we should assign to the variable, to start? How about 50?

>>> myscore = 50

Creating Messages

Creating a message

Let's create a string that expresses what we want to say about the score. This string is called the message.

The message will use a placeholder for the changing values. Each time the score changes, the message changes, too. 


In Python, we use % as a placeholder and a letter, in this case s, to track the changing value.

This tells Python to replace the %s with the value stored in the variable myscore.

Combining Strings and Variables

Running the program

Your code in IDLE should look like this:

>>> myscore = 50

>>> message = "I scored %s points!"

>>> print (message % myscore)

In IDLE Editor, try changing the value of the variable (myscore).

Using Multiple Variables

Multiple Variables

We can add another video game player - another variable - by simply inserting a second variable. We can name this player Sarah and her variable sarahscore.

Let's give Sarah 48 points to start. 

>>> sarahscore = 48

Let's call the second version of the message relating to Sarah message2.

>>> myscore = 50

>>> sarahscore = 48

>>> message = "I scored %s points"

>>> message2 = "Sarah scored %s points"

>>> print (message % myscore)

I scored 50 points

>>> print (message2 % joescore)

Sarah scored 48 points

Combining Strings

Combining Strings

But what if we want Python to tell us what Sarah and I scored all at once?

In Python, strings are "immutable" which means they cannot be changed once created. We need to build new strings each time and then combine them.

To simplify this process of combining strings, we use the + operator. 

>>> myscore = 50

>>> sarahscore = 48

>>> message = "I scored %s points"

>>> message2 = "Sarah scored %s points"

print (message % myscore + message2 % sarahscore)

Try this in IDLE Editor and see what happens. 

Review Exercise 1

Exercise 1

Using IDLE Editor, write a program that makes your computer tell you it is going to snow tomorrow.


Exercise 2

Using IDLE Editor, write a program that tells this joke:

What's the difference between a piano and a fish?

You can't tuna fish.


Exercise 3

What is the symbol we use to note that a value is changing? 

Using IDLE Editor, write a message that shows the following video game players and scores:

Sam = 30, Arlene = 59, Joy = 72

Exercise 1

Using IDLE Editor, write a program that makes your computer tell you it is going to snow tomorrow.

Review Exercise 1 - Answer

Heading 1 text goes here

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Review Exercise 2

Exercise 2

Using IDLE Editor, write a program that tells this joke:

What's the difference between a piano and a fish?

You can't tuna fish.

Review Exercise 2 - Answer

Review Exercise 3

Exercise 3

Using IDLE Editor, write a message that shows the following video game players and scores:

Sam = 30, Arlene = 59, Joy = 72

Review Exercise 3 - Answer

Lesson II - Python Coding

Python Data Types and Operators

Data types 

strings - any combination of text characters (letters, numbers, symbols)

variables - names attached to actual data

booleans - true or false values

integers - whole numbers

floats - fractional numbers with decimal points



+ - * / Operators

As long as the data types are the same on both sides of the equation, you can add, subtract, multiply, and divide values in Python, for example:

>>> 5 * 5

25

To calculate exponents, you simply use two asterisks:

>>> 4 ** 2

16

>>> 2 ** 3

8




Floor division

If we run this in IDLE Editor

>>> a = 100

>>> b = 3

>>> a / b

33.333333333333336

Python gives us a (floating point) fractional number. 

But if we want Python to round up, we can use Floor division - //:

>>> a = 100

>>> b = 3

>>> a // b

33


.

Fundamental Code Writing Rules in Python

Basic code writing rules in Python

  • You do not have to end each line with a parentheses or brackets, as you do in other computer programs.
  • You create a new block of instructions by indenting.
  • Since Python is not relying on brackets, it needs to interpret white space. Be careful about how you are using spaces when writing code.
  • When indenting to create a new line of instruction, use the space bar or tab – but do not use both at the same time. Choose one or the other to indent. The normal count is 4 spaces, though as long as you are consistent throughout your coding program, you can select your own default number.
  • Python ignores entire blank lines.

How Python understands numbers

In IDLE Editor, at the prompt write the following numbers:

>> 8*9

What happens?

Another:

>> 47/2

What happens?

Another:

>> 47

What happens?

Python can computer, just as a calculator does.

Now at the prompt, type:

>> [47]

What happens?

Python reads this number as part of a potential list or sequence, because it is in brackets. And so it puts the 47 in brackets.