-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_6_task
64 lines (51 loc) · 1.75 KB
/
exercise_6_task
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Exercise 6 (and Solution)
Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
Discussion
Concepts for this week:
List indexing
Strings are lists
List indexing
In Python (and most programming in general), you start counting lists from the number 0. The first element in a list is “number 0”, the second is “number 1”, etc.
As a result, when you want to get single elements out of a list, you can ask a list for that number element:
>>> a = [5, 10, 15, 20, 25]
>>> a[3]
20
>>> a[0]
5
There is also a convenient way to get sublists between two indices:
>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:4]
[10, 15, 20]
>>> a[6:]
[35, 40]
>>> a[:-1]
[5, 10, 15, 20, 25, 30, 35]
The first number is the “start index” and the last number is the “end index.”
You can also include a third number in the indexing, to count how often you should read from the list:
>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:5:2]
[10, 20]
>>> a[3:0:-1]
[15, 10, 5]
To read the whole list, just use the variable name (in the above examples, a), or you can also use [:] at the end of the variable name (in the above examples, a[:]).
Strings are lists
Because strings are lists, you can do to strings everything that you do to lists. You can iterate through them:
string = "example"
for c in string:
print "one letter: " + c
Will give the result:
one letter: e
one letter: x
one letter: a
one letter: m
one letter: p
one letter: l
one letter: e
You can take sublists:
>>> string = "example"
>>> s = string[0:5]
>>> print s
examp
Now s has the string “examp” in it.
Moral of the story: a string is a list.
Happy coding!