Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han
Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey Introduction to Python 3 Try out Python IDLE (Interactive DeveLopment Environment) Learn Python basic syntax print command Strings Variables Learn to get around in Python IDLE Restarting IDLE session 8/28/2018 2
How to do well in this course 1. Be hard-working. If you are new to programming, expect to put in 4-credit worth of work. 2. Be detail-oriented. Do not skim for "important" stuff! You should learn everything. Pay attention to instructions & details when doing homework. 3. Be organized. Class moves fast, and there are a lot of assignments. 4. Be persistent. Coding has frustrating moments. Keep at it! 5. Ask for help. When you had enough of hair-pulling, email/office hours. 8/28/2018 3
Your first code 1. Open up a new window ("File" > "New Window", or Ctrl+n). 2. Python editor window opens up. Type in: 3. Save the script as "hello.py". print('hello, world!') 4. Run the script by selecting "Run" > "Run Module" or F5. 5. Success! The command executes in the IDLE shell window. Python SCRIPT file IDLE shell (Python interpreter)
Scripts can be edited and saved More lines of code added to the script Script is run again; shell re-starts and then executes 8/28/2018 5
Following up a script in shell Variable name is available in shell for subsequent commands 8/28/2018 6
Try it out 1 minute 8/28/2018 7
Operating in shell >>> print('hello', 'world!') Hello world! >>> 4 * 12 48 >>> In IDLE shell window, Python interprets and responds to each line of code you type in. called a command prompt 8/28/2018 8
>>> print('hello', 'world!') Hello world! >>> 4 * 12 48 >>> print(4 * 12) 48 >>> 1 + 4 * 12 49 >>> 1+4*12 49 >>> (1 + 4 * 12) / 10 4.9 >>> prints two strings as two words returns value prints value white space is optional with these operators Parentheses ( ) are used to override precedence 8/28/2018 9
Variable assignment Variable name >>> salary = 4500*12 >>> print(salary) 54000 Variable assignment operator Expression: variable content VALUE is what s stored, not the expression itself 8/28/2018 10
Printing vs. returning Prints string content >>> who = 'Homer' >>> print(who) Homer >>> who 'Homer' >>> Evaluates expression, returns the value. Value is a string: note the quotes! 8/28/2018 11
>>> who = 'Homer' >>> print(who) Homer >>> who 'Homer' >>> salary = 4500 *12 >>> salary 54000 >>> print(who, 'makes', salary, 'dollars a year.') Homer makes 54000 dollars a year. >>> who = 'Mr. Burns' >>> salary = 50000*12 >>> print(who, 'makes', salary, 'dollars a year.') Mr. Burns makes 600000 dollars a year. 8/28/2018 12
Changing variable value Variable value is declared and then changed >>> who = 'Homer' >>> print(who) Homer >>> who 'Homer' >>> salary = 4500 *12 >>> salary 54000 >>> print(who, 'makes', salary, 'dollars a year.') Homer makes 54000 dollars a year. >>> who = 'Mr. Burns' >>> salary = 50000*12 >>> print(who, 'makes', salary, 'dollars a year.') Mr. Burns makes 600000 dollars a year. 8/28/2018 13
Variables, variables 2 minutes >>> greet = 'Hello,' >>> nameis = 'my name is' >>> name = 'Homer' >>> print(greet, nameis, name) Hello, my name is Homer >>> >>> name = 'Marge' >>> print(greet, nameis, name) Hello, my name is Marge >>> >>> greet = 'Good morning everyone,' >>> print(greet, nameis, name) Good morning everyone, my name is Marge Same command. Use command history! Ctrl+p/n (Mac)* Alt+p/n (Win)* *It could be up/down arrows. You can also configure your IDLE. 8/28/2018 14
Can anything be a variable name? Answer: NO. You can use: Any letter Number, but not initially. ex: name1 is good, 1name is not Underscore "_". ex: student_name Variable names are case-sensitive! greet and Greet are two different variables. Following are built-in Python keywords and cannot be used as a variable name: and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass raise return try while yield 8/28/2018 15
Restarting shell Ctrl+F6 restarts IDLE shell >>> greet = 'Hello,' >>> nameis = 'my name is' >>> name = 'Homer' >>> print(greet, nameis, name) Hello, my name is Homer >>> name = 'Marge' >>> print(greet, nameis, name) Hello, my name is Marge ================================ RESTART ==================== >>> print(greet, nameis, name) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> print(greet, nameis, name) NameError: name 'greet' is not defined After RESTART, the 3 variables are no longer defined!! 8/28/2018 16
String vs. number: '+' and len() >>> 4 + 15 19 >>> '4 + 15' '4 + 15' >>> '4' + '15' '415' >>> 'ab' + 'cde' 'abcde' >>> len('abcde') 5 >>> len('4' + '15') 3 >>> len('ab' + 'cde') 5 >>> len(4 + 15) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> len(4 + 15) TypeError: object of type 'int' has no len() 8/28/2018 17
String vs. number: '+' and len() >>> 4 + 15 19 >>> '4 + 15' '4 + 15' >>> '4' + '15' '415' >>> 'ab' + 'cde' 'abcde' >>> len('abcde') 5 >>> len('4' + '15') 3 >>> len('ab' + 'cde') 5 >>> len(4 + 15) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> len(4 + 15) TypeError: object of type 'int' has no len() ERROR: Integers do not inherently have length! 8/28/2018 18
len() >>> 4 + 15 19 >>> '4 + 15' '4 + 15' >>> '4' + '15' '415' >>> 'ab' + 'cde' 'abcde' >>> len('abcde') 5 >>> len('4' + '15') 3 >>> len('ab' + 'cde') 5 >>> len(4 + 15) len() returns the length of a string measured in # of characters Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> len(4 + 15) TypeError: object of type 'int' has no len() 8/28/2018 19
+: number vs. string operation >>> 4 + 15 19 >>> '4 + 15' '4 + 15' >>> '4' + '15' '415' >>> 'ab' + 'cde' 'abcde' >>> len('abcde') 5 >>> len('4' + '15') 3 >>> len('ab' + 'cde') 5 >>> len(4 + 15) 4 and 15 are integers. + is an addition operator '4' and '15' are strings of letters. + is a concatenation operator Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> len(4 + 15) TypeError: object of type 'int' has no len() 8/28/2018 20
+ vs. print >>> 'police' + 'man' 'policeman' >>> print('police', 'man') police man >>> print('police' + 'man') policeman 8/28/2018 21
+ vs. print >>> 'police' + 'man' 'policeman' >>> print('police', 'man') police man >>> print('police' + 'man') policeman prints two strings, separated by a space prints the concatenated output as a single string 8/28/2018 22
+, *: overloaded operators >>> 14 * 3 42 >>> 'abc' * 3 'abcabcabc' >>> '14' * 3 '141414' >>> 'x' * 10 'xxxxxxxxxx' 8/28/2018 23
+, *: overloaded operators >>> 14 * 3 42 >>> 'abc' * 3 'abcabcabc' >>> '14' * 3 '141414' >>> 'x' * 10 'xxxxxxxxxx' Integers arguments. * is a multiplication operator String argument on left. * is a multi-copy concatenation operator Just like +, * also behaves differently for number and string arguments: overloaded operators 8/28/2018 24
+ as concatenation operator >>> w1 = 'school' >>> w2 = 'bus' >>> w1+w2 'schoolbus' >>> print(w1, w2) school bus >>> print(w1+w2) schoolbus >>> w1+' '+w2 'school bus' >>> print(w1+' '+w2) school bus >>> [w1, w2] ['school', 'bus'] 8/28/2018 25
A list of strings >>> w1 = 'school' >>> w2 = 'bus' >>> w1+w2 'schoolbus' >>> print(w1, w2) school bus >>> print(w1+w2) schoolbus >>> w1+' '+w2 'school bus' >>> print(w1+' '+w2) school bus >>> [w1, w2] ['school', 'bus'] A list containing two strings. Square bracket [ ] marks the list data type. 8/28/2018 26
A string can contain a space >>> w1 = 'school' >>> w2 = 'bus' >>> w1+w2 'schoolbus' >>> print(w1, w2) school bus >>> print(w1+w2) schoolbus >>> w1+' '+w2 'school bus' >>> print(w1+' '+w2) school bus >>> [w1, w2] ['school', 'bus'] Concatenating two words with a space ' ' in between 8/28/2018 27
String String: a single piece of text, composed of a sequence of characters. Enclosed in ' ' or " " >>> print("it's me, Homer.") It's me, Homer. >>> print('homer says "hi."') Homer says "hi." 8/28/2018 28
String String: a single piece of text, composed of a sequence of characters. Enclosed in ' ' or " " >>> print("it's me, Homer.") It's me, Homer. >>> print('homer says "hi."') Homer says "hi." Enclosed in """ """ (triple double quotes) Can be multi-line! >>> print("""this is a long string that spans three lines.""") This is a long string that spans three lines. 8/28/2018 29
The trouble with quotation marks But how to print: >>> print("""both ' and " are ok.""") Both ' and " are ok. Method 1: Use triple double quotes """. >>> print("""both ' and " are ok.""") Both ' and " are ok. Method 2: Use backslash \ to "escape". >>> print('both \' and " are ok.') Both ' and " are ok. >>> print("both ' and \" are ok.") Both ' and " are ok.? 8/28/2018 30
Escaping with backslash \ >>> print('it\'s snowing.') It's snowing. >>> print('lala\tlala') lala lala >>> print('lala\nlala') lala lala >>> multi = """This is a long string across multiple lines.""" >>> print(multi) This is a long string across multiple lines. >>> multi 'This is a\nlong string across\nmultiple lines.' 8/28/2018 31
Escaping with backslash \ >>> print('it\'s snowing.') It's snowing. >>> print('lala\tlala') lala lala >>> print('lala\nlala') lala lala >>> multi = """This is a long string across multiple lines.""" >>> print(multi) This is a long string across multiple lines. >>> multi 'This is a\nlong string across\nmultiple lines.' 8/28/2018 32
Special character and \ Prefixing backslash \ (=escaping) turns: A special character into a normal one SPECIAL NORMAL ' String delimiter \' Single quote character " String delimiter \" Double quote character \ Escape marker \\ Backslash character A normal character into a special one NORMAL SPECIAL n Alphabet n \n New line character t Alphabet t \t Tab character 8/28/2018 33
Practice 2 minutes Compose print commands to output the following: >>> print('look in C:\\temp\\note.') Look in C:\temp\note. >>> print('lisa said \'Look in C:\\temp\\note\'.') Lisa said 'Look in C:\temp\note'. >>> print('lisa said \'Look in C:\\temp\\note and find "my.txt".\'') Lisa said 'Look in C:\temp\note and find "my.txt"'. >>> print('roses are red,\nviolets are blue,\nsugar is sweet.') Roses are red, Violets are blue, Sugar is sweet. 8/28/2018 34
Practice 2 minutes Compose print commands to output the following: >>> print('look in C:\\temp\\note.') Look in C:\temp\note. >>> print('lisa said \'Look in C:\\temp\\note\'.') Lisa said 'Look in C:\temp\note'. >>> print('lisa said \'Look in C:\\temp\\note and find "my.txt".\'') Lisa said 'Look in C:\temp\note and find "my.txt"'. >>> print('roses are red,\nviolets are blue,\nsugar is sweet.') Roses are red, Violets are blue, Sugar is sweet. 8/28/2018 35
Wrap-up Exercise #1 Review today's lesson Learn on your own: String Methods 1, Boolean Operators Due 30 mins before next class (=Thu 4pm) Friday recitation Will send individual email tomorrow. Python installation/configuration: make sure you followed all instructions in "Getting Started" sections Next class More Python practice Study Tutorials 5, 7, 16, 17, 18 and Additional Topics 1, 2, 3 before class New to programming? Try to log a few additional hours! 8/28/2018 36