910 likes | 1.2k Views
TM 331: Computer Programming Introduction to Class, Introduction to Programming. 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
E N D
TM 331: Computer ProgrammingIntroduction to Class,Introduction to Programming
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
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
What the class is really about There are three main goals of this course: 1. Basics of Python • Core Concepts of Programming Languages • Using programming to solve mathematics and science problems • 4
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
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
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
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
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); } Both of these also count from 1 to 10. Compare the readability of Python vs. JavaScript. • 9
Course Web Site • Course web site is available at: http://www.piedmont.edu/math/jroberts/teaching/tm331s13.html Web site contains the following information: • Course Syllabus • Class text • Homework assignments • Class notes • Class programs • 10
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.
1.2 - Computer Hardware • 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.
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.
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
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.
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’
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
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.
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.
Example >>> x = 6 >>> print x >>> y = x * 7 >>> print y
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.
Rest of Today • Work through the rest of Section 1 • Begin Homework problems
Chapter 2 and 3 were presented in lecture format in the classroom.
Chapter 4: Functions • A function is a named sequence of statements that performs computations. • You ‘call’ the function by name. >>>type(32) <type ‘int’> • The function name is type.
Functions takearguments and returns a result. >>>type(32) <type ‘int’> • In this case, type takes the argument 32 has a return value of int.
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)
4.3 - Type conversion - int() • Value to integer >>> int('32') >>> int('Hello') • Doesn’t round floats >>> int(3.99999) >>> int(-2.3)
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)
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.
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
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)
4.5 - Math Functions • Go ahead and import the math module >>> import math >>> print math >>> help(math)
Python math documentation . http://docs.python.org/2/library/math.html
As with the random module, we have to use dot notation to call math functions. >>> radians = 0.7 >>> height = math.sin(radians) >>> math.pi
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)
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)
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.
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’)
Storing Class Files in SkyDrive • Navigate to 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.
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.
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.)
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)
Once functions are defined, you can use them in other functions. From the shell def repeat_lyrics(): print_lyrics() print_lyrics() Call the function with repeat_lyrics()
4.9 - Parameters and Arguments • In the edit window or the shell, enter def print_twice(bruce): print bruce print bruce • Putting something inside the parenthesis tells Python that our function takes an argument.
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)
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 Adding 1 is called an increment, subtracting 1 is called a decrement
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!' Pay attention to the indentation.
while [condition]: [action if true] [action if false] (Note the possible looping behavior)
5.3 – Infinite Loops while True: print “I can’t stop!” print ‘Help!’ • You can kill the loop with ctl-c.