Basic Syntax

Students cheer on the Redhawks during a sporting event at Miami University.

A brief introduction to Spyder

There are three main windows in Spyder, see the following layout of Spyder.

Spyder Inteface

There are three tags on the top right side: Object inspector, Variable explorer, and File Explorer.

  • Object Inspector - this is used for information, help documentation, and many actions
  • Variable Explorer - names and properties of variables
  • File Explorer - where you can access files

There are three tags on the bottom right side as well: (Python) Console, History log, and IPython console.

  • Console - this is the default Python shell, where the commands are going to be executed. You can test small parts of code in a console but anything you type here is not saved.
  • History Log - history of commands executed in consoles
  • IPython Console - this is a powerful interactive Python shell. For example, it makes system commands available directly and it allows you to see plots inline. There are many good features of IPython. See more detail in IPython Documentation. You also can test small sections of code in IPython consoles. Anything you type here is not saved.

Note: You can use either Python console or IPython console. We recommend using IPython as it has many good features.

Some tips for using Spyder

  • You can personalize the look and feel of the Spyder interface by choosing from different syntax themes. You can access the setting by clicking Tools --> Preferences. Click on the different options to instantly view the setting for different windows. For example, you can change the syntax color scheme to Spyder/Dark after visiting Editor.

Change syntax color to Spyder/Dark under Editor in Preferences

  • Using # to note the information about sections of code will help you recall what you have done. Also, commenting is useful in instances where you are not sure which part of your code is wrong. The shortcut key for commenting and uncommenting in Spyder is Ctrl + 1 (Click Ctrl and 1 simultaneously).
  • For both Python shell and IPython shell, they have command history through the arrow key. Clicking the up arrow key will show previously typed commands.
  • To clear the output on Console, use Ctrl-L.
  • To clear all global variables and restart the Python interpreter (in general, it is Python 1), click the yellow triangle on the down-right corner and click the green man icon which is next to the yellow triangle.
  • To restart kernel or open a new IPython console (in general, it is Console 1/A), click the small square icon on the down-right corner (see the layout of Spyder above).
  • Use the help command to get help for using functions. For example, type help(range) on Console will show the help on the built-in function range.
  • You can enable the object inspector to display the documentation of a function when the function is called. Go Tools (on the top) ----> Preferences ----> Object Inspector (on the left-hand side) ----> Automatic connections and check the environment you want to use the inspector. High recommended checking all of them. Try type range( in the IPython console and check out the output in the window of object inspector. You will see the documentation of the built-in function range() in Python.

Basic Syntax

  • Print function - (0:26)
  • Assign variables - (1:27)
  • String variable - (2:44)
  • Float variable - (3:11)
  • Int variable - (4:01)
  • Round function - (4:14)
  • Mathematical functions - (4:33)
  • Input function - (5:22)
  • Formatting - (6:33)

The detail Built-in Types can be found at python.org.

Special notes:

  1. In python, x^y doesn't represent x to the power y. It is the bitwise exclusive or of x and y. To calculate x to the power y (x^y), you can use x**y or pow(x,y). This is very different from other programming languages.
  2. A pound sign '#' is used when we want to make comments. It defines a comment line.

  • Basic Calculation - (0:09)
  • Exponent Operator - (1:37)
  • Sequence - (2:12)
  • List - (2:31)
  • Tuple - (3:53)
  • abs function - (4:45)
  • max function - (5:08)
  • sum function - (5:50)
  • len function - (6:08)

Basic data structure: sequences

There are 6 built-in types of sequences. Here we introduce two of the most common - tuples and lists.

  • tuple() - a function to list a sequence of values.
    • Note: in Python, indexes start at 0, and the maximum is non-inclusive; for example, specifying the range 1 to 5 will include the second, third, fourth, and fifth values.

tuple((3, 1, -2)) # use the tuple function
    Output: (3, 1, -2)
    
    (3, 1, -2) # use parentheses to create a tuple
    Output: (3, 1, -2)
    
    3, 1, -2 # use a comma to separate components 
    Output: (3, 1, -2)
    
    3, 1, "hello" # tuple can be used to store numbers and strings together 
    Output: (3, 1, "hello")
    
    "math", "statistics", "physics", "chemistry" # a tuple of strings
    Output: ('math', 'statistics', 'physics', 'chemistry')
    
    tuple("hello") # a tuple of 5 components h, e, l, l, o
    Output: ('h', 'e', 'l', 'l', 'o')
    
    a = tuple("hello") # assigning a name to the tuple 
    a[1] # the second component in the tuple will be returned
    Output: 'e'
    
    a[0] # it returns the first component in the tuple 
    Output: 'h'
    
    a[0:3] # it returns a tuple of the first, second, 
             and thrid components in the original tuple 
    Output: ('h', 'e', 'l')
    
    a[2:4] # it returns a tuple of the third and fourth components in the original tuple
    Output: ('l', 'l')

Note: You should notice that the index or position of a tuple starts from zero, not one.

Tutorials for learning Python tuples can be found at python.org (data structures) or tutorialspoint.

  • list() - a function to list a sequence of values. Here is an example:

list((1, 2, 3)) # use the list function 
Output: [1, 2, 3]

[1, 2, 3] # simply use brackets to create a list
Output: [1, 2, 3]

list("abc") # use the list function 
Output: ['a', 'b', 'c']

list(("abc", 2, 3))
Output: ['abc', 2, 3]

b = [3, 1, -2, 7, -5] # assign a name to the list 
b[2] # it returns the third element in the list 
Output: -2 

b[0] # it returns the first element in the list 
Output: 3

b[1:4] # this returns a list of the second, third, and fourth elements 
         in the original list
Output: [1, -2, 7]

Note: The index of a list also starts from zero.

Tutorials for learning Python lists can be found at python.org (data structures) or tutorialspoint.

Difference between tuples and lists: Tuples have no methods, which means that you can't add, remove, or find an element in a tuple directly; their contents are fixed and cannot be changed without overwriting the tuple entirely.

Numeric Types - float(), int()

  • float() - convert a number or a string to a floating-point number, if possible.
  • int() - convert a number or a string to an integer (i.e. a whole number), if possible.

Here is an example for float() and int().

float(312)
Output: 312.0

float("312.17635")
Output: 312.17635

round(312.17635, 2) # use round() to round a number for 2 decimal places 
Output: 312.18

int(312.17635) # truncate the number and replace it with the resulting integer
Output: 312

int("312") # convert a string to an integer 
Output: 312

int(float("312.17635")) # convert a string to an integer 
Output: 312

round(312.17635, 0) # round a number to the nearest integer 
Output: 312.0

Stop: In the above example, you can find the outcomes of the last four commands are all 312. What's the difference between them? Why do we need different ways to find the same outcome? Try int("312.17635"), what do you get?

Some commonly used built-in functions in data analysis

There are a number of functions built into the Python interpreter. We introduce some commonly used built-in functions here. More details about the built-in functions can be found on this page on the official website of Python Programming Language.

Simple calculation functions: abs(), max(), min(), sum(), len()

  • abs() - a function to evaluate the absolute value of a number. Try abs(-5) and see what you get.
  • max() - a function to evaluate the maximum of a list of values
  • min() - a function to evaluate the minimum of a list of values
  • sum() - a function to evaluate the sum of a list of values
  • len() - a function to evaluate the length of an object

Here is an example for abs(), max(),min(), sum(), and len().

abs(7)
Output: 7

abs(-7)
Output: 7

max(3, 1, 5, -2) # maximum of values 
Output: 5

max((3, 1, 5, -2)) # maximum of values in a tuple
Output: 5

max([3, 1, 5, -2]) # maximum of values in a list
Output: 5

min(3, 1, 5, -2) # minimum of values 
Output: -2

min((3, 1, 5, -2)) # miniimum of values in a tuple
Output: -2

min([3, 1, 5, -2]) # minimum of values in a list
Output: -2

sum((3, 1, 5, -2)) # sum of values in a tuple
Output: 7

sum([3, 1, 5, -2]) # sum of values in a list
Output: 7

c = 3, 1, 5, -2;
len(c) # it returns the length of a tuple 
Output: 4

d = [3, 1, 5, -2];
len(d) # it returns the length of a list 
Output: 4

More functions

  • Range function - (0:04)
  • All function - (0:37)
  • Any function - (1:53)
  • Sorted function - (3:42)
  • range() - a function to list a range of values. It indexes in the same way as a tuple or list (see above).

range(0, 10) # it returns a list of values from 0 to 9
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(13, 19) # it returns a list of values from 13 to 18
Output: [13, 14, 15, 16, 17, 18]

  • all() - a function to check if all elements of an object that is capable of returning its members one at a time are true
  • any() - a function to check if any element of an object that capable of returning its members one at a time is true

Here is an example for all() and any().

all(x > 5 for x in range(0, 10))
Output: False

all([x > 5 for x in range (0, 10)])
Output: False

all([x > 5 for x in range (5, 10)])
Output: False

any(x > 5 for x in range (0, 10))
Output: True

any([x > 5 for x in range (0, 10)])
Output: True

any([x > 5 for x in range (0, 6)])
Output: False

Note: In the above example, all(x > 5 for x in range(0,10)) and all([x > 5 for x in range(0,10)]) return the same outcome; this is because lists and tuples behave the same way when they aren't being edited. To see how the example above examines each element in a list or tuple, see the example below.

a = (x > 5 for x in range (0, 10)) # a is a generator 
a.next() # repeat this command 10 times, you should see False, False, False, 
           False, False, False, True, True, True, True, respectively
           
[x > 5 for x in range (0, 10)] # this returns a list of [False, False, False, 
                                 False, False, False, True, True, True, True]

  • print() - a function to print an object. Here is an example

a = 3 
b = 5
print a+b
Output: 8

print "a+b=", a+b # use a comma to combine two statements
Output: a+b= 8

print "a+b="+str(a+b) # use a plus to combine two statements 
Output: a+b=8

print "Hello! You are doing great!!"
Output: Hello! You are doing great!!

Note: We can use a comma or + to combine two statements. But what's the difference between these two ways? Try: print "a+b="+(a+b) and see what you get.

  • sorted() - a function to sort a list of numbers. Here is an example

c = [8, 3, -7, 0, 2, -4, 1] # define a list and assign it to c 
    sorted(c) # sort the list in ascending order 
    Output: [-7, -4, 0, 1, 2, 3, 8]
    
    sorted(c, reverse = True) # sort the list in descending order 
    Output: [8, 3, 2, 1, 0, -4, -7]
    
    print c # c maintains the same 
    Output: [8, 3, -7, 0, 2, -4, 1]
    
    c.sort() # methods are another way to sort a list 
        # just place a period after the object and follow it with the method you wish to use.       
        # in this example, we call the .sort method on the object c.
        
    print c # the list is changed 
    Output: [-7, -4, 0, 1, 2, 3, 8]
    
    c.sort(reverse=True)
    print c # the list is changed 
    Output: [8, 3, 2, 1, 0, -4, -7]

Note: From the above example, you should see that using the sorted function only sorts the list of values but it doesn't change the original list. In addition, sorted() can be used to sort any object that capable of returning its members one at a time, not just a list.