Download presentation
Presentation is loading. Please wait.
Published byRoss Briggs Modified over 9 years ago
1
TM 331: Computer Programming Introduction to Class, Introduction to Programming
2
Outline for Today Course Description –What material will we cover? –What am I getting myself into? Administrative Issues –Course Web Page, Text Book, Exams, Office Hours, Homework, Grading, etc. Syllabus Intro. to Programming Languages and Python Reading –Section 1 of the text. First assignment – Exercises at the end of Section 1 (page 16). 2
3
Catalog Description Study of computing systems manipulation using a current programming language. Includes input/output techniques, program processing control, file processing and database interfacing. 3
4
What the class is really about There are three main goals of this course: 1. Basics of Python 2. Core Concepts of Programming Languages 3. Using programming to solve mathematics and science problems 4
5
Basics of Python Python is a popular programming language, with an emphasis on readability. We will learn all the specifics of how to program in Python. This includes all the peculiar rules that are specific to Python. We will cover the fundamentals: Variables, Arithmetic, If / Else, For Loops, While Loops, Arrays, Methods, etc. 5
6
An Example /* Sample Python Program */ i = 1 while i <=10: print i i += 1 This program counts from 1 to 10. In a few weeks all of the details, including the colon and the indention, will make sense. 6
7
Concepts of all Programming Languages There are many programming languages available: Python, Java, C, C++, etc. All of these languages share core concepts. By focusing on these concepts, you are better able to learn any programming language. Hence, by learning Python, you are poised to learn other languages, such as C++ or Java. Note: Python is an object oriented programming (OOP) language. However, we won’t be discussing this aspect very much. 7
8
An Example: For Loops Python has a construct called a for loop that enables a program to repeat actions over and over. Most other languages also have a for loop. Hence, by learning about for loops in Python, you can easily learn for loops in Java or C. 8
9
Comparing For Loops # Sample Python # for Loop for i in range(10): print i+1 /* Sample JavaScript for Loop */ var i; for (i = 1;i < 11;i++) { console.log(i); } 9 Both of these also count from 1 to 10. Compare the readability of Python vs. JavaScript.
10
Course Web Site Course web site is available at: http://www.piedmont.edu/math/jroberts/teaching/t m331s13.html Web site contains the following information: –Course Syllabus –Class text –Homework assignments –Class notes –Class programs 10
11
Chapter 1 : Why Program? Our primary motivation is to be more productive in handling data and info Most of us are “end-users” of programs on computers, phones, etc. By the end of this course, you will be on your way to being the programmer and the end-user. 11
12
1.2 - Computer Hardware 12 CPU – Always asking “What’s next?” 1.0 Gigahertz = “what’s next” 1 billion times per second Main memory – store info computer needs quickly. Gone when computer is turned off. Secondary Memory – Slower to access than main memory, but stays even without power. I/O devices – Screen, keyboard, etc. Ways to interact with the computer Network – Can be thought of as a slower, unreliable form of secondary memory.
13
13 Programmers answer the CPU’s “What next?” question. You may talk to the CPU and tell it to use the main memory to do something. The instructions to the CPU is a program.
14
Hardware Trends Every year or two the following approximately double (Moore’s Law): –Amount of memory in which to execute programs –Amount of secondary storage (such as disk storage) Used to hold programs and data over the longer term –Processor speeds The speeds at which computers execute their programs 14
15
1.4 - Programming – Vocabulary Vocabulary to talk to CPU Python’s vocabulary is small – reserved words like and, for, elif, try. Writing programs involves teaching Python new words, variables. Cannot use reserved words as variables. 15
16
1.5 - Programming - Language Simply sing the correct vocabulary is not enough. We must speak in a language Python understands. >>>I come in peace, take me to your leader Syntax error! >>>print ‘I come in peace, take me to your leader’ 16
17
If you use a word that is not a reserved word and not declared to be a variable, Python will give you a Name Error. >>>good-bye 17
18
1.6 - Interpreters and Compilers Computers cannot understand human- language. They understand machine- language. Machine-language is all ones and zeros. To get a computer to understand a high- level language like Python, we have to translate. 18
19
Interpreters The first type of translator is an interpreter. Interpreters read the source-code a programmer writes, parses the code, and interprets it on-the-fly. Interpreters can be interactive. Python is an interpreter. 19
20
Example >>> x = 6 >>> print x >>> y = x * 7 >>> print y 20
21
Compilers Compilers need to have the entire program written into a file. It runs a process to convert the program to machine-language, and saves this for later use. File extensions such as “.exe” (executable) and “.dll” (dynamically loadable library) are examples. C is a compiled language. 21
22
Rest of Today Work through the rest of Section 1 Begin Homework problems 22
23
Chapter 2 and 3 were presented in lecture format in the classroom. 23
24
Chapter 4: Functions A function is a named sequence of statements that performs computations. You ‘call’ the function by name. >>>type(32) The function name is type. 24
25
Functions take arguments and returns a result. >>>type(32) In this case, type takes the argument 32 has a return value of int. 25
26
4.2 - Built in Functions max and min of a list >>> max('Hello world') >>> min('Hello world') Length function >>> len('Hello world') >>> len([1,2,3]) >>> len(125) 26
27
4.3 - Type conversion - int() Value to integer >>> int('32') >>> int('Hello') Doesn’t round floats >>> int(3.99999) >>> int(-2.3) 27
28
Type conversion – float() & str() float() converts integers and strings to floating point numbers >>> int(-2.3) >>> float('3.14159') str() converts its argument to a string >>> str(32) >>> str(3.14159) 28
29
4.4 - Random numbers Programs that generate the same output every time are deterministic. Truly nondeterministic programs are hard to make. Most of the time we use pseudorandom numbers. 29
30
random module The module random generates (pseudo) random numbers. random returns a floating point greater than or equal to 0.0 and strictly less than 1.0. import random for i in range(10): x = random.random() print x 30
31
More randomness Other options for random numbers are random integers between two other integers >>> random.randint(5, 10) Choosing a random element of a list >>> t = [1, 2, 3] >>> random.choice(t) 31
32
4.5 - Math Functions Go ahead and import the math module >>> import math >>> print math >>> help(math) 32
33
Python math documentation. http://docs.python.org/2/library/math.html 33
34
As with the random module, we have to use dot notation to call math functions. >>> radians = 0.7 >>> height = math.sin(radians) >>> math.pi 34
35
Recall to convert from degrees to radians, divide by 360 and multiply by 2pi. >>> degrees = 45 >>> radians = degrees / 360.0 * 2 * math.pi >>> math.sin(radians) 35
36
Digression on Scripts and Directories Go to Start – All Programs – Python 2.7 – IDLE (Python GUI) This opens the Python Shell, which looks a lot like the command line interface. Instead of ‘arrow up’ and ‘arrow down’ giving the history, you can use alt-p for ‘previous’ and alt-n for ‘next.’ (Or you can just remap the keys in Options) 36
37
The advantage to using the shell is that you have a nice scripting program nearby. In the shell, click File – New Window (or hit ctrl-n) This opens a new window inside the Python GUI We can use this to type long (or short) sequences of code to be used again and again. 37
38
In the new windows enter the following commands (with no indentation) hi = “Hello world!” print hi Run the program by clicking Run – Run Module or by hitting F5. You’re asked to save the file first. For now save it in the default directory as ‘hello.py’ Run in shell with >>> execfile(‘hello.py’) 38
39
Storing Class Files in SkyDrive Navigate to www.skydrive.live.com.www.skydrive.live.com Log in with your lions email and password. Create a folder to store all your Python scripts for this class. Make a new folder on the Desktop and name it Python. 39
40
Go back to the edit window in Python and save the ‘hello.py’ file into the ‘Python’ folder on the Desktop.’ In the Python shell, File – Open and navigate to the ‘hello.py’ file in the ‘Python’ folder. The ‘Python’ folder is now your current working directory. Anything you save will save here and execfile() will run files from here. Now any work you do can be uploaded/dowloaded to/from SkyDrive. 40
41
4.6 - Creating New Functions In a new edit window in Python, type the following code: Def print_lyrics(): print “I’m a lumberjack and I’m okay.” print ‘I sleep all night and I work all day.’ (Notice the use of quotation marks.) (Scripting in IDLE isn’t the best thing to do. We’ll learn better ways later.) 41
42
Run the function with F5 (and save it into your desktop Python folder). On the shell, check the type of the function you just created. >>>type(print_lyrics) 42
43
Once functions are defined, you can use them in other functions. From the shell def repeat_lyrics(): print_lyrics() Call the function with repeat_lyrics() 43
44
4.9 - Parameters and Arguments In the edit window or the shell, enter def print_twice(bruce): print bruce Putting something inside the parenthesis tells Python that our function takes an argument. 44
45
The function works with anything that can be printed. print_twice(‘Hello world!’) print_twice(17) print_twice(‘Hi’*4) import math print_twice(math.sin(math.pi/2)) We can use variables in functions. montyPython = ‘A funny show.’ print_twice(montyPython) 45
46
Quiz on Section 4.10 on Tuesday 46
47
Chapter 5: Iteration It’s common to update assignments of variables in terms of the variables themselves. >>> x = x+1 We have to initialize the variable first. >>> x = 0 >>> x = x+1 >>> x 47
48
5.2 – The while statement Computers are good at automated repetitive tasks. People aren’t. Using while is one type of iteration. n = 5 while n > 0: print n n = n-1 print 'Blastoff!' 48 Pay attention to the indentation.
49
49 while [condition]: [action if true] [action if false] (Note the possible looping behavior)
50
5.3 – Infinite Loops while True: print “I can’t stop!” print ‘Help!’ You can kill the loop with ctl-c. 50
51
5.4 – break ing infinite loops You may want an infinite loop on purpose and use break to get out of the loop. Look at the following code that keeps asking for input until the user types done. while True: newLine = raw_input(‘=>’) if newLine == ‘done’: break print newLine print ‘Done!’ 51
52
5.5 – Finishing iterations with continue If you are in an iteration and want to finish the current one and jump straight to the next, you can use continue to skip the next iteration. The next example copies the user’s input until the user types ‘done’, but lines that start with a hashtag aren’t printed. 52
53
while True: newLine = raw_input(‘=> ') if newLine[0] == '#' : continue if newLine == 'done': break print newLine print 'Done!' 53
54
5.6 – Loops using for The while loop is an indefinite loop; it loops until a condition is False. If we have a list or set of things to loop through, we construct a definite for loop. actors = [‘Denzel’, ‘Harrison’, ‘Sean’] for actor in actors: print actor + ‘: I love his movies!’ print ‘Done!’ 54
55
Denzel: I love his movies! Harrison: I love his movies! Sean: I love his movies! Done! The variable actors is a list of three strings and the for loop goes through the list and executes the body once for each of the strings. 55
56
56 for [var] in [list]: [statement(s)] (Note the indentation and the looping behavior.) for and in are reserved words in Python.
57
5.7 – Loop patterns Many times we use loops to go through a list or file searching for something like the largest or smallest value of a data set. 1.Initialize one or more variables before the loop starts. 2.Perform a computation on each item in loop body, maybe changing the variables. 3.Look at the resulting variables when the loop completes. 57
58
5.7.1 – Counting & Summing Loops To count the number of items in a list, we could write this for loop. count = 0 for itervar in [3, 41, 12, 9, 74, 15]: count = count + 1 print ‘Count: ‘, count 58
59
A similar loop that finds the total of a set of numbers. total = 0 for itervar in [3, 41, 12, 9, 74, 15]: total = total + itervar Print ‘Total: ‘, total Our counting and summing loops aren’t really that useful in practice. The built in function len() counts the number of items in a list and sum() computes the total of the items in a list. 59
60
5.7.2 – Maximum & Minimum loops largest = None print ‘Before:’, largest for itervar in [3, 41, 12, 9, 74, 15]: if largest is None or itervar > largest: largest = itervar print ‘Loop: ‘, itervar, largest print ‘Largest: ‘, largest 60
61
Before: None Loop: 3 3 Loop: 41 41 Loop: 12 41 Loop: 9 41 Loop: 74 74 Loop: 15 74 Largest: 74 61
62
Daily Grade Write a similar function that finds the smallest of a list of numbers. 62
63
Chapter 6 was presented in lecture format in the classroom. 63
64
Chapter 7 Recall our earlier diagram of a computer. 64
65
We’ve been writing programs to communicate with the CPU. Most of the time we restricted ourselves to the Main Memory. But anything in the Main Memory is lost when the power is cut off. In this section, we’ll start using Secondary Memory more and more. We’re going to write and edit our files in Notepad++ and run Python in the terminal window. 65
66
Remember SkyDrive Navigate to www.skydrive.live.com.www.skydrive.live.com Log in with your lions email and password. Create a folder to store all your Python scripts for this class. Make a new folder on the Desktop (or wherever) and name it ‘Python’. 66
67
Open Notepad++ and make a simple Python file. name = raw_input(“What’s your name?\n”) print “Nice to meet you, “ + name + “!” Save this file as hello.py in your previously created directory. Start Run cmd 67
68
(Windows) Terminal Commands When in the command prompt (or terminal), we need to be able to navigate to different files and folders. See handout for some commands. cd – change directory dir – List files & folders in a directory Navigate to your Python directory. python hello.py Start Python, then …. execfile(‘hello.py’) 68
69
7.2 – Opening files Save the file at www.py4inf.com/code/mbox.txt to your Python folder. >>> fhand = open(‘mbox.txt’) >>> print fhand We have a file handle in read only mode, not the actual data in the text file. 69
70
7.3 – Text files and lines A text file is a sequence of lines similar to how a Python string is a sequence of characters. Open mbox.txt in Notepad++. The is broken into lines by the newline character that just means “end of the line”. Represented in Python by \n. In strings, \n counts as a character. 70
71
>>> stuff = ‘Hello\nworld!” >>> stuff ‘Hello\nworld!’ >>> print stuff Hello world! >>> stuff = ‘X\nY’ >>>print stuff X Y >>>len(stuff) 3 71
72
7.4 – Reading Files While a file handle doesn’t contain the data for the file, we can use it get information. In Notepad++ save this as open.py. fhand = open(‘mbox.txt’) count = 0 for line in fhand: count = count + 1 print ‘Line count:’, count 72
73
In Python, >>> execfile(‘open.py’) Quit Python with the command quit() From command prompt, python open.py 73
74
fhand = open(‘mbox.txt’) count = 0 for line in fhand: count = count + 1 print ‘Line count:’, count Using for on a text file loops through the lines of the file. 74
75
This is an efficient way to get info about the text file. The loop doesn’t read the entire file at once (which may be LARGE). It reads a line, adds 1 to count and then forgets that line from main memory. Modern data sets can contain terabytes of information, so you wouldn’t (or couldn’t) store them in main memory. 75
76
If you know your file is relatively small, you can store all of it into main memory with the read method. Download and save the file at www.py4inf.com/code/mbox-short.txt >>> fhand = open(‘mbox-short.txt’) >>> inp = fhand.read() >>> print len(inp) 94626 >>>print inp[:20] From stephen.marquar 76
77
Only use open and read in this way if you know the file will fit into comfortably in the main memory of your computer. Otherwise, use for or while loops and read the file in chunks. 77
78
7.5 – Searching through a file We can use the string method startswith to find specific lines from files. The code below prints out only the lines that begin with “From:”. fhand =open(‘mbox-short.txt’) for line in fhand: if line.startswith(‘From:’): print line 78
79
Notice that your output has blank lines between the printed line. This is due the hidden newline character. The print command prints the lines in the string, which include a newline at the end, but then print adds another newline. One way to fix this is to use string slicing to remove the last character from each line. The method rstrip works better. 79
80
The rstrip method strips whitespace from the right side of a string. fhand = open(‘mbox-short.txt’) for line in fhand: line = line.rstrip() if line.startswith(‘From:’): print line 80
81
Using continue An alternative way to do the same thing that is sometimes useful is continue. fhand = open(‘mbox-short.txt’) for line in fhand: line = line.rstrip() #Skips uninteresting lines if not line.startswith(‘From:’): continue #Process interesting lines print line 81
82
Searching through text The string method find can be used search for a string in lines of a file The find method looks for an occurrence of a string and returns position of the string or returns -1 if it’s not found. The next bit of code looks for lines that contain the string ‘@uct.ac.za’. 82
83
fhand = open(‘mbox-short.txt’) for line in fhand: line = line.rstrip() if line.find(‘@uct.ac.za’) == -1: continue print line 83
84
7.6 – User chooses filename In practice, we wouldn’t write the name of every text file into a different file. fname = raw_input(‘Enter the filename: ‘) fhand = open(‘fname’) count = 0 for line in fhand: if line.startswith(‘Subject:’) : count = count + 1 print ‘There were’, count, ‘subject lines in’, fname 84
85
Save this previous code as search6.py and execute the file. When prompted, enter the file name mbox.txt Run it again with mbox-short.txt Question: What could possibly go wrong? 85
86
7.7 – Using try, except, and open Try executing that code again and entering a file that doesn’t exist or a gibberish name. We can fix this using a try/except combo. 86
87
fname = raw_input(‘Enter the file name: ‘) try: fname = open(fname) except: print ‘File cannot be opened:’, fname exit() count = 0 for line in fhand: if line.startswith(‘Subject:’): count = count + 1 print ‘There were’, count, ‘subject lines in’, fname 87
88
The exit function The exit function used above terminates the program at that point. This function never returns. Try executing the function again with bad or gibberish file names. 88
89
7.8 – Writing Files If we want to write onto a file, we open it in with ‘w’ as a second parameter. >>> fout = open(‘output.txt’, ‘w’) >>> print fout Careful! If the file exists, opening it in write mode clears the file. Otherwise, it creates a new file. 89
90
The write method used on the file handle writes data into the file. >>> line1 = “This here’s the wattle,\n” >>> fout.write(line1) Using write again puts the text at the end of the file >>>line2 = ‘the emblem of our land.\n’ >>> fout.write(line2) 90
91
Always be close ing After finished writing, you have to close the file to guarantee your changes are saved. >>> fout.close() In Notepad++, check the file that you just created. 91
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.