That's it!
In [ ]:
'''
This is a multi-line comment useful for module or overall program information.
Every assignment submission should include at the very beginning a multi-line
comment consisting of:
Name: Stephen Harrington
Course: CS521
Date: January 21, 2017
Assignment: Module #1 Extra Material - Simple Input/Output
Description: This notebook contains a series of interactive python statements highlighting
python's input/output operations
'''
In [ ]:
## Classic output example
## Hello World!
## Note that Python 3.X requires parentheses around the arguments passed to the print function.
## Parentheses were not necessary in earlier versions of Python (e.g. 2.7).
print("Hello World!")
## Input example
variable = input('Prompt for input. Type in anything and hit enter: ')
print( 'Input variable is ' + variable)
In [ ]:
firstname = input('Please type your first name: ')
lastname = input('Now type your last name: ')
print( 'Hello, ' + firstname + ' ' + lastname )
In [ ]:
##basic types are string, int, float and boolean
aString = 'abcD'
anInt = 4
aFloat = 3.1415926
aBoolean = True ## or False
aNoneType = None
##Note that print statements require you to cast ints and other non strings using the str() function
print('a string ' + aString + ' has type: ' + str( type( aString ) ) )
print('an int ' + str(anInt) + ' has type: ' + str( type( anInt ) ) )
##Note that print takes a single type and will cast it as a string to print, same for any non-string type
print(anInt)
print('a float ' + str( aFloat ) + ' has type: ' + str( type( aFloat ) ) )
print('a boolean ' + str( aBoolean ) + ' has type: ' + str( type( aBoolean ) ) )
In [ ]:
##more advanced built-in type are tuple, list and dictionary
aTuple = ( 1, 2, 3 )
aMixedTuple = ( 1, 'a' )
aList = [ 'I', 'am', 'a', 'list', 'of', 'strings' ]
aMixedList = [ 'Mixed Lists include', 'ints', 1, 2, 3, 'strings', 'ab', 'cd',
'and even other lists', [ 1, 2, 3 ], [ 'ab' , 'cd' ] ]
aDictionary = { "key_1" : 1, "key_2" : ( 'a', 'b', 'c'), "bob" : [ 1 , 2, 'a' ] }
print('a tuple ' + str(aTuple) + ' has type: ' + str( type( aTuple ) ) )
print('a list ' + str(aList) + ' has type: ' + str( type( aList ) ) )
print('a dictionary ' + str(aDictionary) + ' has type: ' + str( type( aDictionary ) ) )
In [ ]:
## multiple assignments on basic type
print( "1. multiple assignment", end = " " ) #multiple prints on one line by changing the default end from '\n'
m, n = 5, 12
print( m + n )
print( "\n2. mixed assignment", end = " " )
m, n = 'bob', 6
print( m + str( n ), end = "\n\n" ) #note extra line feed
## assignment with reuse
print( "3. assignment with reuse", end=" " ) #no extra '\n' at beginning like #2 above
m, n = 5, 12
m, n = n, m + n
print( m , end = " ")
print( n )
In [ ]:
help(print)
In [ ]:
'''
1. Tuples, lists and dictionaries are indexed from 0 thru N-1
2. Tuples are immutable
3. Intro try/except blocks
'''
aTuple = ( 1, 25, 87 )
print( "Value of index 0 of a tuple is " + str( aTuple[ 0 ] ), end = "\n\n" )
N = len( aTuple )
##Note the use of the +\ to extend the code to a newline for readability
print( "Value of index " + str( N - 1 ) + " of a tuple of length " +\
str( N ) + " is " + str( aTuple[ N-1 ] ), end = "\n\n" )
'''
Note. If there was no try: and except: block the python interpreter would print out an error message
with a TypeError. A try/except block allows us to "catch" the error and continue with the program
'''
try:
aTuple[ 0 ] = 45 #try to assign index 0 a new value
except TypeError:
print( "Oops! tuples are immutable and you can't assign an element by its index.", end = "\n\n\n" )
##Lists are not immutable and elements can be changed by index assignments
aMixedList = [ 'Mixed Lists include', 'ints', 1, 2, 3, 'strings', 'ab', 'cd',
'and even other lists', [ 1, 2, 3 ], [ 'ab' , 'cd' ] ]
'''
Note how we include quotes " in a string by escaping the character \",
we could also enclose double quotes with single quotes;
i.e. print("This is an apostrophe '")
'''
print( "Value of index 5 of a list is \"" + str( aMixedList[ 5 ] ) + "\"", end = "\n\n" )
try:
aMixedList[5] = "even floats"
except:
print( "We don't reach here!" )
print( "Value of index 5 of a list is now \"" + str( aMixedList[ 5 ] ) + "\"", end = "\n\n\n" )
'''
dictionaries are mutable like lists but are indexed
by keys like an associative array
each entry in the dictionary is referenced by a key
'''
aDictionary = { "key_1" : 1, "key_2" : ( 'a', 'b', 'c'), "bob" : [ 1 , 2, 'a' ], 1 : "this key is an int" }
print( str( aDictionary[ "bob" ] ), end = "\n\n" )
print( str( aDictionary[ 1 ] ), end = '\n\n' )
##List methods - append
print( "\n\nList methods - append and find ", end = '\n\n')
aList = [ 'This is a list','of strings and ints', 1, 2 ]
print( aList)
aList.append( 'String added on at end' )
print( aList )
In [ ]:
string = 'abcdefghijk'
print("\n\nIndexes and slices\n")
print( "index 2 of a string \"" + string + "\" equals \"" + str( string[ 2 ] ) + "\"" )
##slices
print( "indexes 3-7 of a string \"" + string + "\" equals \"" + str( string[ 3:7 ] ) + "\"" )
##not the use of -1
print( "last index of a string \"" + string + "\" equals \"" + str( string[ -1 ] ) + "\"" )
print( "last three indexes of a string \"" + string + "\" equals \"" + str( string[ -3: ] ) + "\"" )
print("The length of the string \"" + string + "\" is " + str( len( string ) ) )
##reverse a string
print("To reverse a string \"" + string + "\" use [::-1] " + string[ : : -1 ] )
print("\n\nSplitting a string\n")
##split a string into a list, useful for parsing files
string = "Column1,Column2,Column3,Column4"
print( string.split( "," ) )
##remove extra white space, split on "|"
string = "Column1| Column2| Column3| Column4"
print( string.replace(" ","").split( "|" ) )
print("\n\nFormatted prints\n")
print( '{0},{1},{2}'.format( 'a', 'b', 'c' ) )
print( '{1},{1},{1}'.format( 'a', 'b', 'c' ) )
print( 'Your name {Firstname} {Lastname}'.format( Firstname = "Stephen", Lastname = "Harrington" ) )
In [ ]:
aTuple = ( 1, 25, 87 )
aMixedList = [ 'Mixed Lists include', 'ints', 1, 2, 3, 'strings', 'ab', 'cd',
'and even other lists', [ 1, 2, 3 ], [ 'ab' , 'cd' ] ]
print( '\n\nObject contains element\n' )
print( 25 in aTuple )
print( "Bruce Springsteen" in aMixedList )
print( [ 1, 2, 3 ] in aMixedList )
print( '\n\nSimple Predicates\n' )
print( 3 < 5 )
print( True == True )
print( 'b' < 'a' )
print( (True or False) == True )
print( (False and True) != False ) ## False and True is equal to True!!!
In [ ]:
##change a, b and c to see all possible answers
a = 2
b = 7
c = 12
print("\n\nif/elif/else")
if a > b:
print ( "{a} > {b}".format( a = a, b = b ) )
elif b > c:
print ( "{first} > {second}".format( first = b, second = c ) )
else:
print( " No criteria met" )
##while loop
print("\n\nWhile Loops")
d = 0
while d < a:
print ( "{d} is less than {a}".format( d = d, a = a))
d+=1
print ( "Loop ends with d = {d}".format( d = d))
##for loops
print("\n\nFor Loops: in")
for letter in 'Python': # First Example
print( 'Current Letter :' + letter )
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print( 'Current fruit :' + fruit )
print("\n\nFor Loops: range")
for i in range(5):
print( "i=" + str( i ) )
In [ ]: