Error: If-Else
Error: If-Else
str(int(myAge) // correct
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and
floats are both numbers.
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
spam = 0
while spam < 5: // while loop
print('Hello, world.')
spam = spam + 1
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
Since randint() is in the random module, you must first type random.
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
def spam():
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] // lists of lists
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat'
>>> spam[1][4]
50
indexes start at 0 and go up. integer value -1 refers to the last index in a list, the value -2
refers to the second-to-last index in a list, and so on.
>>> spam = ['cat', 'bat', 'rat', 'elephant'] // in shortcut sublist with slices.
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
When you run this program, the output will look something like this: // output
Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
A common Python technique is to use range(len(someList)) with a for loop to iterate over the
indexes of a list. For example, enter the following into the interactive shell:
# determine whether a value is or isn’t in a list with the in and not in operators.
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] // 1st index for duplicate value is returned
>>> spam.index('Pooka')
1
** The append() and insert() - methods are list methods and can be called only on list values, not on
other values such as strings or integers.
>>> bacon = 42
>>> bacon.insert(1, 'world') # error insert() is oy for list
>>> spam = ['cat', 'bat', 'rat', 'elephant'] // removing value from list
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
**sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting string
If you need to sort the values in regular alphabetical order, pass str.
lower for the key keyword argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
Python knows that until it sees the ending square bracket, the list is not finished.
you can have code that looks like this:
>>>spam = ['apples', //
'oranges',
'bananas',
'cats']
>>>print(spam)
**You can also split up a single instruction across multiple lines using the \ line continuation
character at the end.
**list value is a mutable data type: It can have values added, removed, or changed. However, a
string is immutable: It cannot be changed.
*like strings, are immutable. Tuples cannot have their values modified, appended, or removed.
The comma is what lets Python know this is a tuple value. (Unlike some other programming
languages, in Python it’s fine to have a trailing comma after the last item in a list or tuple.)
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
**Passing References
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
[1, 2, 3, 'Hello']
indexes for dictionaries can use many different data types, not just integers. Indexes for dictionaries
are called keys, and a key with its associ- ated value is called a key-value pair.
dictionary is typed with braces, {} .