Chapter 2- types, Variables, Memory, Simple Input and Output I. Basic Programming



Download 45 Kb.
Date26.04.2018
Size45 Kb.
Chapter 2- Types, Variables, Memory, Simple Input and Output
I. Basic Programming

Input Process Output

II. Strings


  1. 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(

"""


_____ ___ ___ ___ _____

/ ___| / | / |/ | | ___|

| | / /| | / /| /| | | |__

| | _ / ___ | / / |__/ | | | __|

| |_| | / / | | / / | | | |___

\_____/ /_/ |_| /_/ |_| |_____|

_____ _ _ _____ _____

/ _ \ | | / / | ___| | _ \

| | | | | | / / | |__ | |_| |

| | | | | | / / | __| | _ /

| |_| | | |/ / | |___ | | \ \

\_____/ |___/ |_____| |_| \_\


"""

)


  1. 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.

    1. teacher = “Mrs. Heineman” or teacher = ‘Mrs. Heineman’




  1. 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.


  1. Concatenate- adding together strings

i. print “cat” + “dog would show catdog

  1. open Silly string program

  1. Long Strings- triple quoted string

    1. Use when you have several lines of text that you want displayed together

    2. 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.


  1. 3 + 5 5. 10//3




  1. -2*8 6. 10 % 3




  1. 3**2 7. 20/3




  1. 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)




  1. 3**3 + 4 * -2 – 3




  1. 5 + 8 /4 * 3




  1. (2 + 3) ** 2 -10%2




  1. 100%34 + 30/5




  1. 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




  • See Word Problem Program


IV. Using Variables

  1. 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.



  1. The equal sign is used to give the variable a value.

  2. Variables can be created for characters as well as numbers.

  3. Rules for Variable Names

    1. Can have letters, numbers and underscore

    2. Python is case sensitive

    3. Must start with letter or underscore

    4. No spaces

    5. Use descriptive names

    6. Name convention - intercap method- start with lowercase

      1. firstName

      2. middleInitial

    7. try to keep within 15 characters

  4. Assigning variables

    1. The variable name goes on the left side of the equal sign.

    2. 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

  • Run Trust Fund Buddy Bad

Logical Errors- program produces unintended results but does not crash.




  1. 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___________________________


  1. How do you tell Python that a variable is a string instead of a number?



  1. Once you have created a variable, can you change the value that is assigned to it?



  1. With the variables teacher and Teacher, are they the same?



  1. Is “Hello” the same as ‘Hello’ in Python?



  1. Which of the following is not a correct variable name? Why?




    1. Teacher2

    2. 2Teacher

    3. teacher_25

    4. TeaCher

  1. Is “10” a number or a string?



  1. Is ‘4’ the same as 4 to Python?



  1. State the output.

name=”John Doe”

print (name.lower())





  1. Fix the statement so it converts to stated data type.

    1. age=input(“Enter age”) #convert age to an integer

    2. hourlyWage=input(“Enter wage”)




  1. Write a valid variable name for the following – state its data type.

    1. Your grade point average.

    2. Book title

    3. Number of students in school

    4. 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.



  1. 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.




  1. 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.




  1. 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

Download 45 Kb.

Share with your friends:




The database is protected by copyright ©ininet.org 2020
send message

    Main page