Text And Number Equivalence
Strings can’t equal integers or floats but integers can equal floats. >>> 42 == '42' False >>> 42 == 42.0 True
Strings can’t equal integers or floats but integers can equal floats. >>> 42 == '42' False >>> 42 == 42.0 True
Function calls are stacked one on top of another. When a program calls a function it stacks that function on top of the program. If that function calls another function it stacks that function on top of the function that called it. The program keeps track of the call stack and when it reaches the return statement of any function it returns to where it was in the previous function or program. ...
Tuples are a form of immutable data type. >>> eggs = ('hello', 42, 0.5) >>> eggs[0] 'hello' >>> eggs[1:3] (42, 0.5) >>> len(eggs) 3 >>> eggs[1] = 99 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment Note tuples can’t have an index reassigned to a value like lists can. To define a single tuple value you put a , after the value. ...
Converts string to uppercase. >>> spam = 'Hello, world!' >>> spam.upper() 'HELLO, WORLD!'
The values() method returns a list of values from a dictionary . @>>> spam = {'color': 'red', 'age': 42} @>>> for v in spam.values(): @... print(v) @... red 42
Variables are stored with assignment statements. An assignment statement consists of a variable name and an assignment operator (equal sign). spam = 42 Variables are initialized the first time a value is stored in it. When a variable is assigned a new value the old value is overwritten. >>> eggs = 'red' >>> eggs 'red' >>> eggs = 'green' >>> eggs 'green' Variable Names # A good variable name describes the data it contains. ...
The code in the while clause will be executed as long as it’s condition is True. while statements always consist of: The while keyword A condition A colon Starting on a newline, an indented clause AKA the while loop. Example # while spam < 5; print('Hello, world.') spam = spam + 1
In order to write to files they need to be opened in either write mode or append mode. Use the write() method to write or append to the file. Example: i>>> baconFile = open('bacon.txt', 'w') i>>> baconFile.write('Hello, world!\n') 14 i>>> baconFile.close() i>>> baconFile = open('bacon.txt', 'a') i>>> baconFile.write('Bacon is not a vegetable.') 25 i>>> baconFile.close() i>>> baconFile = open('bacon.txt') i>>> content = baconFile.read() i>>> baconFile.close() i>>> print(content) Hello, world! Bacon is not a vegetable. ...