Strings versus lists, and a small checker program
Strings and lists are both ordered and both use indexes, but they differ. A string is written in quotation marks, holds only characters and cannot be changed. A list is written in square brackets, holds any values and can be changed. The function list() turns a string into a list of single characters: list("cat") gives ['c', 'a', 't']. You do not need it to loop over a string, because a loop can visit a string directly. Two small programs use both ideas. The first prints the names that start with S, using name[0]. The second gives a strength score to a sample string, one point each for the length, a digit, a capital letter and a symbol. After finding the first digit the loop uses break, so each rule gives at most one point. The sample is an invented string. In real life never type a real password into any practice program or game.
| String | List | |
|---|---|---|
| Written with | quotation marks | square brackets |
| Can hold | characters only | any values |
| Can be changed | no | yes |
1names = ["Mona", "Omar", "Salma", "Sami"] 2for name in names: 3 if name[0] == "S": 4 print(name)
Salma Sami
1sample = "Blue7sky!" 2symbols = "@#$%&!" 3score = 0 4if len(sample) >= 8: 5 score += 1 6for ch in sample: 7 if ch.isdigit(): 8 score += 1 9 break 10for ch in sample: 11 if ch.isupper(): 12 score += 1 13 break 14for ch in sample: 15 if ch in symbols: 16 score += 1 17 break 18print(score)
4
Use the four checks to give a score to these invented strings, never your own: “Sunny2024”, “tree!”, “ABCDEFGH”. Fill a table with 1 or 0 for each check and the total. Which string scores highest?
1names = ["Mona", "Omar", "Salma", "Sami"] 2for name in names: 3 if name[0] == "S": 4 print(name)