Chapter 2- Types, Variables, Memory, Simple Input and Output
I. Basic Programming
Input Process Output
II. Strings
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(
"""
_____ ___ ___ ___ _____
/ ___| / | / |/ | | ___|
| | / /| | / /| /| | | |__
| | _ / ___ | / / |__/ | | | __|
| |_| | / / | | / / | | | |___
\_____/ /_/ |_| /_/ |_| |_____|
_____ _ _ _____ _____
/ _ \ | | / / | ___| | _ \
| | | | | | / / | |__ | |_| |
| | | | | | / / | __| | _ /
| |_| | | |/ / | |___ | | \ \
\_____/ |___/ |_____| |_| \_\
"""
)
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.
teacher = “Mrs. Heineman” or teacher = ‘Mrs. Heineman’
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.
Concatenate- adding together strings
i. print “cat” + “dog would show catdog
open Silly string program
Long Strings- triple quoted string
Use when you have several lines of text that you want displayed together
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
|
Description
|
\\
|
Backslash, prints one backslash
|
\’
|
Single quote, prints one single quote
|
\”
|
Double quote, prints one double quote
|
\a
|
Bell, sounds the system bell
|
\n
|
Newline, moves cursor to beginning of next line
|
\t
|
Horizontal tab, moves cursor forward one tab
|
III. Math in Python
Mathematical Operations in Python
Operator
|
Description
|
Example
|
Evaluates to
|
+
|
Addition
|
7+3
|
10
|
-
|
Subtraction
|
7-3
|
4
|
*
|
Multiplication
|
7*3
|
21
|
/
|
Division ( true)
|
7/3
|
2.33333…
|
//
|
Integer Division
|
7//3
|
2
|
%
|
Modulus
|
7%3
|
1
|
**
|
Exponentiation
|
2**3
|
8
|
Evaluate the expression.
3 + 5 5. 10//3
-2*8 6. 10 % 3
3**2 7. 20/3
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.
8 + 3*(6 + 1)
3**3 + 4 * -2 – 3
5 + 8 /4 * 3
(2 + 3) ** 2 -10%2
100%34 + 30/5
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
|
Is Equivalent to
|
+=
|
x+=5
|
x=x+5
|
-=
|
x-=5
|
x=x-5
|
*=
|
x*=5
|
x=x*5
|
/=
|
x/=5
|
x=x/5
|
%=
|
x%=5
|
x=x%5
|
IV. Using Variables
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.
The equal sign is used to give the variable a value.
Variables can be created for characters as well as numbers.
Rules for Variable Names
Can have letters, numbers and underscore
Python is case sensitive
Must start with letter or underscore
No spaces
Use descriptive names
Name convention - intercap method- start with lowercase
firstName
middleInitial
try to keep within 15 characters
Assigning variables
The variable name goes on the left side of the equal sign.
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
|
Description
|
upper()
|
Returns uppercase version of string
|
lower()
|
Returns lowercase version of string
|
swapcase()
|
Returns a new string where the case of each letter is switched. Uppercase becomes lowercase and lowercase becomes uppercase.
|
capitalize()
|
Returns a new string where the first letter is capitalized and the rest are lowercase.
|
title()
|
Returns a new string where the first letter of each word is capitalized and all others are lowercase.
|
strip()
|
Returns a string where all the whitespace (tabs, spaces, and newlines) at the beginning and end is removed.
|
replace(old, new[,max])
|
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
Logical Errors- program produces unintended results but does not crash.
Converting Values
Run Trust Fund Buddy Good program
Function
|
Description
|
Example
|
Returns
|
float(x)
|
Returns a floating point value by converting x.
|
float(“10.0”)
|
10.0
|
int(x)
|
Returns an integer value by converting x
|
int(“10”)
|
10
|
str(x)
|
Returns a string value by converting x.
|
str(10)
|
‘10’
|
Review Questions Name___________________________
How do you tell Python that a variable is a string instead of a number?
Once you have created a variable, can you change the value that is assigned to it?
With the variables teacher and Teacher, are they the same?
Is “Hello” the same as ‘Hello’ in Python?
Which of the following is not a correct variable name? Why?
Teacher2
2Teacher
teacher_25
TeaCher
Is “10” a number or a string?
Is ‘4’ the same as 4 to Python?
State the output.
name=”John Doe”
print (name.lower())
Fix the statement so it converts to stated data type.
age=input(“Enter age”) #convert age to an integer
hourlyWage=input(“Enter wage”)
Write a valid variable name for the following – state its data type.
Your grade point average.
Book title
Number of students in school
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.
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.
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.
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.
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
Share with your friends: |