Week 5

All the function learnt this week 

Storing multiple values
When storing more than one value it an get repetitive
Example - 
author1 = "J.K. Rowling"
author2 = "P. Pullman"
author3 = "S. Collins"
print(author1)
print(author2)

print(author3)
Instead we can make lists using a for loop
Example - 
authors = ["J.K. Rowling", "P. Pullman", "S. Collins"]
for author in authors:

  print(author)
or 
odds = [1, 3, 5, 7, 9]
print(odds)
Reading in Lists
Example - 
data = input("Enter your subjects: ")
subjects = data.split()
print(subjects)
Enter your subjects: hv kb jb
['hv', 'kb', 'jb']
or put it in a for loop to print it in a vertical list

Lists

Acessing list items:
Example - 
colours = ['red', 'blue', 'green', 'yellow']
print(colours[1])
print(colours[-1])

Changing list items; 
Example - 
colours = ['red', 'blue', 'green', 'yellow']
colours[0] = 'crimson'
colours[-2] = 'lime'
print(colours)
Sorting 
Use these functions for sorting data out, use  sort to sort alphabetically and in number order or append and add a variable into the brackets to sort from that variable. Also reverse will do the opposite. 
Append: 
Example - 
pets = ['dog', 'mouse', 'fish']
pets.append('cat')
print(pets)
['dog', 'mouse', 'fish', 'cat']
Sort:
Example - 
pets = ['dog', 'mouse', 'fish', 'cat']
pets.sort()
print(pets)
['cat', 'dog', 'fish', 'mouse']
Reverse; 
Example - 
pets = ['cat', 'dog', 'fish', 'mouse']
pets.reverse()
print(pets)
['mouse', 'fish', 'dog', 'cat']
List of words or characters 
Characters:
Example - 
print(list('hello'))
['h', 'e', 'l', 'l', 'o']
Words: 
Example - 
line = 'hello world'
words = line.split()
print(words)
['hello', 'world']

Creating sublists and finding indexes
Sublist:
Example - 
colours = ['red', 'blue', 'green', 'yellow']
fewer_colours = colours[:2]
print(fewer_colours)
['red', 'blue']
Indexes: 
Example - 
words = ['the', 'fox', 'jumped', 'over', 'the', 'dog']
print(words.index('fox'))
print(words.index('dog'))
1
5
Joining & Splitting 
Joining with spaces; 
Example - 
values = ['a', 'b', 'c', 'd', 'e']
print(' '.join(values))
a b c d e
Joining with seprator:
Example - 
sep = ':'
values = ['a', 'b', 'c', 'd', 'e']
print(sep.join(values))
a:b:c:d:e

No comments:

Post a Comment