Objectives



Day #1: Programming, Python ArithmeticObjectivesAfter today, you should know how to:Identify the four basic data types in PythonExplain the difference between int and float.Explain the difference between strings that look like ints and floats and actual ints and floats.Identify the six relational operators in Python.Identify the three Boolean operators in Python.Explain what a variable is.Explain what a reserved word is.Explain how an assignment statement works.Name the rules for creating identifiers (variable names) in Python.Name the four basic arithmetic operators in Python (+, -, *, /).Name and explain the function of the three additional arithmetic operators in Python (//, %, **).Name the precedence rules for evaluating arithmetic expressions in Python.Read a "trace back" to locate an error in a Python program. Use the input function to get data from the user.Convert a string to a number by using the int or float function.Convert a number to a string by using the str function.Explain what happens when a variable is assigned a new value.Explain what happens when a variable is used on both sides of an assignment statement.Insert comments into a Python programProgrammingThis class about computer programming. What is computer programming?Computer Programming: the process of writing instructions for a computer to get the computer to solve a problem. This class is for students who:Are thinking about a major or minor in computer science (this is the first course in the sequence).Are interested in learning more about how computers do what they doWant to improve their logical thinking and problem-solving skillsIf you are good at thinking logically, you will do well in this class.If you are not good at thinking logically, you will probably be much better at it by the end of this class.The person who writes the instructions (you) is a programmer.PythonPython is the name of the programming language we will use in this class. A Python program solves a problem. We will begin with very simple problems and work our way up to more complicated ones.ProgrammingWhat does it take to be a programmer? A programmer must, above all, be able to think logically. He must be able to look at a problem, and determine all of the steps that are required to solve the problem. Because these steps are very small, there will be a lot of them. And because they are very small and there are a lot of them, it is easy to forget one or put it in the wrong place. Because of this, your programs will never work the first time. And because programs never work the first time, patience is another useful attribute of a programmer. What is not needed is a lot of math. Most of the problems we will solve require nothing more complicated than high school algebra.What kinds of problems will we solve this term?Every problem that we will solve will be some type of problem that involves getting (reading) data from the user (usually through the keyboard) and then doing some computation with that input and displaying the results for the user to read. Your job will be to: Identify the data that you need to keep track of for your program.Read the input from the pute the solution to the problemDisplay the results.The ProcessThe process should go something like this:1. PlanningPlan the data that you want to keep track of.Create an algorithm (instructions—in English—for responding to the data).2. ProgrammingDefine the user interface (everything that the user sees on the screen).Translate the algorithm into a program (instructions in Python).Test. Have the computer follow the instructions. Check the results. If they are incorrect, you will have to go back and make changes to your program instructions.In real life, there is a maintenance phase that involves using the program over a period of time and making changes to it as user requirements change. We will not be doing maintenance in this class. ToolsYou will need the following tools to write the programs in this book:A computer. We will be using Windows computers in the lab, but Python is available for all platforms.A Python interpreter. We will use Anaconda, individual edition. A free download.PythonPython is a programming language. A programming language is used to tell the computer how to do something. Learning Python involves learning what types of instructions the computer can "understand", but mostly about how to put them together to get useful work done. All of the instructions and all of the data will be represented using the Python programming language. Computers don't actually "understand" Python instructions. Another program called an interpreter or compiler converts your Python into instructions that the computer can "understand". Your program must be written according to the syntax rules of Python. If not, the compiler will not be able to translate your program, and it will generate an error message telling you that there is a problem. Every Python program must be compiled before it can be executed (run) by a computer.Interactive Python: Constants and TypesComputers manipulate data. Python has 4 basic types of data. Enter some the following into the Python interpreter.type(5)type(5.0)type("5.0")type(True)type(true)type(False)type(false)There are four "primitive" data types in Python: integers (int), real/floating-point numbers (float), text (string), and logical/Boolean (bool).Integers (int)The following are integers:0112345+12-15Note that we do NOT put commas in numbers in Python (or most other programming languages). However, it is legal to use underscores instead of commas! 1,000 is not a legal int in Python, but 1_000 is. Also, Python doesn't care where you put the underscores. This is also legal: 1_0_0. The abbreviation int is used for the integer data type.Try the following in your Python interpreter:type(12345)type(12_345)type(1_2_3)type(+12)type(-15)Floating point numbers (float)The following are floating point numbers:1.5-1.51_234.567_890The following are also floating point numbers, even though their fractional part is 0:5.0-1000.0Notice that there are no commas. The word float is used for the floating-point data type.Try the following in your Python interpreter:type(1.5)type(-1.5)type(1_2.3_4)type(5.0)type(-10.0)StringsThe "string" data type refers to any string of characters enclosed in quotation marks. There are four different ways to create a string in Python:Apostrophes: 'Hello!'Quotation marks: "Hello!"Triple apostrophes: '''Hello!'''Triple quotation marks: """Hello!"""Try the following in your Python interpreter:print('Hello!')print("Hello!")print('''Hello!''')print("""Hello!""")type('Hello!')Logical/Boolean ValuesLogical values are used to make decisions in Python. Decisions are made depending on whether something is true or false, so True and False are logical values.Try the following in your Python interpreter:type(True)type(False)type(true)# Case sensitive!type(false)# Case sensitive!type("true")type('false')Relational operators and Boolean resultsEnter the following at the Python command prompt:1 < 22 < 11 > 22 > 11 <= 11 >= 112 = 12#Error! This is the assignment operator.12 == 12#Equals. This is the comparison operator.13 == 1213 != 12#Not EqualsNow enter these. "and" means "both":1 < 1 and 2 < 3#True, TrueBoth are True so result is True1 < 2 and 3 < 2#True, FalseOnly one is True, so result is False3 < 2 and 0 < 1#False, TrueOnly one is True, so result is False3 < 2 and 1 < 0#False, FalseNeither is True, so result is False"or" means "either:1 < 2 or 2 < 3#True, TrueBoth are True so result is True1 < 2 or 3 < 2#True, FalseOne is True, so result is True3 < 2 or 1 < 2#False, TrueOne is True, so result is True3 < 2 or 2 < 1#False, FalseNeither is True, so result is Falsenot 10 < 11not (10 < 11)# the parentheses are preferrednot 13 < 12False and FalseFalse and TrueTrue and FalseTrue and True# only way to get True with the "and" opertorFalse or False# only way to get False with the "or" operatorFalse or TrueTrue or FalseTrue or TrueAssignment and variablesThe equal sign that appears in each statement below is called an assignment operator because it means that a value is going to be assigned to the variable on its left. The value that gets assigned is whatever appears on the right side of the equal sign. I've always thought that the symbol "<-" should be used here instead, because it describes what is happening better than "=", but nobody asked for my input. 5=n#error! the variable must be on the left siden=5x=2.5y=Truez="2.5"nxyzRules for variable names:Must begin with a letter or underscore (just use letters though)Must be followed with letters, digits, or underscoresCannot be a reserved wordIs case-sensitiveConventions for variable names (not rules of the language)Do not begin with an underscoreNo uppercase letters anywhereSeparate words with an underscoreMust be descriptive (this is not a syntax rule, but the others are)this_is_my_very_important_number = 1002this_is_my_very_important_number = 100#error! Can't begin with a digit!ThisIsMyVeryImportantNumber = 100#legal, but don't do_this_is_my_very_important_number = 100#legal, but don't dothis_is_my_very_important_number = 100print(n)print(x)Print(y) #error! Capital "P"print(y)print(z)type(n)type(x)type(y)type(z)print(n+x)type(n+x)Hello#error! Undefined! A value hasn't been assigned to it yet."Hello"'Hello'"2.5"type(Hello)#error! Still undefined!type("Hello")type('Hello')type("2.5")str1="Don't do that"str1print(str1)str2='He said "Hello!"'str2print(str2)What if you want both an apostrophe and quotation marks in a string? Enclose the string inside of triple quotation marks or triple apostrophes."""He said "Don't do that!""""Can't have 4 quotation marks together! Must leave a space:"""He said "Don't do that!" """Or use apostrophes:'''He said "Don't do that!"'''msg = """Hello,howareyou?"""msg# includes \n (a code for the "new line" character)print(msg)# does NOT include \nAssignment and Variables: Numberslength = 10width = 5Order makes a difference. The variable name must be on the left side. The value must be on the right side. The following are illegal:10 = length#error!5 = width#error!Variable re-assignment:Statements are run sequentially. The computer does not “look ahead.” In the code below, the computer will print out 5 on line 2, and then line 4 will print out a 6. This is because on line 2, the code to add one to x has not been run yet.x = 5print(x) # Prints 5x = x + 1print(x) # Prints 6The next statement is valid and will run, but it is pointless. The computer will add one to x, but the result is never stored or printed.x + 1The code below will print 5 rather than 6 because the programmer forgot to store the result of?x + 1?back into the variable?x.x = 5x + 1print(x)The statement below is not valid because on the left of the equals sign is more than just a variable:x + 1 = xPython has other types of assignment operators. They allow a programmer to modify a variable easily. For example:x += 1The above statement is equivalent to writing the code below:x = x + 1There are also assignment operators for addition, subtraction, multiplication and division:x -= 1#Same as x = x – 1x *= 2#Same as x = x * 2X /= 2#Same as x = x / 2More assignment statements:quotation = "Bye!"# quotation is a string (str)quotationpayRate = 10.00# payrate is a floathours = 40# hours is an integer (int)pay = hours * payrate# pay is a floatpaypayRate = 20pay# it does NOT change to 800!pay = hours * payRate# it must be recalculatedpayType conversions = "10"# "s" for str, "i" for int, "f" for floattype(s)i = 10type(i)f = 10.5type(f)y = int(s)# convert str to intytype(y)y = float(s)# convert str to floatytype(y)y = str(i)# convert int to strytype(y)y = float(i)# convert int to floatytype(y)y = str(f)# convert float to strytype(y)y = int(f)# convert float to int (drops fractional part)ytype(y)ArithmeticThe usual arithmetic operators are: +Addition-Subtraction*Multiplication/DivisionBut Python has some not-so-usual arithmetic operators://Integer division—result is always an integer (but the type can be float!)**Exponentiation%"Mod" (remainder) operatorThe precedence rules are the same that you learned in math class:()*** and / and // and % (the last two involve division and so are at the same level)+ and –All operators at the same level (except **) are evaluated from left to right. So 20/2*2 = 10*2 = 20. It is NOT 5/(2*2) = 5.Exception: The ** operator is evaluated from right to left!2**3**2# 2 to the 9th power(2**3)**2# 9 to the 2nd powerTry:Type these into the interpreter:2+3*4# * has higher precedence(2+3)*4# () have highest precedence(2+3)4# Error! Juxtaposition doesn't work for multiplication(2+3)*4**2)#** has higher precedence2+3-4# + and – are the same so go left to right6*10/2# * and / are the same so go left to rightWhat about these?"5"# string!"5.0"# string!"5.0"/2.0type("5")type("5.0")These (above) look like an int and a float, but they are strings!What about these?x = 42000# legal representation of an inty = 42,000# legal, but gives a tuple, not an intz = 42_000# legal representation of an intAnd these?xy# prints two numbers (called a "tuple")zArithmetic:x = 5*2type(x))x = 5 * 2.0type(x)x = 8/4#floating point divisionxtype(x)9/4# one slash is always floating point division10/411/412/413/48//4#integer division9//410//411//412//413//49//4.5# result is a float, but fractional part is always 0!9//4.49//4.68%4#modulo (remainder) arithmetic. Divide by 4 and keep the remainder.9%410%411%412%413%42**1#exponents2**22**32**43**13**23**33**4e = 10/2type(e)ee = 10//2.1type(e)# type is float, but fractional part is 0ee = 10.5//2# type is float, but fractional part is 0type(e)e2**102**1002**10002**10000The mod operator:10%2# remainder is 010%3# remainder is 110%4# remainder is 210%5# remainder is 010%6# remainder is 410%7# remainder is 310%8# remainder is 210%9# remainder is 110%10# remainder is 010%11# remainder is 1010%11.0# remainder is 10.0Note that the "%"operator has NOTHING TO DO WITH PERCENTAGES!Application of both // and %:minutes = 645# This is 10 hours and 45 minuteshours = minutes / 60# Floating point division = 10.75print(hours)I want to break it up into 10 hours and 45 minutes, though:minutes = 645hours = minutes // 60#integer division = 10minutes = minutes % 60#remainder division. Same variable on both sides!print (hours, minutes)Note that the output here is:10 45What we want is:10:45The print functionTry the following:print("Hours", hours)print("Minutes", minutes)Note that there is no problem using commas between items that are to be printed.Now consider putting a plus sign between numbers or strings:print(hours + minutes) #legal, but makes no sense mathematically (6+45=51)print("hours" + "minutes")#adding words?Note that the plus sign is being used in two different ways here: (1) to add two numbers, and (2) to "concatenate" two strings. The plus sign actually works in two different ways (we say it is "overloaded"). If it is between two numbers, it adds the numbers. If it is between two strings, it concatenates the strings.But what if we put a plus sign between text and a number, like this:print("Hours:" + hours)We get an error message!TypeError: can only concatenate str (not "int") to strIt would be nice if Python told you what must be a string, but it doesn't. This message means that we must convert the hours variable to a string before we can print it out.Another similar error (but the number is first in the print statement):print(hours + ":" + minutes)Error message:TypeError: unsupported operand type(s) for +: 'int' and 'str'f StringsProbably the simplest way to print in Python is by using an "f" string ("formatting" string). A formatting string has the letter "f" before the string, and the variables that are to be printed are listed inside of curly brackets (braces). Like this:Print a stringname = "George"print(f'Hello {name}, welcome to Python!')Print an integercount = 10print(f'The count is {count}.')Print a floating point number (unaligned)# takes the minimum number of columns so $ is right next to the number# The "f" after the 2 means "floating point"cost = 10.95print(f'The cost is ${cost:0.2f}.')# output:The cost is $10.95.Print a floating point number (aligned)# right-aligned in an 8-column field with 2 decimal places.print(f'The cost is ${cost:8.2f}.')# output 12345678:The cost is $ 10.95.InputTo get input from the user, use the input function.name = input("Please enter your name: ")age = input("How old will you be this year?")birthYear = 2021 - ageTypeError: unsupported operand type(s) for -: 'int' and 'str'Line 3 causes an error! You can't do arithmetic on a string—only on numbers (ints or floats).Both of the first two instructions use a built-in function of Python called input. The input function is used to get a small quantity of text from the user. The text between the quotation marks (a string) is what will appear on the screen, and is necessary so the user will know what he is supposed to enter. Note that everything entered from the keyboard is a string, even if it looks like a number.Make the following change:name = input("Please enter your name: ")age = input("How old will you be this year?")age = int(age)birthYear = 2021 - ageprint ("You were born in ", birthYear)ExampleYou can combine the input function and the int or float function to convert a string to an int or a float:hoursWorked = int(input("How many hours did you work?"))# only input an int here!payRate = float(input("What is your hourly rate of pay?"))pay = hoursWorked * payRateprint(f"Pay is ${pay:0.2f}.")NOTE that Python knows nothing about "hours" or "pay rates" or "pay". Another exampleseconds = 3600+120+5 #1 hour, 2 minutes, 5 secondshours = seconds // 3600# 1seconds = seconds % 3600# 125minutes = seconds // 60# 2seconds = seconds % 60# 5print(f"Time: {hours}:{minutes}:{seconds}.")This program works, but only for the value 3600 + 120 + 5 (3725). Real programs don't have the data built-in. They allow the user to input different data each time the program runs.Let's make this program more general by allowing input from the user. Replace the first line with this:seconds = input("How many seconds?")seconds = int(seconds)We could also have combined the two above statements:seconds = int(input("How many seconds?"))Functions and argumentsIn the above examples, input and int are called functions. A function does some computation and returns an answer. Usually some data has to be passed to a function so that it can do its job. These are called arguments. When we "call" the input function, it is expecting a string to be passed to it that it will display on the screen. The argument in this case (above) is "How many seconds?”When we "call" the int function, it is expecting a string or a float to be passed to it (and it expects the string to "look" like a number) that it will convert to an integer. The argument in this case is the string that was entered by the user. It will vary from one program execution to the next, depending on what the user chooses to enter.When functions are nested as in the second example, the innermost function (input) is evaluated first. The value that it returns (a string typed by the user) is used as the argument to the second function (int).ReassignmentIf you assign a new value to a variable, the old one goes away (forever).x = 10print(x)x = 20print(x)What is the output of the following?x = 12x = x - 3x = x + 5x = x + 1print(x)A very common instruction is one that looks like this:x = x + 1But the shortcut for that is:x += 1This is used to count things.DebuggingTypes of errors: Syntax errors Type errorsName errors (forgetting to assign a value to a variable before using it)Value errors (e.g., trying to convert "xxx" to an int)Creating and Saving a ProgramDo homework #1A in class and put it in the drop box. Everybody gets an A. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download