Introduction to Python
Autor: shleshst • March 26, 2016 • Study Guide • 3,226 Words (13 Pages) • 774 Views
Introduction to Python
www.buckysroom.org/forum
Legend – Blue = Output
Green = Commands
Red = error
1. Numbers
• x/y = decimals
• x//y = smallest integer quotient => 18//4 = 4
• x%y = remainder => 18%2 = 2
• x**y = power => 5**3 = 125
2. Strings
We can use single or double quotes. Use double when the string you want to enter may contain apostrophes like “don’t, I’m”, etc. since it will consider that as a single quote and terminate the string definition.
'I didn't know
SyntaxError: invalid syntax
Similarly, use single quotes when the string may contain double quotes like a dialogue.
If a sentence contains both, use escape characters (“\”). It treats the following character as regular text.
'He didn\'t say'
"He didn't say"
Backslash (\) always has a special meaning. Be careful while printing out folder/file paths, since they contain “\” in them.
print('D:\new folder')
D:
ew folder
print(r'D:\new folder')
D:\new folder
• \n => new line
To avoid this, use “r” before the quotes. It disregards all special characters within the quotes. (Raw string)
Ans: It does. Use an IDE.
s='He said "I don\'t know"'
Out[7]: 'He said "I don\'t know"'
s.decode(“string-escape”)
Out[8]: 'He said "I don\'t know"'
Print s.decode(“string-escape”)
He said "I don't know"
s.decode(“utf-8”)
Out[10]: u'He said "I don\'t know"'
Print s.decode(“utf-8”)
He said "I don't know"
s.decode(“utf-8”).encode(“utf-8”)
The decode function in itself just decodes it for the program, not for the output. That’s why with just the decode command, the string displays the escape sequences. Using print, encodes it back again and makes it readable to users (by not displaying the sequence characters)
•Accessing characters in a string => str[n].
If n is positive, it goes left to right. If n is negative, it goes right to left. 0 returns the first value.
S = “shlesh”
S[5] = s[-1] = ‘h’
S[2:5] => sequence excluding 5, including 2
S[:5] => beginning to 4
S[2:] => 2 to the end
• len(): length of a string
3. Lists
Players = [29, 60, 70, 77]
Players[2]=70 (This and the rest same as slicing strings)
Players[2] = 77 => new assignment overwriting the existing value in the list
Players[n:m] = [30,40]=> multiple new assignments overwriting in the specified position range (n to m-1)
...