Intro to Python

Python Crash Course

Objectives

  • Describe the history of the Python language

  • Identify fundamentals and concepts of the Python language

  • Utilize different primitive types, control structures, and methods in Python

  • Use the python3 interactive shell

  • Write a program that responds to user input

Python History

Benevolent Dictator For Life

Guido van Rossum
  • Guido van Rossum (Dutch) built Python as a hobby project on his winter break

Goals

  • An easy and intuitive language just as powerful as major competitors

  • Open source, so anyone can contribute to its development

  • Code that is as understandable as plain English

  • Suitability for everyday tasks, allowing for short development times

Releases

  • Python 1.0 realeased 1991

  • Python 2.0 (2000) - started to gather a development community

  • Python 3.0 (2008) - unified the language more at the cost of making some old 2.0 code incompatible

Advantages

  • high-level language (closer to english than machine code)

  • interpreted (as opposed to compiled)programming language (compiled languages have to be run through a compiler that changes

    source code into compiled code before the program can be run, whereas interpreted

    languages are run on the fly

  • general purpose scripting language that runs outside a browser

  • free and open source (community development through Python Enhancement Proposals)

  • comes with a huge library of builtin functions

  • The documentation is fantastic

Python Features and Syntax!

Here's the long list of how to get Python to do the things you already know how to do in JavaScript. Let's dive right into it.

Comments

In Python, multiline comments exist, but we generally use line comments with hashtags, for readability.

For multiline comments in Python, you can use """ blocks. However observe proper indentation or you will get a SyntaxError.

Variables

Local variables start with a lowercase letter. No var necessary. Most Python programs choose to insert underscores between words instead of writing names in camelCase (this is considered more readable by the PEP maintainers).

Data Types

Nothingness

Just as Javascript uses undefined or null, Python uses None.

None is a unique datatype (NoneType) and is not equivalent to False, empty string, or 0. However, None does not evaluate to True.

Booleans

A binary representation: either True or False. Capitalization matters here. you must write "True" and Python will not recognize "true."

Numbers

There are several datatypes used to represent numbers:

  • int: 23

  • float: 0.8947368421052632

  • complex: 2+3j

Python does decimal division normally with / but you can force it to do integer division with //:

Complex numbers can be added to complex numbers:

Python is great at dealing with very large integers. Use ** to calculate exponents. JavaScript will only approximate large numbers with Scientific Notation:

Strings

You can declare strings in Python just like in JavaScript:

String Methods

Python has some familiar String methods like split. Other String methods are under different names:

You can use the special in keyword to quickly find out if one string appears in another.

Use the len() operator on a string to find it's length.

Ranges

Python has a very cool syntax to select things inside a range. You can select a letter in a string a specific index. You can select letters between a start and and index. You can select letters counting backwards from the end using negative numbers. You can select every N letters by specifying a step size.

  • str[index] choose one letter at index

  • str[-index] choose letter at index counting backwards from the end.

  • str[start:end] get a range of letters from a start to end.

  • str[start:end:step] get a range of letters taking step sized steps between.

  • str[:end] omit the start index and grab letters from zero up to end.

  • str[start:] omit the end index and grab letters from start up to the end of the string.

  • str[::-1] reverses a string by going backwards with a step of -1 from start to end.

Arithmetic Operators

Python uses common operators for math.

Logical Operators

Python uses == for equality. It uses != for "not equal to." It uses the literal words not, or and and instead of !, || and && like JavaScript does.

Lists

Arrays in Python are called Lists.

Python lists can be indexed just like strings. Also, use the len() operator to find the length of a list. Python lists don't have a .length property on them.

Python lists can be indexed just like Python strings. You can use negative indexes and select a range of values in the middle of the list.

several ways to create an array

List Methods

Fire up the interactive Python console on your terminal with python3 or ipython3 and pass list to the help function to read documentation about all of the methods on list.

Dictionaries

Python stores key-value pairs (like objects in JavaScript) in Dictionaries. The syntax is almost exactly like objects in JavaScript.

Anything can be used as a key. Strings are commonly used as keys. If the key is a string then you must surround the key in quotes when the dictionary is defined.

Type Conversion

You can turn one Python data type into another by passing it to type functions:

String Interpolation

Python has super convenient ways to format strings on the fly. You'll never have to bother with crazy string concatenation again. These are like small rendered templates.

Define any string with the letter f in front of the quotes and Python will treat it as a "formatted" string. Formatted strings use curly braces {} to identify where to evaluate values inside a string. The value inside the curly braces can be variable names, or expressions.

The curly braces and the format function can refer to names for where values appear in the template, and what values are named.

Let's see format strings calling a function too!

F-strings are awesome. There's also a format() function on all strings. You can specify empty curly braces and pass values as parameters and the parameter values will fall in line in the order the curly braces appear.

The format() function an also name the curly braces and accept named parameters:

Control flow

  • Conditionals

  • Loops

Iterating through Arrays

Python for loops always act on iterators. This means they always automatically pull things out of a sequence and loop through those things one by one. Python never uses a for loop where it increments a value like i manually.

If you want to have fine-grain control over what's happening to i, and you don't want to just step through everything in a sequence one by one, then you're probably better off using a while loop.

If you want access to the current index of each item then you need to pass your list through a function called enumerate. Enumerate takes items out of an iterator one by one and returns a tuple of the index of the item and the item like (index, item).

i is still zero-indexed:

Iterating through Dictionaries

For loops will automatically iterate over the keys in a dictionary:

Functions

In Javascript

  • anonymous: function (param1, [..param2, [...]]){...},

  • named: function Name(param1, [..param2, [...]]){...}

  • uses lexical scope

  • used as values (functional programming)

  • require explicit return

  • all params are optional

  • no default values for optional params

  • functions can be used before they're declared

In Python

  • uses def foo(param1, param2, city="Seattle"):

  • may provide default values for optional parameters

  • may use one return statement to return more than one variable

  • functions must be declared before they're used

Examples

Parameters (Arguments)

Return Values

Tuples and Multiple Return Values

Python has a datatype called a tuple which groups "multuple" things together. A tuple is a collection of multiple values wrapped in parentheses. Tuples are not lists. List support more operations than tuples. Tuples are immutable. Once one is made it never changes. You can't add or remove things from a tuple.

Python will automatically unpack tuples into variables if the number of variables on the left side of an equals sign is equal to the number of variables on the right hand side.

Python uses tuples to return multiple values in one return statement. Here's our own function called divide_mod() that allows us to calculate the division of two numbers as well as their modulus all at once!

Input / Output

You've already seen how print will output information to the screen. What if e want to accept user input? Let's try input(). Input takes a parameter where we can define a message to be printed as a prompt for the input:

Notice: input() always returns a string value. If you want someone to enter a number then you should pass the value input returns through something like int() or float().

There's nothing special about the int() or float() functions. They try to convert whatever value their given to an int or a float.

Now You're Hacking!

That's a quick introduction to only some of the things Python has to offer. You now have enough knowledge about Python's basic data types, functions, lists, dictionaries, control flow statements to try writing some programs of our own.

Try to write a program that prompts the user for the current temperature, and asks them whether they've entered a Celsius or Fahrenheit temperature. Have the program convert their temperature from the units they provided into the other units.

Last updated

Was this helpful?