Python3

来源:互联网 发布:淘宝电子书阅读器 编辑:程序博客网 时间:2024/05/21 15:50

Numbers

>>> 8 / 5    # division always returns a floating point number1.6>>> 17 / 3   # classic division returns a float5.666666666666667>>>>>> 17 // 3  # floor division discards the fractional part5>>> 2 ** 7   # 2 to the power of 7128>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06>>> from fractions import Fraction>>> Fraction(16, -10)Fraction(-8, 5)>>> Fraction(123)Fraction(123, 1)>>> Fraction()Fraction(0, 1)>>> Fraction('3/7')Fraction(3, 7)>>> Fraction(' -3/7 ')Fraction(-3, 7)>>> Fraction('1.414213 \t\n')Fraction(1414213, 1000000)>>> Fraction('-.125')Fraction(-1, 8)>>> Fraction('7e-6')Fraction(7, 1000000)>>> Fraction(2.25)Fraction(9, 4)>>> Fraction(1.1)Fraction(2476979795053773, 2251799813685248)>>> from decimal import Decimal>>> Fraction(Decimal('1.1'))Fraction(11, 10)

Strings

>>> '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:\someame>>> print(r'C:\some\name')  # note the r before the quoteC:\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 3window 6defenestrate 12# The range() Function>>> for i in range(5):...     print(i)...01234range(5, 10)   5 through 9range(0, 10, 3)   0, 3, 6, 9range(-10, -100, -30)   -10, -40, -70>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):...     print(i, a[i])...0 Mary1 had2 a3 little4 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 number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 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)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597# 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)
0 0
原创粉丝点击