欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python基础知识

程序员文章站 2022-07-07 19:18:03
1、print()函数print函数用于向控制台、python解释器、cmd命令行输出你想要输出的内容。print函数有输入参数,可以是字符串、数字、变量等等,也可以是它们的混合,不同对象之间可以使用,来分隔,print函数遇到,的时候会输出一个空格来作为分隔输出的效果。注意:在print函数中,如 ......

学习python第一天笔记

2020.10.11
资料查询 for myself

输出语句

python没有int float等数据类型
print('welcome to python')
welcome to python
print('hello '+' world')
hello  world
print('i love u\n'*5)
i love u
i love u
i love u
i love u
i love u

输入语句

temp=input('please input a number:')
guess=int(temp)
if guess==3:
    print('equal me ^-^')
else:
    print('not equal me :)')
please input a number:1
not equal me :)

BIF=built in function 内置函数

dir(__builtins__)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'WindowsError',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__build_class__',
 '__debug__',
 '__doc__',
 '__import__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'breakpoint',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']
help(input)
Help on method raw_input in module ipykernel.kernelbase:

raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
    Forward raw_input to frontends
    
    Raises
    ------
    StdinNotImplentedError if active frontend doesn't support stdin.

变量

python 没有“变量” 只有 ‘名字’
name='lifat'
print(name)
name='add lifat'
name
lifat





'add lifat'
first=1
second=3
print(first+second)
4

变量名可以包括字母、数字、下划线,但是不能以数字开头

字母可以大写也可以小写,python区分大小写

字符串

print('let\'s GO')
let's GO
print('C:\\now')
C:\now

原始字符串

st=r'let\n'
print(st)
let\n
st=r'let\'s go'#这里有一些问题
print(st)
let\'s go

三重引号

st="""I,
LOVE,
you.
"""
st
'I,\nLOVE,\nyou.\n'
print(st)
I,
LOVE,
you.

条件分支

if语句

if 1==1:
    print('dddddd')
else:
    print('bbbb')
dddddd

while循环

temp=input('please input a number:')
k=int(temp)
while k!=2:
    temp=input('please input a number:')
    k=int(temp)
   
please input a number:2

for循环

range()这个BIF可以使用

help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
 |  
 |  Methods defined here:
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __reduce__(...)
 |      Helper for pickle.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      Return a reverse iterator.
 |  
 |  count(...)
 |      rangeobject.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      rangeobject.index(value) -> integer -- return index of value.
 |      Raise ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop

两个关键语句

break 退出循环
continue 中止本轮循环
temp=input('please input a number:')
k=int(temp)
while k!=1:
    temp=input('please input a number:')
    k=int(temp)
    if k==4:
        break
    elif k==3:
        continue
    print('Test')
    
please input a number:2
please input a number:3
please input a number:2
Test
please input a number:5
Test
please input a number:4

python的数据类型

整型,布尔类型,浮点型,e记法
"520"+'das'
'520das'
a=150000000000000000
a
150000000000000000
15e10
150000000000.0
b=0.00000000000000002
b
2e-17
True+True
2
False+True
1

转化

int()
str()
float()

获得数据类型

type()
isinstance()
type("dddd")
str
a='ddddd'
isinstance(a,str)#这里判断str有问题,是因为上面用str去定义变量
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-150-dd385436226d> in <module>
      1 a='ddddd'
----> 2 isinstance(a,str)#这里判断str有问题,是因为上面用str去定义变量


TypeError: isinstance() arg 2 must be a type or tuple of types
help(str)
No Python documentation found for 'I,\nLOVE,\nyou.'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

基本操作符

算术操作符

+ - * / ** // %
4**5
1024
9//2
4
9%2
1

逻辑操作符

and or not
not True
False
True and True
True
True and False
False
True or False
True

三元操作符

x=4
y=3
small = x if x<y else y
small
3

断言(assert)

当关键字后面的条件为假得到时候,程序自动崩溃并且抛出AssertionError

本文地址:https://blog.csdn.net/li_fat/article/details/109035816