ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python 基本语法

2019-02-24 19:02:59  阅读:349  来源: 互联网

标签:基本 animals nums Python cat 语法 animal print legs


  • 加减乘除
x = 3
print(type(x))  # <class 'int'>
print(x, x + 1, x - 1, x * 2, x ** 2)  # 3 4 2 6 9

x += 1
print(x)  # 4

x *= 2
print(x)  # 8

y = 2.5
print(type(y))  # <class 'float'>
print(y, y +1, y * 2, y ** 2)  # 2.5 3.5 5.0 6.25
  • 布尔
# Booleans
t = True
f = False
print(type(t))  # <class 'bool'>
print(t and f, t or f, not t, t != f, t == f)  # False True False True False
  • 字符串
hello = "hello"
world = "world"
hw = hello + world
hw12 = "%s %s %d" % (hello, world, 12)
print(hello, world, "!" ";", hw, ";", hw12)  # hello world !; helloworld ; hello world 12

s = "helLo"
print(s.capitalize())  # Hello
print(s.upper())       # HELLO
print(s.lower())       # hello
print(s.rjust(7))      # __helLo
print(s.ljust(7))      # helLo__
print(s.center(7))     # _helLo_
print(s.replace("l",'(ell)'))  # he(ell)Lo
print('     wo  rld     '.strip())  # wo  rld
  • 列表
xs = [3, 1, 2]
print(xs, xs[1], xs[-1])  # [3, 1, 2] 1 2
xs.append('bar')
print(xs)                 # [3, 1, 2, 'bar']
x = xs.pop()
print(x, xs)              # bar [3, 1, 2]
  • 切片
nums = list(range(5))
print(nums)       # [0, 1, 2, 3, 4]
print(nums[-1])   # 4
print(nums[2:4])  # [2, 3]
print(nums[2:])   # [2, 3, 4]
print(nums[:2])   # [0, 1]
print(nums[:])    # [0, 1, 2, 3, 4]
print(nums[:-1])  # [0, 1, 2, 3]
nums[0:2] = [8, 9]
print(nums)       # [8, 9, 2, 3, 4]
  • 循环访问列表
animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)

cat
dog
monkey

for idx, animal in enumerate(animals):
    print('%d:%s' % (idx + 1, animal))

1:cat
2:dog
3:monkey

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print(squares)  # [0, 1, 4, 9, 16]

nums = [0, 1, 2, 3, 4]
squares = [x ** 3 for x in nums]
print(squares)  # [0, 1, 8, 27, 64]

nums = [0, 1, 2, 3, 4]
squares = [x ** 3 for x in nums if x % 2 == 0]
print(squares)  # [0, 8, 64]
  • 字典
d = {'cat': 'cute', 'dog': 'furry'}
print(d['cat'])  # cute
print('cat' in d)  # True
d['fish'] = 'wet'
print(d)  # {'fish': 'wet', 'cat': 'cute', 'dog': 'furry'}
print(d.get('fish', 'N/A'))  # wet
print(d.get('fi  sh', 'N/A'))  # N/A
del d['fish']
print(d.get('fish', 'N/A'))  # N/A
  • 循环访问字典
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal, legs))

A spider has 8 legs
A cat has 4 legs
A person has 2 legs

for animal, legs in d.items():
    print('A %s has %d legs' % (animal, legs))

A cat has 4 legs
A person has 2 legs
A spider has 8 legs

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x+1: x ** 2 for x in nums if x % 2 ==0}
print(even_num_to_square)  # {1: 0, 3: 4, 5: 16}
  • 集合
animals = {'dog', 'cat'}
animals.add('fish')
animals.remove('cat')
animals.add('dog')  # does nothing and no return
print('dog' in animals)  # True
print('do  g' in animals)  # False
print(len(animals))  # 3
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # {0, 1, 2, 3, 4, 5}

d = {(x, x + 1): x for x in range(3)}
t = (0, 1)
print(d)  # {(0, 1): 0, (1, 2): 1, (2, 3): 2}
print(type(t))  # <class 'tuple'>
print(type(d[t]))  # <class 'int'>
print(d[t])  # 0
print(d[(1, 2)])  # 1
  • 函数
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))

negative
zero
positive

def hello(name, loud = False):
    if loud:
        print('HELLO,%s !' % name.upper())
    else:
        print('Hello,%s' % name)

hello('Bob')  # Hello,Bob
hello('Fred', loud=True)  # HELLO,FRED !
class Greeter(object):
    def __init__(self, name):
        self.name = name

    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello,%s' % self.name)

g = Greeter('Fred')
g.greet()  # Hello,Fred
g.greet(loud=True)  # HELLO, FRED!

标签:基本,animals,nums,Python,cat,语法,animal,print,legs
来源: https://www.cnblogs.com/yangzhaonan/p/10427360.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有