Professional Documents
Culture Documents
Python - Data Type, String, Operators
Python - Data Type, String, Operators
>>> b Traceback (innermost last): File "<interactive input>", line 1, in ? NameError: b >>>
10
11
Strings in use
34 5here are strings displayed and entered6
12
String composition
"trings are a composite data type
! ! ! ! 2uilt from another data type, characters #n a string, characters are stored in sequence$ "trings can be any length (including empty $ "tring are enclosed in quotation mar.s$
str_var = "300 m/s" empty_str=""
13
Length o a string
'se len(str) to return string length (7 of characters
sample="SERIES" len(sample)=6 empty_str="" len(empty_str) = 0
14
String representation
#n strings, characters are accessed by inde!
! 8li.e mailboxes in an apartment building$ ! /irst index is 9, not :$
s="LE EL" start!"ar=s# 0$ %&st_v=ss# 2 $
15
#perations$ %oncatenation
-ombine strings using & (concatenation operator
(&ll_name = ")enry" * " " * "+ames" print "," * (&ll_name * ","
inde8*=:
17
18
19
20
21
22
23
24
#perators
25
#perators
;ython has many operators$ "ome examples are4 *< =< >< /< ?< @< 1< == print 1perators perform an action on one or more operands$ "ome operators accept operands before and after themselves4 -perand: * -perand., or 3 * 2 1thers are followed by one or more operands until the end of the line, such as4 print 4)iA5< 3.< 3B 5hen operators are evaluated, they perform action on their operands, and produce a new value$
26
Type %onversion
int() 6loat() str() Examples4 int(3;3) produces I str(3;3) produces AI$ID
(l-at(3) produces I$9 (l-at(43;25) produces I$@ int(4C5) produces G int(4C;:5) throws an ESS1SC (l-at(4Dest5) *hrows an ESS1SC
30
Variables
Variables are names that can point to data$ *hey are useful for saving intermediate results and .eeping data organi0ed$ *he assignment operator (= assigns data to variables$
)onTt confuse the assignment operator (single equal sign, = with the Equality+*est operator (double equal sign, ==
Variable names can be made up of letters, numbers and underscores (U , and must start with a letter$
31
Variables
5hen a variable is evaluated, it produces the value of the data that it points to$ /or example4 my aria/le = 2 my aria/le produces @ my aria/le * :0 produces :@ >ou %'"* assign something to a variable (to create the variable name before you try to use (evaluate it$
32
Program E!ample
/ind the area of a circle given the radius4 Radi&s = :0 pi = 3;:3:2E area = pi > Radi&s > Radi&s print area will print I:H$:@ to the screen$
33
&ames that are defined outside of a function are AglobalD to the module$
(ocal names overshadow global names when inside the function that defined them$
#f you want to access a global variable from inside of a function, you should declare it AglobalD$
34
35