(一)Addition: Numbers and Strings
Numeric addition
Numeric addition Single line math equations, run in a code cell, will output a sum
# adding a pair of single digit Integers
3 + 5
String addition
string addition single line equations, run in a code cell, will output a single concatenated string
Tip: all strings must be in quotes
# adding a pair of strings
"I wear " + "a hat"
We can also add variables as long as we add strings to strings and numbers to numbers
示例图:
(a)
(b)相信正确的写法不用我再写一遍了吧?
(c)
翻译:
assign:分配
variables:变量。变数。
perform:执行
(二)Errors!
Encountering Errors and troubleshooting errors are fundamental parts of computer programming
TypeError
The line print("my number is " + 123)
causes the TypeError
message to appear
TypeError: Can't convert 'int' object to str implicitly
When adding to the string "my number is "
the compiler is experiencing another string, but finds a number *123
Python cannot convert the Integer 123
to a string without explicit instruction (in code)
in other words, python only allows combining like types
str
+str
int
+int
(三)
More Errors
SyntaxError & NameError
- SyntaxError - breaks code formatting rules of python (破坏了python的代码格式化规则)
- NameError - object is not defined (can't be found)
Python has a specific grammar that it follows that is referred to as syntax(语法).
The print function syntax rules for output of a single string include
- parentheses
( )
containing a string followprint
(SyntaxError) - strings have matching quotation marks (SyntaxError)
print
is lowercase and correctly spelled (NameError)
Failure to follow any of these rules results in a SyntaxError
or NameError
when the code is run
示例图: