970 likes | 1k Views
CS 105 – Intro. What is this class about? Problem solving Examples from secret communication How a computer system works Read “guiding principles” in syllabus What is computer science? Relatively new discipline Start with the basics today:
E N D
CS 105 – Intro • What is this class about? • Problem solving • Examples from secret communication • How a computer system works • Read “guiding principles” in syllabus • What is computer science? • Relatively new discipline • Start with the basics today: • How information is represented inside the computer
What is CS? • Computer science is the study of how to solve problems • Representation of information • Classify various problems • Seek systematic ways to solve them • The computer is just a machine to help us in the process • “Solve a problem” ? • The solution is not just a single word or number. • Goal is to provide the necessary steps to get an answer • It’s all about the journey, rather than the destination! • Example – how do you calculate a GPA? • The answer is not a number, but a procedure.
(continued) • Correct solution = we always get the right answer when we follow the steps • In other words… If we work through the steps, and the final answer is wrong, then there was a mistake in our solution. • This course is about • How to solve problems in general on the computer • Apply these principles to a particular problem domain, e.g. secret communication
Consider … • Since you woke up this morning, what “problems” did you have to work out? Did you follow a sequence of steps that you figured out in the past? • If you had to describe the computer with one word, what would it be? • I’ve got some “information” on a little piece of paper. How would you describe or characterize this information? • Some aspects are important, others are not
Binary • Information includes: numbers, text, sounds, images, video. • All must be stored as 0’s and 1’s! • Bits and bytes • Numbers: • interpreting: binary decimal • encoding: decimal binary • If time permits, shorthand ways of writing binary
Some terminology • All information in computer is in binary form (0/1) • Smallest unit of information is the bit: a single 0 or 1 • When we have lots of bits, usually grouped in set of 8 called a byte • Basic building block of CPU is the logic gate, which manipulates bit values. • Very fast • Logic gates combine to perform math operations
Numbers in binary • Place value system just like decimal • We understand 278 = (2 * 100) + (7 * 10) + (8 * 1) • In a binary number: • Each digit is either a 0 or 1 • Digits are multiplied by powers of 2, not powers of 10. • For example, 001110 and 100011:
Powers of 2 • 20 = 1 • 21 = 2 • 22 = 4 • 23 = 8 • 24 = 16 … • 210 ~ 1 thousand • 220 ~ 1 million • 230 ~ 1 billion • Let’s say we have 4 bits. • What is the lowest # ? • What is the highest # ? • What if we had 5 bits? • Is there a pattern?
Questions • Estimate the values of 216 and 234. • Let’s go the other way! Which powers of two are near… • 4 billion • 128 thousand • 2 million
There are 10 kinds of people in the world. Those who understand binary, and those who don’t.
Decimal binary • One thing to note is that binary numbers are “longer” than decimal. • A 5-digit decimal number may turn out to be 15 bits long. • My technique is the “binary store” • All merchandise is priced $1, $2, $4, $8, $16, … • You enter store with some money, say $45. • Goal is to always buy most expensive gift possible. • So, 45 = 32 + 8 + 4 + 1
Another example • Convert 61 to binary: • Go to binary store with $61… 61 = 32 + 16 + 8 + 4 + 1 Another way to write this is: 61 = 25 + 24 + 23 + 22 + 20 • Our binary answer is 111101.
Octal • Octal means base 8: each digit is a power of 8. • Because 8 = 23, each octal digit corresponds to 3 bits. • Examples, converting to octal • 671 = 110 111 001 • 7325 = ? • Can we convert the other way?
Hexadecimal • Called “hex” for short • Base 16: each digit is a power of 16 • Since 16 = 24, each hex digit corresponds to 4 bits. • Hex also means that we have 16 different digits • a = 10, b = 11, c = 12, d = 13, e = 14, f = 15
Hex examples • Converting into binary • 964 = 1001 0110 0100 • D123 = 1101 0001 0010 0011 • Converting into hex: • 111000 = ? • 10011111 = ?
Decimal octal, hex • Often, the best way to come up with octal or hex is to go thru binary first. • Example: What is 71 in octal? • Binary store gives: 71 = 64 + 4 + 2 + 1 • Binary number is 1000111 • Grouped as octal: 001 000 111 = 1078 • We can check answer.
Why couldn’t the computer scientist tell the difference between Halloween (Oct 31) and Christmas (Dec 25) ?
CS 105 – First look • Computer program • Definition • Appearance • Things we see in a computer program • Comment(s) • Input, calculations, output • Python details we need to know about • Running a program
Some questions • What is a computer program? • What does a computer program look like? • Does a program resemble anything you have seen before? • What little things do we seen in a computer program? • How can we tell if it works correctly or not? • If incorrect, what could have gone wrong?
How to answer “what is” • what it consists of • what it resembles, is analogous to • how it behaves • how life would be different without it • what it is NOT • its purpose
Program • A computer program is a list of instructions written in a computer language that solves some problem. • Python is a computer programming language. • The program is submitted to the computer. • We run the program. • While the program is running, it may ask for input from you. • When finished, look for the program’s output.
Gross anatomy • A simple program will have these elements: • Comment(s) • Input statement(s) • Calculation statement(s) • Output statement(s) • See example on page 39 • Eventually: could we modify this program so that it does something with rectangles instead of circles? • Comments may appear anywhere in the program. Highly recommended to put one at the beginning.
Example 1 # hello.py# This program will ask the user to enter# his/her name, and then say hello to that person.# This program contains no calculations.# inputname = input("Please tell me your name: ")# outputprint("Hello, ", name, ", nice to meet you!")
Example 2 # animals.py # Let’s illustrate simple I/O and calculations. # Add up how many animals on a farm. horses = int(input("How many horses? ")) pigs = int(input("How many pigs? ")) chickens = int(input("How many chickens?")) total = horses + pigs + chickens print("You have a total of ", total, " animals.")
Important elements • Statements • Performs one step of the program. Each “line of code” may have one statement. • There are several kinds of statements. • Variables • Name of a variable sometimes called an identifier • Type • Constants • Expressions • Can appear on right side of "=“ • Can output
Easy to read? • Whitespace • Spaces, tabs and newlines are generally ignored. • Readability: put a space on either side of an operator • Indentation • Statements that need to be grouped together are indented. • We won’t need to do this yet. • Continuation • Lines should not go past 80 characters. If you have a long statement, put \ at end of line, and continue the statement on the next line.
Variable name • a.k.a. identifier • Must begin with a letter or underscore • After first character, may include letters, digits, or underscores. • May not be a keyword (reserved word) • Certain words already have meaning in Python. • See page 47 for list.
Assignment stmt. • See pp. 50 – 52. • Used to introduce a variable for the first time • Or, to reassign a value. • Example: x = 5 • If the variable x has never been used before, the Python system will create a new variable, and store the value 5 in it. • If the variable x already exists, its old value is overwritten with the value 5. • You will not be warned if a variable already exists or not.
Remainder of Ch. 1 • Nuance between variable and object/value. • We intuitively understand variables in our program. • Behind the scenes, Python maintains objects • The “namespace” is the association between our variables and the system objects or values. • Types • Operators, including shortcut assignment • What is an algorithm? • Review questions at end of chapter.
Variables • Variable name should be meaningful • Count is more descriptive than x. “Count” implies an integer value. • Type is associated with a value or “object” rather than the variable itself. • In other words, a variable can change type! • Constructor functions allow us to convert types. • int(“4”) and int(4.7) both return 4 • float(4) and float(“4.0”) both return 4.0 • str(92) returns “92”
Notes on operators • / does exact division • // is for truncated or “floor” division • % calculates modulo, a.k.a. mod, remainder • Ex. What day of the week is it 30 days from now? • Ex. Leap year • Ex. How many pennies are needed for 58 cents? • ** means exponentiation • Right associative • Can you work out: 30 – 3 ** 2 + 8 // 3 ** 2 * 10 ?
Shortcut assignment • Examples: += -= *= /= %= • Suppose we want to increment the variables usa_grid_polygon_x and usa_grid_polygon_y by 1. What is wrong with this: usa_grid_polygon_x = usa_grid_polygon_x + 1 usa_grid_polygon_y = usa_grid_polygon_x + 1 • With an operator like +=, we only need to type the variable name once, as in: usa_grid_polygon_x += 1
Algorithm • A list of instructions written in English that explains how to solve a problem. • How is this different from a computer program? • Even though an algorithm is in English, it needs to be • Unambiguous • Detailed • Deterministic: As we “control” the CPU, we should always be clear where the next step is, and when we are finished. • Examples?
CS 105 – Chapter 2 • Program is list of instructions • In what order are the steps performed? • By default, in the order specified • Other ways to structure our “code”: • Making choices, allowing some steps to be skipped • Repetition of some steps • Python keywords we’ll see to handle this: • if, else • while, for
Some remarks • Basic structure √ • A program needs to have output • Output is based on calculations • Calculations are based on input • We can solve more problems if we allow our programs to make choices, ask questions about: • Input values • Results of calculations • A program can decide which path to follow based on whether the answer is yes or no.
if-statement • Sometimes, we need our program to make a decision, based on what’s in our variables • Format of an if-statement in Python if <condition>: # steps to perform if <condition> is true • Optionally, we can include an “else” statement. if <condition>: # steps to perform if <condition> is true else: # steps to perform if <condition> is false
The condition • An if-statement is essentially asking a question, usually about the value in a variable. • Comparisons are done with a relational operator: < > <= >= == != • The result of a comparison is boolean (True or False). • It’s possible to ask multiple questions, combined with the words “and” or “or”
Example # input n = int(input("Enter an integer: “)) # tell user if it’s positive if n > 0: print("Your number is positive.") # ---------------------------------------- # tell user if number is odd or even if n % 2 == 0: print("Your number is even.") else: print("Your number is odd.")
Syntax notes • Colon required • At end of line introducing the if-statement • At end of line containing the word “else” • You need to indent • The body of the if-statement • The body of the else clause • Indentation required • Body may contain several statements • Your editor might automatically indent for you. If not, hit space 4 times.
Practice • Write if conditions for these situations. • Let’s say we are dealing with an integer called n. • The number is between 5 and 25 inclusive. • Less than 12 or equal to 95. • Even and less than 100. • Between 10 and 20, or between 80 and 90. • Ends in 7. • Is neither 13 nor 17. • Compare two numbers x and y. • y is positive, and x is strictly between 0 and y.
Leap year • Easy (Julian) definition • The year must be divisible by 4 if year % 4 == 0: print("Leap year") else: print("Not a leap year") • Actual (Gregorian) definition • If the year ends in 00, must be divisible by 400. • If the year doesn’t end in 00, must be divisible by 4.
Repetition • In Python, we use a while statement to allow some statements to be performed several times. • Format of while is very similar to if. while <condition>: # steps that will be repeated • Doing the body each time is called an iteration. • When the body of the while is finished, Python will re-evaluate the condition. If it’s still true, the body is performed again. The process repeats. • At some point, the condition must become false!
Counting print("I’m going to count to 5:") n = 1 while n <= 5: print(n) n += 1 print("I’m finished counting.") # If we can count to 5, we can easily modify # the code so we can count to 1000.
Counting by 5’s print("Let’s count by 5’s from 0 to 100.") n = 0 while n <= 100: print(n) n += 5 # ------------------------------------------- # How would we modify this program # to print in reverse order? 100 down to 0
Prime number • A positive integer that has exactly 2 factors, 1 and itself. Examples: 2, 3, 5, 7, 11, 13, … • How can we tell if n is prime? • For each possible divisor from 1 to n, see if it divides evenly into n. • We need to count how many times a divisor goes in evenly store in another variable. • When done, see if the count is 2.
Examples • Is 5 prime? • Try the possible divisors 1, 2, 3, 4, 5 • 1 yes, 2 no, 3 no, 4 no, 5 yes • We counted 2 divisors. Prime! • Is 6 prime? • Try the possible divisors 1, 2, 3, 4, 5, 6 • 1 yes, 2 yes, 3 yes, 4 no, 5 no, 6 yes • We counted 4 divisors. Not prime!
Prime code n = int(input("Enter a positive integer: ")) # The divisor goes from 1 to n inclusive, just # like we are able to count from 1 to n. # Also, start count at 0. count = 0 divisor = 1 while divisor <= n: if n % divisor == 0: count += 1 divisor += 1 if count == 2: print("Your number is prime.") else: print("Your number is not prime.")
CS 105 – Section 2.2 • Programs often need several variables • More on the if-statement • Sometimes we have more than 2 alternatives • More on loops • If we can count, we can also sum. • Asking the user for several values • Common mistakes • Error checking of input • For loop vs. while loop • Nested loop • Break & continue
Several alternatives • Examples • Testing for positive / negative / zero • Converting numerical grade to letter grade • General format if <condition 1>: # steps if condition 1 is true elif <condition 2>: # steps if condition 2 is true # You can have as many elif’s as needed... else: # steps if all conditions were false
if value > 0: # do positive case elif value < 0: # do negative case else: # at this point, we # we know it’s zero! if grade >= 90: letter = 'A' elif grade >= 80: letter = 'B' elif grade >= 70: letter = 'C' elif grade >= 60: letter = 'D' else: letter = 'F' Answers