Welcome!
This is the coding component of the workshop. To visit the introductory overview of Python language, please go to the workshop slides.
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.
print(1 + 2)
print(2 + 2)
3 4
1 + 2
2 + 2
4
# print() function
print("Hello, World!")
Hello, World!
# Customize your Hello Message!
# Remove the pound sign in the fourth row (#), and write your name in the underscore area
# Then, run it!
# print("Hello, __")
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:
# This is a comment
print("Hello, World!")
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
print("Hello, World!") # This is also a comment
Hello, World!
Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code:
#print("Hello, World!")
print("Happy Friday!")
Happy Friday!
# This is a comment
# written in
# more than just one line
print("Hello, World!")
Hello, World!
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:
"""
This is a comment
written in
more than just one line
"""
""" Triple quote also works on the same line """
print("Hello, World!")
Hello, World!
Variables are containers for storing data values.
A variable is created the moment you first assign a value to it.
a = 'John'
print(a)
John
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
# Illegal variable names:
# 1myvar = "John"
# &myvar = "John"
# Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
John
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:
# Camel Case
# Each word, except the first, starts with a capital letter:
randomPersonName = "John"
# Pascal Case
# Each word starts with a capital letter:
RandomPersonName = "John"
# Snake Case
# Each word is separated by an underscore character:
random_person_name = "John"
Note: You could choose any method that you like to define variable names, but make sure to be consistent!
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Orange Banana Cherry
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Orange Orange Orange
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:
You can get the data type of any object by using the type() function:
x = 5
y = "John"
z = 5.55
i = 15j #appending j to an int yields an imaginary number
boo = False
print(x, y, z, i, boo)
5 John 5.55 15j False
print(type(x), type(y), type(z), type(i), type(boo))
<class 'int'> <class 'str'> <class 'float'> <class 'complex'> <class 'bool'>
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
print("Hello")
print('Hello')
Hello Hello
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
a = "Hello"
print(a)
print(type(a))
Hello <class 'str'>
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.
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.
# Get the character at position 1 (remember that the first character has the position 0):
a = "wonderland"
print(a[1])
o
# Challenge: What letter is on position 4?
# Replace the underscore with your answer, uncomment and run it
print(a[4])
# Check:
# Put your letter in the quotes below to see if it returns 4
a.index('e')
e
4
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.
# Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
llo
# Slice From the Start
# By leaving out the start index, the range will start at the first character:
# Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Hello
# Slice To the End
# By leaving out the end index, the range will go to the end:
# Get the characters from position 2, and all the way to the end (included):
b = "Hello, World!"
print(b[2:])
llo, World!
# Negative Indexing
# Use negative indexes to start the slice from the end of the string:
# Get the characters:
# From: "o" in "World!" (position -5)
# To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-1])
print(b[-5:-2])
! orl
# Step
# [start_index:end_index:step_size]
b = a[1:8:2]
print(b)
el,w
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
13
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Python has a set of built-in methods that you can use on strings, using "." operator.
# The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
# The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
hello, world!
# The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a)
print(a.strip())
Hello, World! Hello, World!
# try with multiple whitespaces
l = " apple, bee "
print(l.strip())
apple, bee
# The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "M"))
Mello, World!
# The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
['Hello', ' World!']
type(a.split(","))
list
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.
# Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
# To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Hello World
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:
print(10 > 9)
print(10 == 9) # "==" is used in boolean statements, "=" is used in value declarations
print(10 < 9)
True False False
The bool() function allows you to evaluate any value, and give you True or False in return.
print(bool("Hello")) # string value, legit!
print(bool(15)) # integer value, legit!
True True
Most Values are True
# The following will return True:
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
True True 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.
# The following will return False:
bool(False) # boolean value
bool(None) # null value
bool(0) #'empty' integer
bool("") #empty string
bool(()) #empty tuple
bool([]) #empty list
bool({}) #empty dictionary
False
print(1 > 2)
print(bool(1 > 2))
False False
print("Hello" == "Hi")
print("HELLO" == "hello")
print("Hello" == "Hello")
False False True
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:
x = 1
print(x)
print(type(x))
x_str = str(x)
print(x_str)
print(type(x_str))
x_float = float(x)
print(type(x_float))
1 <class 'int'> 1 <class 'str'> <class 'float'>
z = 5.55
z_str = str(z)
print(type(z_str))
<class 'str'>
** 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)
z_int = int(z)
print(type(z_int))
print(z_int)
#import library, which has the floor() and ceil() functions
import math
# round decimal down
print(math.floor(z))
# round decimal up
print(math.ceil(z))
<class 'int'> 5 5 6
# previously, we defined y = 'John'
# try to see the error:
# print(int(y))
a = '10'
# a can be changed into integer and float
print(int(a))
print(float(a))
10 10.0
c = '10.9'
Challenge: can c be changed into an integer, float, or both?
# print(int(c))
# print(float(c))
# From string to float, then to integer
# print(int(float(c)))
Practical application of bool() in Python?
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.
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.
Python divides the operators in the following groups:
Python Operators links:
Arithmetic operators are used with numeric values to perform common mathematical operations:
# Addition
1 + 1
2
2 * 2
4
Assignment operators are used to assign values to variables:
x = 7
print(x)
x = x - 1
print(x)
7 6
x -= 1
print(x)
5
x += 3
print(x)
8
Logical operators are used to combine conditional statements:
print(2 > 1 and 3 < 2)
False
Comparison operators are used to compare two values
a = 9
b = 'a'
print(a == b)
False
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:
a = 3
b = '3'
print(a is b)
False
Comparison VS Identity Operators: Example with Boolean Value
print(1 == True)
# this statement uses a Comparison Operator
# It compares the value of 1 and 'True', which are the same
# Since 1 could be representing 'True', as we mentioned in the Boolean section
True
print(1 is True)
# this statement uses an Identity Operator
# It's saying integer 1 is the identical object as the Boolean value True
# which is false, despite they hold the same value
# because 1 is an integer, while True is a Boolean type value
# try:
# print(1)
# print(True)
False
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".
print(bool(1) is True)
# However, if we say the boolean value of 1 is the same thing as True,
# Python will return 'True'
# try:
# print(bool(1))
# print(True)
True
Membership operators are used to test if a sequence is presented in an object:
s = "hello"
s1 = "e"
print(s in s1)
False
To check if a certain phrase or character is present in a string, we can use the keyword in.
# Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
True
print("apple" in txt)
False
# Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
True
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.
a = 5
b = 7
print(a and b)
print(a & b)
7 5
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.
# If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
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.
# If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # if you don't indent here, you will get an error
File "<ipython-input-38-b6691ae03602>", line 5 print("b is greater than a") # if you don't indent here, you will get an error ^ IndentationError: expected an indented block
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
a = 33
b = 50
if b > a:
print("b is greater than a")
elif a == b:
print("b and a are equal")
else: # b < a is the only possibility left
print("b is smaller than a")
b is greater than a
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
a is greater than b
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
# One line if statement:
if a > b: print("a is greater than b")
a is greater than b
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:
# One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
B
The and keyword is a logical operator, and is used to combine conditional statements:
# Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Both conditions are True
The or keyword is a logical operator, and is used to combine conditional statements:
# Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True
# Exercise I: Use Slicing to print the word 'everything' from the following sentence
sentence = "Everything is under control."
# write your code below:
# Exercise II: Use casting to make the 2 variables the same data type,
# and print them out together on one line
sentence = 'My dog is'
age = 7
# write your code below:
# Exercise III: Print the larger one between two numbers
m = 5
n = -99
# write your code below:
# Exercise IV: Check if student A is John Lee (use AND operator)
A_fn = "Joe"
A_ln = "Lee"
# write your code below:
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