Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 2- Types, Variables, Memory, Simple Input and Output I. Basic Programming Input Process Output II. Strings A. Using String # Demonstrates the use of quotes in strings print("Program 'Game Over' 2.0") print("Same", "message", "as before") print("Just", "a bit", "bigger") print("Here", end=" ") print("it is...") print( """ _____ ___ ___ ___ _____ / ___| / | / |/ | | ___| || / /| | / /| /| | | |__ | | _ / ___ | / / |__/ | | | __| | |_| | / / | | / / | | | |___ \_____/ /_/ |_| /_/ |_| |_____| _____ _ _ _____ _____ / _ \ | | / / | ___| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | |/ / | |___ | | \ \ \_____/ |___/ |_____| |_| \_\ ) """ a. When you put quotes around something, Python takes it literally. It prints exactly what is in the quotes. You can use double quotes or single quotes for a string. i. teacher = “Mrs. Heineman” or teacher = ‘Mrs. Heineman’ b. You can print multiple values with a comma in-between strings for example: print ( “Same”, “message”, “ as before”) A space is automatically placed between the words. c. Concatenate- adding together strings i. print “cat” + “dog would show catdog ii. open Silly string program d. Long Strings- triple quoted string i. Use when you have several lines of text that you want displayed together ii. longString=””” Sing a song of sixpence, a pocket full of rye, Four and twenty black birds baked in a pie. When the pie was open, the birds began to sing. Wasn’t that a dainty dish to set before the king?”” B. Escape Sequences with Strings a. allows you to put special characters into your strings. b. made up of two characters: a backslash followed by another character. # Fancy Credits # Demonstrates escape sequences print("\t\t\tFancy Credits") print("\t\t\t \\ \\ \\ \\ \\ \\ \\") print("\t\t\t\tby") print("\t\t\tMichael Dawson") print("\t\t\t \\ \\ \\ \\ \\ \\ \\") print("\nSpecial thanks goes out to:") print("My hair stylist, Henry \'The Great,\' who never says \"can\'t.\"") # sound the system bell print("\a") input("\n\nPress the enter key to exit.") Sequence \\ \’ \” \a \n \t Description Backslash, prints one backslash Single quote, prints one single quote Double quote, prints one double quote Bell, sounds the system bell Newline, moves cursor to beginning of next line Horizontal tab, moves cursor forward one tab III. Math in Python Mathematical Operations in Python Operator Description + Addition Subtraction * Multiplication / Division ( true) // Integer Division % Modulus ** Exponentiation Evaluate the expression. 1. 3 + 5 Example 7+3 7-3 7*3 7/3 7//3 7%3 2**3 Evaluates to 10 4 21 2.33333… 2 1 8 5. 10//3 2. -2*8 6. 10 % 3 3. 3**2 7. 20/3 4. 10/3 8. 20.0/3.0 Order of Operations in Python- same as mathematics - unary ( )Parenthesis **exponents *,/,//,% multiplication, division, integer division, modulus ( left to right evaluation) +,- addition and subtraction ( left to right evaluation) Evaluate using order of operations. 1. 8 + 3*(6 + 1) 2. 3**3 + 4 * -2 – 3 3. 5 + 8 /4 * 3 4. (2 + 3) ** 2 -10%2 5. 100%34 + 30/5 6. 6 + 2 – 5 * 2 +20%6 Data Types 1. Integers …-3, -2, -1, 0, 1, 2, 3, …. 2. Decimal- floating point numbers 1.24, -0.3789 etc 3. Strings- characters contained in “ ” or ‘ ’ Short cut for Increments and Decrements- Augmented Assignment Operators If you wrote the coding score= score + 1 This line would add one to the value of score Python short cut score+=1 means the same thing as the line above. score-=1 would subtract one from the value of score Operator += -= *= /= %= Example x+=5 x-=5 x*=5 x/=5 x%=5 Is Equivalent to x=x+5 x=x-5 x=x*5 x=x/5 x=x%5 See Word Problem Program IV. Using Variables a. Variable exists when you assign a name to a value. A variable is stored in memory. Example of an assignment statement teacher= “Mrs. Heineman” print( teacher) The result would be Mrs. Heineman on the screen. b. The equal sign is used to give the variable a value. c. Variables can be created for characters as well as numbers. d. Rules for Variable Names i. Can have letters, numbers and underscore ii. Python is case sensitive iii. Must start with letter or underscore iv. No spaces v. Use descriptive names vi. Name convention - intercap method- start with lowercase i. firstName ii. middleInitial vii. try to keep within 15 characters e. Assigning variables i. The variable name goes on the left side of the equal sign. ii. firstName=”John” V. Getting User Input #Personal Greeter name=input(“Hi. What is your name?”) print(name) print(“Hi”, name) input(“\n\nPress enter to exit.”) Input is a function that allows the user to enter in information and store it in a variable. Input function always returns a string. VI. String Methods. Look at the coding below. Predict what will happen next to each line. Then type and run program # Demonstrates string methods # quote from IBM Chairman, Thomas Watson, in 1943 quote = "I think there is a world market for maybe five computers." print("Original quote:") print(quote) print("\nIn uppercase:") print(quote.upper()) print("\nIn lowercase:") print(quote.lower()) print("\nAs a title:") print(quote.title()) print("\nWith a minor replacement:") print(quote.replace("five", "millions of")) print("\nOriginal quote is still:") print(quote) input("\n\nPress the enter key to exit.") String Methods Method upper() lower() swapcase() capitalize() title() strip() replace(old, new[,max]) Description Returns uppercase version of string Returns lowercase version of string Returns a new string where the case of each letter is switched. Uppercase becomes lowercase and lowercase becomes uppercase. Returns a new string where the first letter is capitalized and the rest are lowercase. Returns a new string where the first letter of each word is capitalized and all others are lowercase. Returns a string where all the whitespace (tabs, spaces, and newlines) at the beginning and end is removed. Returns a string where occurrences of the string old are replaces with the string new. The optional max limits the numbers of the replacement. Examples : name.lower()- would return the name in lower case name.upper()- would return the name in upper case. VI. Converting Values Run Trust Fund Buddy Bad Logical Errors- program produces unintended results but does not crash. A. Converting Values Run Trust Fund Buddy Good program Function Description float(x) Returns a floating point value by converting x. int(x) Returns an integer value by converting x str(x) Returns a string value by converting x. Example float(“10.0”) Returns 10.0 int(“10”) 10 str(10) ‘10’ Review Questions Name___________________________ 1. How do you tell Python that a variable is a string instead of a number? 2. Once you have created a variable, can you change the value that is assigned to it? 3. With the variables teacher and Teacher, are they the same? 4. Is “Hello” the same as ‘Hello’ in Python? 5. Which of the following is not a correct variable name? Why? a. Teacher2 b. 2Teacher c. teacher_25 d. TeaCher 6. Is “10” a number or a string? 7. Is ‘4’ the same as 4 to Python? 8. State the output. name=”John Doe” print (name.lower()) 9. Fix the statement so it converts to stated data type. a. age=input(“Enter age”) #convert age to an integer b. hourlyWage=input(“Enter wage”) 10. Write a valid variable name for the following – state its data type. a. Your grade point average. b. Book title c. Number of students in school d. Your phone number Chapter 2 Programs. For each program make comments at the top with your name and the program’s name. Use proper variable names Make output “look nice”. It should never be just a number. For example: print(“The total amount is $”,total) Save all programs with proper name in your folder. 1. Make a program that assigns your first name to the variable firstName; last name assigned to variable lastName and then display your first and last name with a space inbetween. 2. Tipper Program- Write a program where the user enters the total of the bill from a restaurant order. The program should then display two amounts; a 15% tip and a 20% tip. 3. Write a car salesman program where the user enters the base price of a car. The program should add on extra fees such as tax, dealer prep and destination charge. Make the tax be 7% of the cost of the car, dealer prep is $250 and destination charge is $130.50. Display the actual price of the car once everything is added in. 4. Write a program that has the user input an amount in change less than one dollar. The program should output the number of quarters, dimes, nickels and pennies used for that amount. Assume it will give the most possible of the largest coins. For example: 92 is the inputted value. Hint: you need to use modulus. Output: The number of quarters: 3 The number of dimes: 1 The number of nickels: 1 The number of pennies: 2