1/36
programming w numbers and strings
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
variables
a named storage location in a computer program
define a variable by telling the compiler:
what name you will use to refer to it
initial value
it’s like the parking space in a garage
the assignment statement
use assignment operator (=) to place a value into a variable
assigning a value to an existing variable replaces the previously stored value
the “=” sign is NOT used for comparison
3 primitive data types
whole number (7) integer
number with a fraction part (7.0) float
sequence “Bob” string
string literal are specified by enclosing a sequence of character within a matching pair of either single or double quotes
the data type in Python is associated with the value, not the variable:
cansPerPack = 6 # int
canVolume = 12.0 # float
Python infers the data type of a variable by the value it holds
a variable can be assigned different values at different places in a program
naming variables
must start with a letter or the underscore (_) character
cannot use other symbols and spaces are not permitted
separate words with ‘camelCase’, ‘PascalCase’, or ‘snake_case’ notation
don’t use ‘reserved’ Python keywords
snake_case
pros: concise when it consists of a few words
cons: redundant when it gets longer
push_something_to_first_queue, pop_what, get_whatever…
PascalCase
pros: seams neat
GetItem, SetItem, Convert, …
cons: barely used
camelCase
pros: widely used int he programmer community
cons: looks ugly when a few methods are n-worded
push, reserve, beginBuilding, …
constants
a variable whose value should not be changed after it’s assigned an initial value
python will let you change the value of a constant
totalvolume = bottles * 2.0 ← aviod magic numbers, a number in the code that seems arbitrary and has no context/meaning
totalvolume = bottles * BOTTLE_VOLUME
python comments
use comments at the beginning of each program and to clarify details of the code
basic arithmetic operations
+ → addition
- → subtraction
* → multiplication
/ → division
% → modulus operator to get remainder in integer division ( ex. 5%2, result: 1)
** → exponent
// → integer division/floor division (ex. 5//2 III -5//2, results: 2 III -3)
line continuation
the backslash (\)
calling functions
a function is a collection of programming instructions that carry out a particular task
print() function can display information, but there are other function that requires arguments
calling function that return a value
most function return a value, when a function completes its task, it passes a value back to the point where the function was called
type conversion functions
use int() and float() to convert between integer and floating-point values
you lose the fractional part of the floating-point value (no rounding occurs) when you use int()
functions in python libraries: library
a collection of code, written and compiled by someone else, that’s ready for you to ise in your program
standard library
a library that’s considered part of the language and must be included with any Python system
provide standardized solutions for many problems that occur in everyday programming
modules
python’s standard library is organized into__
functions defined in a module other than the built-in module must be explicity imported into your program before they can be used
built-in functions
a small set of functions that are defined as a part of the python language that can be used directly
can be used w/o importing any modules
strings
sequence of characters
in python, string literals are specified by enclosing a sequence of characters witghin a matching pair of either single or double quotes
string length
number of characters in a string is
a string of length 0, empty string. contains no characters and is written as ““ or ‘‘
string concatenation “+”
concatenation: you can ‘add’ one String onto the end of another
using “+” to concatenate string is an example of operator overloading. the “+” operator performs different functions of variables of different types
string repetition “*”
produce a string that is the result of repeating a string multiple time, also overloaded
ex. In [20]: dashes = “-” * 50
unicode charaters
encode every character into an integer number
defines over 100,000 characters
designed to be able to encode text essentially all written languages
conversion between unicode and character
the ord() function returns the number used to represent a given character
the chr() function returns the character associated with a given code
round function()
round(number, ndigits=None)
round a number to a given precision in decimal digits
return value is an integer if ndigits is omitted or None. otherwise the return value has the same type as the number
methods (in object-oriented programming)
a collection of programming instructions ot carry out a specific task
like a function but only applied to an object of the type for which is was defined
are specific to a type of object
apple the upper () method to any string
ex.
name = “John Smith
uppercaseName = name.upper() #Sets uppercaseName to “JOHN SMITH”
input
read a user input from the console, input() function
name = input (“Please enter your name: “)
numerical input
the user’s input will always be returned by input() as a string
this is wrong:
age = input (“Please enter age: “)
ageNextYear = age +1
to use the input as number, convert it using int() or float()
age = int (input(“Please enter age: “))
the above is equivalent to doing it two steps (getting the input and then converting it to a number):
ageString = input (“Please enter age:) #String input
age = int(ageString) # Converted to int
print output
using String format() method with positional arguments
String format() with keyword arguments
ways of defining placeholders
can be identified using named indexes { price }, numbered indexes { 0 }, or even empty placeholders { }
formatted output
outputting floating point values can look strange
to control the output appearance of numeric variables, use formatted output such as:
ln [18]: print (“Price per liter: {:.2f}”.format (price))
Price per liter: 1.22
format specifier
‘:10.2f’
<type> Subcomponent in a format specifier
using python f-string
the string has the f prefix and uses {} to evaluate variables
find(substring)
returns the index of the first occurrence of a substring, or -1 if it is not found.
count(substring)
counts how many times a substring appears in the string
startswith(prefix)
returns True if the string begins with the specified text.
endswith(suffix)
returns True if the string ends with the specified text.