say hello:
statement in python 2
print " "
statement in python 3
print (" ")
define a string
While double-quotes (“) and single-quotes (‘) are both acceptable ways to define a string, a string needs to be opened and closed by the same type of quote mark
We can combine multiple strings using +, like so: print "This is " + "a good string"
BUG 1
SyntaxError: EOL while scanning a string literal
This means that a string wasn’t closed, or wasn’t closed with the same quote-character that started it.
Python treats words not in quotes as commands, like the print statement. If it fails to recognize these words as defined (in Python or by your program elsewhere) Python will complain the code has a NameError.
Variables
Python uses variables to define things that are subject to change.
statement
greeting_message = "Welcome to Codecademy!"
current_excercise = 5
arithmetic
The modulo operator is indicated by % and returns the remainder after division is performed.返回除法后的余数
Updating variables
Updating a variable by adding or subtracting a number to its original value is such a common task that it has its own shorthand to make it faster and easier to read.
money_in_wallet = 40
sandwich_price = 7.50
sales_tax = .08 * sandwich_price
sandwich_price += sales_tax
money_in_wallet -= sandwich_price
comments
A line of text preceded by a # is called a comment.
number
integer/ float(You can define floats with numbers after the decimal point or by just including a decimal point at the end:)(You can also define a float using scientific notation, with e indicating the power of 10:
statement
# this evaluates to 150:
float4 = 1.5e2)
division
python 2 when we divide two integers, we get an integer as a result. if the numbers do not divide evenly, the result of the division is truncated into an integer.To yield a float as the result instead, programmers often change either the numerator or the denominator (or both) to be a float
statement
quotient1 = 7./2
# the value of quotient1 is 3.5
quotient2 = 7/2.
# the value of quotient2 is 3.5
quotient3 = 7./2.
# the value of quotient3 is 3.5
# An alternative way is to use the float() method:
quotient1 = float(7)/2
# the value of quotient1 is 3.5
multi-line string
If we want a string to span multiple lines, we can also use triple quotes:
statement
address_string = """136 Whowho Rd
Apt 7
Whosville, WZ 44494"""
booleans
A boolean is actually a special case of an integer. A value of True corresponds to an integer value of 1, and will behave the same. A value of False corresponds to an integer value of 0.
statement
a = True
b = False
BUG 2 ValueError
if we wanted to print out an integer as part of a string, we would want to convert that integer to a string first. We can do that using str()
int() #转换为整数型变量
float()#转换为float型变量