0
I'm totally confused about this code.Could anybody explain how this code works?
2 ответов
+ 3
Dipra, i am not sure what is confusing you in this code. You have done a complete python course and normally should master it.
Anyway, here some explanations:
try:
s = ['a','c']
n = [0 , 2]
s[1:1] = 'b'
n[1:1] = [1]
except:
pass
print(s[1],n[1])
First of all you have try: except: block to make sure that errors that occure during execution of a programm can be handled in in a controllable way. So if the program try to open a file that does not exist, the program will be terminated without a try: except: block.
in the try: block 2 lists are created: s with 2 strings and n with 2 integer numbers.
Next step is:
s[1:1] = 'b' and n[1:1] = [1], where new values are assigned. s[1:1] does mean that a new value will be inserted at index 1. So s is now [‘a’, ‘b’, ‘c’].
The except part only contains a pass statement which is a kind of dummy statement and is doing nothing.
Last step is
print(s[1],n[1])
so index 1 from lists ‘s’ and ‘n’ will be printed.
0
Oh,I mixed up list slice with this.BTW..thanks Lothar