- 变量与数据类型
1.1 Welcome
Python is an easy to learn programming language. You can use it to create web apps, games, even a search engine!
print "Welcome to Python!"
1.2 Variable
my_variable=10
1.3Booleans
A second data type is called a Boolean, a booleanis like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only be True
or False
.
my_int=7
my_float=1.23
my_bool=True
1.4 Reassigned
You can change the value of a variable by "reassigning" it
# my_int is set to 7 below. What do you think
# will happen if we reset it to 3 and print the result?
my_int = 7
# Change the value of my_int to 3 on line 8!
my_int = 3
# Here's some code that will print my_int to the console:
# The print keyword will be covered in detail soon!
print my_int
1.5 Whitespace
In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.
You should indent your code with four spaces.
def spam():
eggs = 12
return eggs
print spam()
1.6 Single Line Comments
You probably saw us use the #
sign a few times in earlier exercises. The #
sign is for comments.
A comment is a line of text that Python won't try to run as code. It's just for humans to read.
1.7 Multi-Line Comments
for multi-line comments, you can include the whole block in a set of triple quotation marks:"""hail hydra"""
1.8 Math
Great! Now let's do some math. You can add, subtract, multiply, divide numbers like this
addition = 72 + 23
subtraction = 108 - 204
multiplication = 108 * 0.5
division = 108 / 9
1.9 Exponentiation
eight = 2 ** 3
1.10 Modulo
Modulo returns the remainder from a division. So, if you type 3 % 2
, it will return 1
, because 2 goes into 3 evenly once, with 1 left over.
#Set spam equal to 1 using modulo on line 3!
spam =7%3
print spam
The Meal
You've finished eating at a restaurant, and received this bill:
- Cost of meal: $44.50
- Restaurant tax: 6.75%
- Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax).
The code on line 10 formats and prints to the console the value of total with exactly two numbers after the decimal. (We'll learn about string formatting, the console, and print in Unit 2!)
# Assign the variable total on line 8!
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total=meal+meal*tip
print("%.2f" % total)