pythonForEveryone Ch2
str( ) function
The str function converts an integer or floating-point value to a string. id = 1729 name = "Agent" + str(id) now we are able to concatenate.
Numerical Input
To read an integer or floating- point value, use the input function followed by the int or float function userInput = input("please enter your age: ") age = int(userInput) or age = float(userInput)
String
"A sequence of characters."
Modulus
The % operator computes the remainder of a floor division. For example, 27 % 4 returns a value of 3.
Floor Division
The // operator computes floor division in which the remainder is discarded
Concatenation
Use the + operator to concatenate strings; that is, to put them together to yield a longer string. firstName = "Harry" lastName = "Morgan" name = firstName + lastName
Naming Variables
1. Names must start with a letter or the underscore, and the remaining characters must be letters, numbers, or underscores. Also start with a lower case. 2. You cannot use symbols or spaces. Use camelCase to denote word boundaries. 3. Names are case sensitive. 4. You cannot use reserved words such as if and class. 5. Use descriptive names such as cansPerPack. 6. A name with ALL_UPPER_CASE letters denotes a constant.
Input function
Use the input function to read keyboard input. first = input("Enter your first name: ") the input function displays the string argument in the console window and places the cursor on the same line, immediately following the string. After the user supplies the input and presses the enter key, the sequence of characters is STORED AS A STRING in the variable so it can be used later.
Formatted Outputs
Use the string format operator to specify how values should be formatted.
Constant
A constant variable, or simply a constant, is a variable whose value should not be changed after it has been assigned an initial value.
Primitive Data Types
A data type provided by the language itself
Library
A library is a collection of code that has been written and translated by someone else, ready for you to use in your program.
Programming Tip: Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code without explanation. For example, totalVolume = bottles * 2 Why 2??? Use a named constant to make the code self-documenting.
Standard Library
A standard library is a library that is considered a part of the language. Python has a standard library that provides function and data types for your code.
String repetition
A string can be repeated using the * operator. message = "Echo" print( message * 50) will display: EchoEchoEchoEcho...
Variable and Types
A variable in Python can store a value of any type. The data type is associated with the value, not the variable. Once a variable is initialized with a value of a particular type, it should always store values of that same type.
Variable
A variable is a storage location. variableName = value
When is a variable created?
A variable is created the first time it is assigned a value. After a variable is defined, it can be used in other statements.
Common Error: Using Undefined Variables
A variable must be creted and initialized before it can be used for the first time.
Assignment Statement
An assignment statement stores a value in a variable. variableName = 6
Comments
As your programs get more complex, you should add comments, explanations for human readers of your code. Use the # symbol to denote a comment.
What happens when you assign a value to an existing variable?
Assigning a value to an existing variable replaces the previously stored value. For example, variableName = 6 variableName = 10 variableName now has a value of 10.
Type: Floating-point
Floating-point numbers contain a fractional part. Do not use a fraction (14/100), they will produce an error. Instead use a decimal.
Type: Integer
Integers are whole numbers without a fractional part. Do not use commas (3,000), they will produce an error.
Basic Arithmetic Operations
Python supports the same four basic arithmetic operations as a calculator - addition, subtraction, multiplication, and division ( + - * / ). The combination of variables, literals, operators, and parenthesis is called an expression. NOTE: Mixing integers and floating-point values in an arithmetic expression yields a floating-point value. NOTE: The / operator always results in a floating-point number, even when both operands are integers.
Exponential Operator
Python uses the exponential operator ** to denote the power operation. For example, the Python equivalent of the mathematical expression a^2 is a ** 2. Note that there can be no space between the two asterisks. Unlike other arithmetic operators, the power operator is evaluated from right to left. Thus, the Python expression 10 ** 2 ** 3 is equivalent to 10^(2^3) = 10^8 = 100,000,000.
Modules
Python's standard library is organized into modules. Related functions and data types are grouped into the same module. A library function must be imported into your program before it can be used. For example, to use the square root function form Python's math module, first include the statement: from math import sqrt at the top of your program file. Then you can simply call the function as: y = sqrt(x)
Assignment Operator
The assignment operator ( = ) does not denote mathematical equality. Assignment is an instruction to do something - namely, place a value into a variable. For example, variableName = 12
Methods
The behavior of an object is given through its methods. A method, like a function, is a collection of programming instructions that carry out a particular task. But unlike a function, which is a standalone operation, a method can only be applied to an object of the type for which it was designed.
Number Literal
When a value such as 6 or 0.355 occurs in a Python program, it is called a number literal.
Data Type
The data type of a value specifies how the value is stored in the computer and what operations can be performed on the value.
int( ) and float( ) functions
The in ( ) and float ( ) functions convert a string containing a number to the numerical value. id = int("1729") or price = float("17.29")
Calling Functions
There are two common styles for illustrating OPTIONAL arguments. The first shows different functions with and without the optional arguments: round(x) # Returns X rounded to a whole number round(x, n) # Returns X rounded to n decimal places The second style, which is used in Python's documentation, uses square brackets to denote the optional arguments: round(x [, n]) # Returns X rounded to a whole number or to n decimal places Finally, some functions, such as max and min , take an arbitrary number of arguments. For example, cheapest = min(7.25, 10.95, 5.95, 6.05)
Problem Solving: First Do It By Hand
When you are asked to write a program for solving a problem, you may naturally think about the Python syntax for the computations. However, before you start programming, you should carry out the computations by hand. If you can't compute the solution yourself, it's unlikely that you'll be able to write a program that automates the computation.
Strings position (index)
You can access the individual characters of a string based on their position within the string. This position is called the index of a character. String position are counted starting with 0 name = "Andy" A n d y #character 0 1 2 3 #index An individual character is accessed using square brackets [ ] , inside of which position is enclosed. first = name[0] last = name[3] first is now set to "A" and last is set to "y"
Built-In Functions
are defined as part of the language itself and can be used directly in your programs. For example, print(), abs(), min(), max(), float()
String Literal
denotes a particular string (such as "hello"). In Python, string literals are specified by enclosing a sequence of characters within a matching pair of either single or double quotes. print("This is a string", 'this too') By allowing both types of delimeters, Python makes it easy to include an apostrophe or quotation mark within a string.
Other Ways to Import Modules
from math import sqrt, sin, min from math import * this imports the entire contents of the module import math this imports the module, but you need to add the module name and a period before each call if you use this method ( y = math.sqrt(x) )
object
in programming, an object is a software entity that represents a value with certain behavior. The value can be simple, such as a string, or complex, like a graphical window or data file.
Characters
letters, numbers, punctuation, spaces, and so on...
String Methods
s.upper( ) is an uppercase version of string s name = "John" upperCaseName = name.upper() #sets upperCaseName to "JOHN" s.lower( ) is a lowercase version of string s name = "JOHN" lowerCaseName = name.lower() #sets lowerCaseName to "john" s.replace(old, new) A new version of string s in which every occurrence of the substring old is replaced but the string new name = "John Smith" name2 = name.replace(John, Jane) #name2 is set to "Jane Smith"
len (length)
the number of characters in a string is called the length of the string. The len function returns the number of characters in a string. length = len("World!") #length is 6 a string of length 0 is called an empty string.