Post Labs
Reading Questions
Quiz
Types
- We have used variables to store information in the computer’s memory
- Everything thing in a computer’s memory is represented with bits, off or on
- Different types of values are represented in memory differently
- Note that the values
"2"
,2.0
, and2
are all stored in memory differently even though they all represent the same thing - Strings can be text,
"two"
or"2"
, the literal value has quotes - Floats can be real numbers,
1.5
or2.0
, the literal value has a decimal point - Ints can be integers,
1
or-2
, the literal value has no decimal point - Can convert between types with the functions
str
,float
, andint
- When converting a string to a float or int float will produce an error if the string does not represent a literal
- When converting to a float to an int, the decimal values will be truncated i.e. rounded to zero
- When performing aritmetic operations, if both operands are ints the result will be an int, otherwise the result will be a float
- Unless the operator is /, in which case the result will always be a float
- Aritmetic operators with strings and numbers will produce errors
- Except for adding two string, concatenate, and multiplying a string and an integer, repeating
Input
- Can rewrite our programs so that instead of changing the value of a variable at the top of the program, it will prompt the user for a value
- The
input
function stops the program until the user hits the enter key - The function evaluates to whatever the user typed, as a string
So the age in seconds program
age_years = 31 seconds_in_year = 31536000 age_seconds = age_years * seconds_in_year print("my age in seconds is", age_seconds)
Becomes
age_years = input('enter your age in years: ') seconds_in_year = 31536000 age_seconds = age_years * seconds_in_year print("my age in seconds is", age_seconds)
- The string inside the parentheses of the
input
function are what are printed while waiting for the user to type something, it is the prompt - Note, the prompt doesn’t include a space, so it usually looks better if you add one
- But the program doesn’t work, recall the function evaluates to a string and multiplying a string by a number repeats the string
So to fix, need to convert the string to an integer
age_years = int(input('enter your age in years: ')) seconds_in_year = 31536000 age_seconds = age_years * seconds_in_year print("my age in seconds is", age_seconds)