>>> 'spam eggs'# single quotes'spam eggs'>>> 'doesn\'t'# use \' to escape the single quote..."doesn't">>> "doesn't"# ...or use double quotes instead"doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
# String literals can span multiple lines. One way is using triple-quotes: """...""" or# '''...'''. End of lines are automatically included in the string, but it’s possible# to prevent this by adding a \ at the end of the line.>>> print("""/
... Usage: thingy [OPTIONS]
... -h Display this usage message
... -H hostname Hostname to connect to
... """)
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
#here is a end of line>>> # 3 times 'un', followed by 'ium'>>> 3 * 'un' + 'ium''unununium'# Two or more string literals (i.e. the ones enclosed between quotes)# next to each other are automatically concatenated.>>> 'Py''thon''Python'>>> word = 'Python'>>> word[0] # character in position 0'P'>>> word[5] # character in position 5'n'>>> word[-1] # last character'n'>>> word[-2] # second-last character'o'>>> word[-6]
'P'>>> word[0:2] # characters from position 0 (included) to 2 (excluded)'Py'>>> word[2:5] # characters from position 2 (included) to 5 (excluded)'tho'# Note how the start is always included, and the end always excluded.# This makes sure that s[:i] + s[i:] is always equal to s:>>> word[:2] + word[2:]
'Python'>>> word[:4] + word[4:]
'Python'>>> s = 'supercalifragilisticexpialidocious'>>> len(s)
34
List
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> squares[0] = 2
>>> squares
[2, 4, 9, 16, 25]
>>> squares.append(50)
>>> squares
[2, 4, 9, 16, 25, 50]
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
>>> # Fibonacci series:...# the sum of two elements defines the next... a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b
...112358
More Control Flow Tools
# if Statements
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
...else:
... print('More')
...
More
# for Statements
>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12# The range() Function
>>> for i in range(5):
... print(i)
...01234
range(5, 10)
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...0 Mary
1 had
2 a
3 little
4 lamb
# Loop statements may have an else clause; it is executed when the loop terminates# through exhaustion of the list (with for) or when the condition becomes false# (with while), but not when the loop is terminated by a break statement.
>>> for n in range(2, 10):
...for x in range(2, n):
...if n % x == 0:
... print(n, 'equals', x, '*', n//x)
...break...else:
...# loop fell through without finding a factor... print(n, 'is a prime number')
...2 is a prime number
3 is a prime number
4 equals 2 * 25 is a prime number
6 equals 2 * 37 is a prime number
8 equals 2 * 49 equals 3 * 3# pass Statements# The pass statement does nothing. It can be used when a statement is# required syntactically but the program requires no action.
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)...# Defining Functions
>>> def fib(n): # write Fibonacci series up to n..."""Print a Fibonacci series up to n."""... a, b = 0, 1...while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:... fib(2000)
011235813213455891442333776109871597# More on Defining Functions
>>> def ask_ok(prompt, retries=4, reminder='Please try again!'):
...while True:
... ok = input(prompt)
...if ok in ('y', 'ye', 'yes'):
...return True
...if ok in ('n', 'no', 'nop', 'nope'):
...return False
... retries = retries - 1...if retries < 0:
... raise ValueError('invalid user response')
... print(reminder)