Welcome!

This is the coding component of the workshop. To visit the introductory overview of Python language, please go to the workshop slides.

Getting Started

Workshop Best Practices

Syntax

Python was designed for readability, and has some similarities to the English language with influence from mathematics.

Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.

Comments

Creating a Comment

Comments starts with a #, and Python will ignore them:

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code:

Multi Line Comments

Or, you can use a multiline string for the same purpose.

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:

Variables

Variables are containers for storing data values.

Creating Variables

A variable is created the moment you first assign a value to it.

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for Python variables:

Multi Words Variable Names

Variable names with more than one word can be difficult to read, since you can't put spaces between them.

There are several techniques you can use to make them more readable:

Note: You could choose any method that you like to define variable names, but make sure to be consistent!

Assign Multiple Values

Python allows you to assign values to multiple variables in one line:

And you can assign the same value to multiple variables in one line:

Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Getting the Data Type

You can get the data type of any object by using the type() function:

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

Array: a group (or collection) of same data types.

However, Python does not have a character data type, a single character (which requires a single byte) is simply a string with a length of 1.

Indexing

We can access characters in a string by indexing. Square brackets can be used to access elements of the string. The first character has the position 0.

Slicing Strings

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

String Length

To get the length of a string, use the len() function.

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Modify Strings

Python has a set of built-in methods that you can use on strings, using "." operator.

Note: split() is actually a very useful method in data analysis when you read in user inputs or data line by line.

String Methods: https://www.w3schools.com/python/python_strings_methods.asp

String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Booleans

Booleans represent one of two values: True or False.

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return.

Most Values are True

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.

Setting or Changing the Data Type

In Python, the data type is set when you assign a value to a variable.

There may be times when you want to specify a type on to a variable. This can be done with Casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

Casting Rules:

  1. Integer can be casted (changed) to float and string
  1. Floats can be changed to a string and integer.

** The default int() function acts like a floor() function (decimal is rounded down). If you want to round up, you can import ceil() function from the math library (more on this next week)

  1. However, you cannot change a non-numeric string to an integer or float.

Challenge: can c be changed into an integer, float, or both?

Practical application of bool() in Python?

  1. It lets you convert any Python value to a boolean value. Sometimes you want to store either True or False depending on another Python object.

  2. A boolean variable could also be represented by either a 0 or 1 in binary in most programming languages. A 1 represents a "True" and a 0 represents a "False".

    Why "Boolean"? Why 0 and 1?

    Boolean values are named after mathmatician George Boole, who invented Boolean algebra -- a branch of algebra in which the values of variables are the logical values true and false, usually denoted as 1 and 0 respectively. Today, it became a convention of describing logic.

Operators

Python divides the operators in the following groups:

Python Operators links:

https://www.w3schools.com/python/python_operators.asp

Arithmetic operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Assignment operators

Assignment operators are used to assign values to variables:

Logical operators

Logical operators are used to combine conditional statements:

Comparison operators

Comparison operators are used to compare two values

Identity operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Comparison VS Identity Operators: Example with Boolean Value

A method to make 1 and True identical:

When we use the bool() function here, we convert 1 to a boolean. This conversion is also casting -- Casting 1 to boolean value of "True".

Membership operators

Membership operators are used to test if a sequence is presented in an object:

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

Bitwise operators

Bitwise operators are used to compare (binary) numbers. It is similar to logical operators as we see before, but on binary numbers.

Binary numbers is a positional numeral system employing 2 as its base, only using 2 symbols: 0s and 1s.

The computer can only understand numbers, it relies on the ASCII table, which encodes a numerical representation (based off of binary numbers) of every character on our keyboard. conversion.png

https://www.programiz.com/python-programming/operators

Statements

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.

Other programming languages often use curly-brackets for this purpose.

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

And

The and keyword is a logical operator, and is used to combine conditional statements:

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Final Exercises - You made it!

If you need help with the exercises, please contact NYU Shanghai Library at shanghai.library@nyu.edu

Ending credits

Tutorial framework: https://www.w3schools.com/python/default.asp

Modified and organized by: Pamela Pan, Jie Chen