zoukankan      html  css  js  c++  java
  • python之数值类型

    数值numbers

    数值类型分为int类型和float类型#和其他程序设计语言一样

    python中+,-,*,/的使用同其他程序设计语言也一样,遵循先乘除后加减,括号内先执行,略微不同的是/,稍后有介绍

    >>> 2 + 2
    4
    >>> 50 - 5*6
    20
    >>> (50 - 5*6) / 4
    5.0
    //the operators +, -, * and / work just like in most other languages (for example, Pascal or C);
    
    >>> 17 / 3  # classic division returns a float
    5.666666666666667
    //此处‘/’默认返回的是浮点数类型(相比c语言中的'/',都是整数默认返回整数,类似求整操作,而python中返回float,取整操作为‘//’)
    >>>
    >>> 17 // 3  # floor division discards the fractional part
    5//python中的取整操作
    >>> 17 % 3  # the % operator returns the remainder of the division
    2 //返回余数
    >>> 5 * 3 + 2  # result * divisor + remainder
    17
    
    #x**y等于power(x,y)
    >>> 5 ** 2  # 5 squared
    25
    //5的平方
    >>> 2 ** 7  # 2 to the power of 7
    128
    //2的7次方
    
    >>> width = 20
    >>>width
    20
    >>> height = 5 * 9
    >>>height
    45
    >>> width * height
    900
    //‘=’等号用以给变量赋值
    
    >>> n  # try to access an undefined variable
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'n' is not defined
    //如果没有事前定义变量,直接使用会出错
    
    >>> tax = 12.5 / 100
    >>> price = 100.50
    >>> price * tax
    12.5625
    >>> price + _
    113.0625
    //此处_值为上一步price * tax的值12.5625
    >>> round(_, 2)
    113.06
    //此处_值为上一步打印出来的113.0625,操作保留2位小数
    

    布尔类型Booleans

    t = True
    f = False
    print(type(t)) # Prints "<class 'bool'>"
    print(t and f) # Logical AND; prints "False"
    print(t or f) # Logical OR; prints "True"
    print(not t) # Logical NOT; prints "False"
    print(t != f) # Logical XOR; prints "True"
    

    字符串string类型

    hello = 'hello' # String literals can use single quotes
    world = "world" # or double quotes; it does not matter.
    print(hello) # Prints "hello"
    print(len(hello)) # String length; prints "5"
    hw = hello + ' ' + world # String concatenation
    print(hw) # prints "hello world"
    hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
    print(hw12) # prints "hello world 12"
    
    s = "hello"
    print(s.capitalize()) # Capitalize a string; prints "Hello"
    print(s.upper()) # Convert a string to uppercase; prints "HELLO"
    print(s.rjust(7)) # Right-justify a string, padding with spaces;
    print(s.center(7)) # Center a string, padding with spaces; 
    print(s.replace('l', '(ell)')) 
    # Replace all instances of one substring with another substring
     # prints "he(ell)(ell)o"
    print(' world '.strip()) # Strip leading and trailing whitespace; 
    
  • 相关阅读:
    【模板】辗转相除法
    【模板】冰茶姬(大概是全的?)
    【模板】快速幂
    【模板】线段树-区间修改
    【模板】线段树-单点修改,区间查询
    【模板】dijkstra与floyd
    【模板】SPFA(不完全详解)
    【济南集训】随机分数
    P3205 [HNOI2010]合唱队
    最大子列2
  • 原文地址:https://www.cnblogs.com/zhichao-yan/p/13368520.html
Copyright © 2011-2022 走看看