****学 习 地 址 :****
计算机科学圈| 01000011 01010011 01000011
1. Variables
«the variable name» = «the value you want to store»
-
Variables act as "storage locations" for data in a program;
-
Variables are a way of naming information for later usage;
-
变量在程序中充当数据的“存储位置”;
-
变量是对之后会用到信息进行命名的一种方式。
2. Errors
Three Python errors:
a syntax error -- 语法错误,程序运行前发生,代码不合乎Python语言规则, Python不理解程序。
在英语中,a syntax error 就像是说,
Please cat dog monkey.
一些语法错误示例:
myfunction(x, y):
return x + y
•
else:
print "Hello!"
•
if mark >= 50
print("You passed!")
•
if arriving:
print("Hi!")
esle:
print("Bye!")
•
if flag:
print("Flag is set!")
a run-time error -- 运行时错误,Python解释器运行程序时发生,语法正确,在执行特定行时才会显示出来。
在英语中,a run-time error 就像是说,
Please eat the piano.
一****些运行时错误示例:
division by zero
print(1/0)
•
•
## performing an operation on incompatible types
print("you cannot add text and numbers" + 12)
•
•
## using an identifier which has not been defined
callMe = "Maybe"
print(callme)
•
•
## accessing a list element, dictionary value or object attribute which doesn’t exist
## trying to access a file which doesn’t exis
logic errors -- 程序可以运行,但是返回的结果可能不对,没有语法或运行时错误,是由程序逻辑中的错误引起的。
An example of logic errors would be,
Please close the back door so that the bugs don't come in.
「如果前门也是开着的,即使后门关闭,但实际上并没有实现阻止bugs的目标。」
一些逻辑错误示例:
## getting operator precedence wrong
## This does not calculate the average correctly
x = 3
y = 4
average = x + y / 2
print(average)
•
•
## using the wrong variable name
nums = 0
for num in range(10):
num += num
## indenting a block to the wrong level
sum_squares = 0
for i in range(10):
i_sq = i**2
sum_squares += i_sq
•
•
## the product will always be zero!
product = 0
for i in range(10):
product *= i
•
## using integer division instead of floating-point division
## making a mistake in a boolean expression
## off-by-one, and other numerical errors
3. Exercise & Answer
Coding Exercise: Heads, Shoulders, Knees and Toes
Write a code fragment (a short part of a Python program) to count heads, shoulders, knees, and toes at a party.
my Answer
heads=1*people
shoulders=2*people
knees=2*people
toes=10*people
Scramble Exercise: Speed Calculator
drag-and-drop the lines to rearrange them into a correct program.
my Answer
Coding Exercise: Exchange Program
Write a program to swap the values of two variables.
my Answer
m=y
n=x
x=m
y=n
Coding Exercise: Shopping
You are going shopping for meat and milk, but there is tax. You buy 4.00 of meat, and the tax rate is 3%. Print out the total cost of your groceries (you don't need to print the dollar sign).
my Answer
meatPrice = 4.00
meatTax = 0.03 * meatPrice
milkPrice = 2.00
milkTax = 0.03 * milkPrice
print(meatTax + meatPrice + milkTax + milkPrice)
参考:
[1]https://cscircles.cemc.uwaterloo.ca/
[2]https://python-textbok.readthedocs.io/en/1.0/Errors_and_Exceptions.html#answer-to-exercise-1
网友评论