COMP 1012 Lecture 1 PDF

Title COMP 1012 Lecture 1
Course Computer Programming For Scientists And Engineers
Institution University of Manitoba
Pages 66
File Size 1.2 MB
File Type PDF
Total Downloads 20
Total Views 164

Summary

lecture notes...


Description

COMP 1012 Computer Programming for Scientists and Engineers Week of May 18th, 2020)

Part 1 of 3 Parts Who am I Introduction to The course Your environment

Who am I 🤖 Dr. Amir Hosseinmemar 🏠 Using Zoom Application link: 992 4824 9134 password: Kvc3jf7gYn 🕜 Class Time: T/W 8:00am - 9:50am, 10:00am - 11:50am, 4:00pm - 5:50pm Office hours: M/TH/F 12:00pm - 1:30pm, on Zoom ✉ [email protected] (from ICM e-mails only)

Administrivia

CC0 Creative Commons

Administrivia Course web page https://moodle.icmanitoba.ca/my/ ROASS - please read ASAP Schedule - consult on regular basis Lecture notes Other background materials and links Assignments and submissions Labs Online quizzes Honesty declaration - Please submit with your Assignment 1

Labs 🔧 10 labs in total Among the 10 labs, 2 labs are “Make-up” labs. Out of 10 labs, best 8 labs will be counted for the final grade. In weeks designated with “Make-up” labs, students can attend any lab section to get credit for an optional make-up lab. Weekly labs unless otherwise stated in schedule. Start next week on Zoom (Zoom link will be send to you by TA). Ensure you attend the lab section you are registered in. Labs will be out of 2 marks. Worth 10% of total grade

Assignments 4 assignments, first one will be out next week. Assignments are 10% Work must be your own (see Academic Dishonesty section below) You learn to program by writing programs and getting feedback on your work. See ROASS for more information

Quizzes 8 quizzes Usually weekly, online on the course website (except for term-test weeks) Starting next week. Worth 10% of total grade. Quiz will be every Friday, except for Week 1 and term-test weeks. Quiz will cover material up and including the previous lecture

Midterm(s) Two tests: Friday, June 26th at 6:30 pm Sunday, July 19th at 1:00 pm 60 minutes each, closed-book, online, Moodle Worth 40% total grade (20% each)

Final The final examination will be scheduled by registrar’s office (ICM) during final examination period. Worth 30% of total grade The exam will be on Moodle. To pass this course, you need to obtain 35% marks of the final exam. This means you have to obtain 10.5 out of 30 in the final exam.

Academic Dishonesty 🎓 Academic dishonesty is taken very seriously. Do not show any part of your assignment, quizzes, or midterm tests, or final to any unauthorized people. This includes posting to the internet, e-mailing, screenshots, etc. COMP1012 uses automated software 💻 to detect academic dishonesty.

Honesty Declaration Read and complete your honesty declaration online. Must be completed before you can submit the first assignment or see any grades.

Computer Science @ UManitoba

CC0 Creative Commons

COMP1012: Programming in Python, designed for Engineering and Science students. COMP1010: Programming in Processing, for everyone.

Computer Science @ UManitoba COMP1020: Second course in programming, in Java. COMP1010 or COMP1012 are prerequisites.

What the heck is this course about?

CC0 Creative Commons

What the heck is this course about? Introduction to problem solving with the intent of writing computer programs to implement your solutions to problems. Learning programming as a problem solving technique. Learn important and useful concepts and ideas for solving problems via computing programming. Programming solutions using Python. Concepts and ideas you learn in this course will be widely applicable and not specific to Python

Programming

Programming ? A very large part of this course will involve programming a computer. There are many (hundreds) different computer languages that can be used to program a computer. For example: Java, C, C++, Go, Pascal, Javascript, and so on. This course will use Python. Python is a high-level language. Translated by an interpreter. Python is pretty-straightforward and used a lot hot areas such as data science and machine learning. To become a good programmer, you need to practice programming

Problem solving CC0 Creative Commons

Problem solving © yug CC BY-SA 3.0

Problem solving © Samantha Cole

Problem solving CC0 Creative Commons

Where is this going to be useful? Prerequisites MATH 2120: Introductory Numerical Methods for Engineers ECE 2240: Numerical Methods for Electrical Engineers CIVL 3590: Numerical Methods for Engineering Analysis ECE 3730: Principles of Embedded System Design ECE 3700: Telecommunication Network Engineering ECE 3740: Systems Engineering Principles 1 MECH 2222: Mechanics of Materials MECH 3482: Kinematics and Dynamics

Tools We’re writing software in Python. What do you need to write and run a Python program? An editor – like Windows Notepad to write your Python (source) program An interpreter – to translate what you’re saying into something the machine understands There are many ways you can write and execute your Python programs We’re going to use the integrated development environment (IDE) Spyder We’re going to use Python 3.7 All comes with Anaconda https://www.anaconda.com/download/

Notepad Notepad??? ???

Er… No. But you can use Notepad or any other IDEs if you really want too!

5 easy ways to fail this course 1. Don’t learn your programming environment 2. Don’t fill in your honesty declaration 3. Cheating 4. Don’t keep up 5. Don’t have any fun.

Things To Do Claim your ID (if you haven’t already. . . ) You will need this to access lab computers (in ad (This is for on-campus) Go to https://umanitoba.ca/computing/ist/stud for details. Log on to https://moodle.icmanitoba.ca/my/ to access lecture notes, assignments, labs, examples Download and install Anaconda on your own comp one) Look around in Spyder

Demo Let’s look at the Spyder environment and write a very simple program or two from scratch. We’ll see Spyder and examples throughout the course. Code will be posted on the course website

Readings If you haven’t already, please read Why you should learn to write programs. All readings are stated in the schedule. You should do the assigned reading BEFORE the start of the lecture.

END of Part 1 of 3 Parts 1. 2. 3. 4.

Who am I Introduction to The course Your environment

Part 2 of 3 Parts We will Introduce integers and floating-point numbers and their operations. We will also introduce the concept of variables.

Numbers Numbers in Python are usually whole numbers (integers) or real numbers (floating point numbers). Integers are numbers like 2, -3, 0, -999, 10. Floating point numbers are numbers like -2.0, 3.14159, 2.7128E-19, 2.5e10. In Python, an integer is called an int and a floating point number is called a float. int and float are data types that are core to the Python language. Python also has a complex data type for representing complex numbers, which we won’t discuss at this point.

Numbers Obvious questions include: What happens when you add (or perform some other operation between) a whole number and a real number? How do you read in a number from a file or keyboard? How do I convert from a whole number to a real number and vice versa? These will all be dealt with as the course progresses.

The Basic Python Arithmetic Operators Name of Operator

Symbol

Example

Exponentiation

**

2 ** 3

Multiplication

*

2*3

Division

/

10 / 4

Floor Division

//

10 // 4

Modulus

%

102 % 13

Addition

+

1.35 + 2

Subtraction

-

10 - 2.5

Order of Operations Name of Operator Round brackets ( )

Precedence highest

** + - (unary operators) * / // % +=

lowest

Operators of the same precedence are evaluated from left to right except for ** which is evaluated from right to left.

Order of Operations: practice predict the following expressions: 2 ** ( 2 + 3 // 2 ) * 10 % 3 + 3 * 20 / 4 = ? 2**3**3 = ?

Arithmetic return types Math between ints results in an int For example, 3 * 3 = 9, 2 + 45 = 47, 2 ** 3 = 8 Except division ( 10/3 returns 3.333333. . . which is a float) (there’s always an exception) If there’s a float in the calculation, then result is a float For example, 3 + 3.5 = 6.5, 4 * 2.5 = 10.0, 2 ** 3.0 = 8.0 These are simple rules - you should remember them.

Example Computing Volume of a Sphere For a sphere of radius r its volume is given by

Suppose we assume the radius of a given sphere is 5. What is the Python expression to compute its volume?

Other operators What about the less familiar operators? // Integer division (floor divide) a//b returns which is the largest integer ≤ a/b. What does 5//2 return? % Modulus operator Returns the remainder of the division Think about old long division 5 / 2 => 2, remainder 1 So 5 % 2 returns 1

Exponents Easy syntax 5 ** 2 Or you can use the function pow pow(5,2) Both of these will compute Know both, use your favorite

Variables For a computer program to do anything useful, it must be able to store data. Variables are used to store data that is used by a computer program. Each variable has a name and stores a value. Variables can store the results of a calculation. Example: result = 42 + 42

result now holds the value 84. Each variable has a type, which is the data type of the data it is storing.

Variables Python is loosely typed. Don’t have to ‘declare’ a variable. Just make it up as you go. The type can changed (from float to int and more) Example: radius = 5 #type is int radius = 2.5 #type is float

The assignment operator = is used to assign a value to a variable.

Variables Probably one of the most important properties of a variable is that you can re-use them. At any given point in your code, a variable will store the last value that was assigned to it. As your program executes, the value of a variable may change depending on the statements that have been executed. Example: radius = 5 print(radius) radius = 2.5 print(radius)

The value of radius after executing the above 4 statements is 2.5.

Naming Variables Give them good, clear, meaningful names. They’re for the programmer, not the language/compiler Good variable names makes programs easier to understand. Good area = width * height

Bad a = w * h

Naming Variables Variables should be named clearly. This sometimes requires more than one word use: lower_case_separated_by_underscores lowerCamelCase

Either is fine. Personally, I prefer the latter. Be consistent in the style you use to name your variables. Example: numStudents = 146 classAverage = 65.75 numFailures = 76

Using variables Makes programs flexible height = 10 width = 100 area = height * width

Clearly names the variables, height and width can change, and the equation need not. What happens when you type “type(height)”?

Global Variables Global variables are variables that can be accessed from any part of your program. Global variables (final variables) should be used only for constants. PI = 3.14159 # Speed of light in m/s SPEED_OF_LIGHT = 299792458 # we can write here too

You should not change these (although not enforced). Global variables, if altered by a program, may lead to hard-to-find errors. Global variables will become more interesting when we start writing our own functions.

Comments Comments give context to people reading your program. Comments provide explanations to human readers of your code. # The speed of light, in metres per second SPEED_OF_LIGHT = 299792458

Without the comment, what does 299792458 mean? Use comments to make your code more readable to people trying to understand your code.

Magic Numbers A magic number is a constant number that occurs in your code without explanation. Example: totalPrice = salesPrice + salePrice * 0.12

There are several problems with this: what does the 0.12 represent? what happens if this value occurs in many places and at a later point we need to change it?

Magic Numbers A better solution would be to use a variable to hold the constant. TAX_RATE = 0.12 taxes = salesPrice + salePrice * TAX_RATE

Avoid using magic numbers in your programs.

Try these yourself Using the interactive console in Spyder, try the following expressions: 10 / 3 10 // 3 20 % 7 2 ** 8 2.5 * 3 3 + 3.14

Suppose you have a triangle whose height is 2.5 and base is 2. Write a Python expression to compute its area.

END of Part 2 of 3 Parts 1.

We will Introduce integers and floating-point numbers and their operations. 2. We will also introduce the concept of variables.

Part 3 Whitespace Calling Python functions Scripting Python (programs) Reading input from user and printing

Whitespace Which is the easiest to read? 42*3.1415926**2/10 42 * 3.1415926**2 / 10 42 * (3.1415926 ** 2) / 10

Within an expression in Python, whitespace is ignored by the language. The three expressions above gives the same result. Whitespace is important to human readers. Python code with spaces is much easier to read. Use whitespace in your programs to promote readability. We will see later that whitespace is also important functionally.

More Operations So far: limited to basic arithmetic operations (see part 2) Other operations available as functions in Python: trigonometric functions, square root, absolute value, floor, ceiling, and many more functions are available. One of the advantages of software development using Python is the abundance of functions that are available

Using Functions For now: think of functions as “Black boxes” You: provide all required inputs Function: responds with result of calculation (known as the output) Often, functions return a result. This is known as the return value of the function. For example, the function call cos(x) returns a float specifying the cosine of x in radians. Many basic math functions are in the math module (must be imported) This is a very useful module for doing scientific calculations.

The math module Either in a script (aka a program) or in a Python console First, import the modules so that it can be used import math All the math functions available at: https://docs.python.org/3/library/math.htm Once a module has been imported, you can start using the functions (and other stuff) in the module.

Example: functions Let’s calculate the hypotenuse of a right-triangle using Pythagoras:

Scripting So far: evaluating expressions in the IPython console. Consoles are good for doing some simple calculations and scratch work. Problem: What happens when I close Spyder? We need to save our expressions in a script What is a script? A series of statements in a file (ending with .py) Statements are executed sequentially (one after the other) File can be executed by the interpreter. Let’s move some expressions to the script area

Scripting A script doesn’t produce any output. We need to explicitly tell Python we want to produce output. Python programs are usually written as scripts. You write your program using an editor (such as Spyder) and save it with a .py extension. Since it is in a file, you can modify it as necessary. You can run your program using a Python interpreter (from within Spyder) or from the command line

Reading Input The Python function input( ) is used to read in a string from the console/keyboard. A string is a sequence of characters. We’ll say more about strings in the following weeks. The input() function is very easy to use. Specify a display string (which is the input to the function). The function returns a string that was entered from the keyboard. An obvious question you may have is: What if my input is suppose to be a number instead of a string, like the radius of a sphere? We’ll deal with that next week

Reading Input Example: firstName = input("What is your first name?") lastName = input("What is your last name?")

Printing Printing is a function in Python: print( ) We can print: literals (strings, numbers) Results of expressions You can specify multiple items to print, separated by a comma.

Printing Example: import math # need it to access pi print("Hello, world") print(1012) print(100 * 3.14) x = 60 * math.pi y = 2.0 * math.pi print(x,y)

END of Week 1 (Part 3 of 3 Parts) 1. 2. 3. 4.

Whitespace Calling Python functions Scripting Python (programs) Reading input from user and printing...


Similar Free PDFs