Python I Basics [C]


Python I Basics

在这里插入图片描述

Python Basic 1 : Intro

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • use # for comment
  • Eclipse + PyDev
  • Emacs & Vim
  • ActivePython
  • WingIDE
>>> help()

Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not
class               from                or
continue            global              pass

help> modules

Please wait a moment while I gather a list of all available modules...

__future__          abc                 html                setuptools
_ast                aifc                http                shelve
_bisect             antigravity         idlelib             shlex
_bootlocale         argparse            imaplib             shutil
_bz2                array               imghdr              signal
_codecs             ast                 imp                 site
_codecs_cn          asynchat            importlib           smtpd
_codecs_hk          asyncio             inspect             smtplib
_codecs_iso2022     asyncore            io                  sndhdr
_codecs_jp          atexit              ipaddress           socket
_codecs_kr          audioop             itertools           socketserver
_codecs_tw          base64              json                sqlite3
_collections        bdb                 keyword             sre_compile
_collections_abc    binascii            lib2to3             sre_constants
_compat_pickle      binhex              linecache           sre_parse
_compression        bisect              locale              ssl
_csv                builtins            logging             stat
_ctypes             bz2                 lzma                statistics
_ctypes_test        cProfile            macpath             string
_datetime           calendar            macurl2path         stringprep
_decimal            cgi                 mailbox             struct
_dummy_thread       cgitb               mailcap             subprocess
_elementtree        chunk               marshal             sunau
_functools          cmath               math                symbol
_hashlib            cmd                 mimetypes           symtable
_heapq              code                mmap                sys
_imp                codecs              modulefinder        sysconfig
_io                 codeop              msilib              tabnanny
_json               collections         msvcrt              tarfile
_locale             colorsys            multiprocessing     telnetlib
_lsprof             compileall          netrc               tempfile
_lzma               concurrent          nntplib             test
_markerlib          configparser        nt                  textwrap
_markupbase         contextlib          ntpath              this
_md5                copy                nturl2path          threading
_msi                copyreg             numbers             time
_multibytecodec     crypt               opcode              timeit
_multiprocessing    csv                 operator            tkinter
_opcode             ctypes              optparse            token
_operator           curses              os                  tokenize
_osx_support        datetime            parser              trace
_overlapped         dbm                 pathlib             traceback
_pickle             decimal             pdb                 tracemalloc
_pydecimal          difflib             pickle              tty
_pyio               dis                 pickletools         turtle
_random             distutils           pip                 turtledemo
_sha1               doctest             pipes               types
_sha256             dummy_threading     pkg_resources       typing
_sha512             easy_install        pkgutil             unicodedata
_signal             email               platform            unittest
_sitebuiltins       encodings           plistlib            urllib
_socket             ensurepip           poplib              uu
_sqlite3            enum                posixpath           uuid
_sre                errno               pprint              venv
_ssl                faulthandler        profile             warnings
_stat               filecmp             pstats              wave
_string             fileinput           pty                 weakref
_strptime           fnmatch             py_compile          webbrowser
_struct             formatter           pyclbr              winreg
_symtable           fractions           pydoc               winsound
_testbuffer         ftplib              pydoc_data          wsgiref
_testcapi           functools           pyexpat             xdrlib
_testimportmultiple gc                  queue               xml
_testmultiphase     genericpath         quopri              xmlrpc
_thread             getopt              random              xxsubtype
_threading_local    getpass             re                  zipapp
_tkinter            gettext             reprlib             zipfile
_tracemalloc        glob                rlcompleter         zipimport
_warnings           gzip                runpy               zlib
_weakref            hashlib             sched
_weakrefset         heapq               select
_winapi             hmac                selectors

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

Python Basic 2 : Flow

  • print digits
  • helloworld.py
print("hello world")
x = int(input('enter 3 digit num: '))
a = x//100 #floor
b = (x-100*a)//10 #floor
c = x-100*a-10*b
print(a, b, c)
  • triangle
import math
a= int(input("enter first sides length: "))
b= int(input("enter second side length: "))
x= int(input("enter angle between (degrees, int): "))
sita=x
c=round(math.sqrt(a**2 +b**2 -2*a*b*math.cos(sita*math.pi/180)))
print ('c=' +str(c))

在这里插入图片描述

Resistance of the series circuit
Rt=R1+R2+R3

Rt= Total Resistance
R1 = Resistance 1
R2 = Resistance 2
R3 = Resistance 3

  • resistor.py
r1 = float(input("enter resistors1:" ))
r2 = float(input("enter resistors2:" ))
R=1.0/(1.0/r1+1.0/r2)
print("R="+'%6.2f' %R)

在这里插入图片描述

  • test
a=3
b=a
a= 'python'
print (a)
print (b)
#python
#3
  • test
a=3+4j
b=4+5j
c=a+b
print(c)
#(7+9j)
  • common functions
  • eval()
  • range()
  • ord() ; chr()
  • set()
  • int(x[,d])
  • console
>>> 0o11
9
>>> 0b101
5
>>> 'abc'+'123'
'abc123'
>>> s='''insert into alist(name, address) values (
... "tom","NYC")'''
>>> print (s)
insert into alist(name, address) values (
"tom","NYC")
>>> x=-1
>>> abs(x)
1
>>> x=10
>>> bin(x)
'0b1010'
>>> ord('A')
65
>>> chr(65)
'A'
>>> x=1
>>> type(x)
<class 'int'>
>>> x=1.0
>>> type(x)
<class 'float'>
>>> [1,2,3]
[1, 2, 3]
>>> x=[1,2,3]
>>> type(x)
<class 'list'>
>>> x=(1,2,3)
>>> type(x)
<class 'tuple'>
>>> x={"1":2}
>>> type(x)
<class 'dict'>
>>>
>>> eval('5')
5
>>> x,y=eval('3,4')
>>> x,y
(3, 4)
>>> w=5
>>> r=2
>>> print( eval('2*w+r'))
12
>>> dict1={'x':1,'y':2}
>>> dict2={'z':3}
>>> a=eval('3*x +2*y +1*z',dict1,dict2)
>>> a
10
>>> range(5)
range(0, 5)
>>> range(2,10,3)
range(2, 10, 3)
>>> basket=['a','b','c']
>>> fruit=set(basket)
>>> print (fruit)
{'c', 'a', 'b'}
>>> 'a' in fruit
True
>>> 'd' in fruit
False
>>>
>>>
>>> int (12.0)
12
>>> int('11',2) #int in base 2
3
>>> int (12.8)
12
>>> int('10',2)
2
>>> int('12',2)
>>>> int ('f', 16) # base 16
15
>>>

在这里插入图片描述

  • del
>>> x=5
>>> x
5
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

在这里插入图片描述

  • raw_input obsolete, use input
  • input
>>> x=input('x=')
x=5.2
>>> x=input('x=')
x=12,4
>>> x
'12,4'
>>> x,y= input('x, y=').split(',')
x, y=1,3
>>> x
'1'
>>> y
'3'
>>> s=input('s=')
s='state'
>>> s
"'state'"
>>> x=input('x=')
x=(3,4)
>>> x
'(3,4)'
>>> print (1+2)
3
>>> print(1,2,3,4)
1 2 3 4

在这里插入图片描述
在这里插入图片描述

  • import
>>> import math
>>> math.cos
<built-in function cos>
>>> math.cos(.5)
0.8775825618903728
>>> math.sin(1)
0.8414709848078965
>>>
>>>
>>>
>>>
>>> from math import *
>>> sin(1)
0.8414709848078965
>>>
>>>
>>> from math import sin,cos
>>> sin(1)
0.8414709848078965
>>> cos(.5)
0.8775825618903728
  • printList.py
a=[[111,2,30],[4,50,6],[7,8,9]]
s1=''
print ('####################1')
for x in a :
    s=''
    for y in x :
        s1='%6d'%y
        s=s+s1
    print(s)
print ('####################2')
i=j=0
while i<3:
    j=0
    s=''
    while j<3:
        s1=str(a[i][j])
        s=s+(s1+' '*(6-len(s1)))
        j=j+1
    print(s)
    i=i+1
print ('\n uses two methods to print lists. \n')
#output

####################1
#   111     2    30
#     4    50     6
#    7     8     9
####################2
#111   2     30    
#4     50    6     
#7     8     9     

# uses two methods. 

  • dateTime1
import datetime
today=datetime.date.today()
one=datetime.timedelta(days=1)
yesterday=today-one
tomorrow=today+one
print(yesterday,today,tomorrow)
  • arrange
s=input('x,y,z=')
x,y,z=s.split(',')
if x>y:
    x,y=y,x
if x>z:
    x,z=z,x
if y>z:
    y,z=z,y
print (x,y,z)]

在这里插入图片描述

  • getcwd()
  • os.listdir()
>>> import os
>>> print('%s' %(os.getcwd()))
D:\program files (x86)\python-3.5.1
>>> import os
>>> x=os.getcwd()
>>> x
'D:\\program files (x86)\\python-3.5.1'
>>> os.listdir(x)
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python
3.dll', 'python35.dll', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools', 'vcruntime
140.dll']
>>> os.mkdir(x+"\\00newDir")
>>> os.listdir(x)
['00newDir', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.e
xe', 'python3.dll', 'python35.dll', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools'
, 'vcruntime140.dll']
>>>
  • string
>>> x=input('enter 8 digit date: ')i
enter 8 digit date: 20200102
>>> x
'20200102'
>>> type(x)
<class 'str'>
>>> y=x[0:4]
>>> y
'2020'
>>> m=x[4:6]
>>> m
'01'
>>> d=x[6:8]
>>> d
'02'
  • char
>>> x=int(input('enter integer:'))
enter integer:10
>>> chr(x)
'\n'
>>> x=int(input('enter integer:'))
enter integer:31
>>> chr(x)
'\x1f'
>>>
  • base
>>> x=int(input('enter 10 dig integer: '))
enter 10 dig integer: 1234567890
>>> b=bin(x)
>>> o=oct(x)
>>> h=hex(x)
>>> print(b,o,h)
0b1001001100101100000001011010010 0o11145401322 0x499602d2

Python Basic 3 : Sequence

在这里插入图片描述

  • sort using if,elif
  • arrange2
x1=input('enter x1:')
x2=input('enter x2:')
x3=input('enter x3:')
x4=input('enter x4:')
x5=input('enter x5:')

#x1,x2
if x1>x2:
    x1,x2=x2,x1

#x1, x2, x3
if x1>x3:
    x1,x2,x3=x3,x1,x2
elif x2>x3:
    x2,x3=x3,x2

#x1,x2, x3, x4
if x1>x4:
    x1,x2,x3,x4=x4,x1,x2,x3
elif x2>x4:
    x2,x3, x4=x4, x2,x3
elif x3>x4:
    x3,x4=x4,x3

#x1,x2,x3,x4,x5
if x1>x5:
    x1,x2,x3,x4, x5=x5,x1,x2,x3,x4
elif x2>x5:
    x2,x3,x4, x5=x5,x2,x3,x4
elif x3>x5:
    x3,x4,x5=x5,x3,x4
elif x4>x5:
    x4,x5=x5,x4

#print
print ("output:",x1,x2,x3,x4,x5)
  • sort.py
data_list=[]

#input 5 values
for integer in range(5):
    x=input('enter value '+str(integer+1)+':')
    data_list=data_list+[x]

print("entered list: ",data_list)

#sort
data_list.sort()

print("sorted list: ",data_list)
  • dict (“key”:value, “key2”:value2…)
  • dict.py
#dict
dict={'a':"algorithm",'b':"bug", 'c':"compile"}
#input
key=input("enter (a;b;c):")
#while
while key>='a' and key<='c':
    print(":",dict[key])
    key = input("enter (a;b;c):")

在这里插入图片描述

  • shell
  • list

>>> a=[10,20,30,40]
>>> a
[10, 20, 30, 40]
>>> b=['ca','al','de']
>>> b
['ca', 'al', 'de']
>>> c=['a',10,[1,2]]
>>> c
['a', 10, [1, 2]]
>>> c[0]
'a'
>>> c[2]
[1, 2]
>>> c[-1]
[1, 2]
>>> c[-2]
10
>>> c[-3]
'a'
>>> print(c[0:2])
['a', 10]
>>> print(c[0:3])
['a', 10, [1, 2]]
>>> print(c[2])
[1, 2]
>>> print(c[1:2])
[10]
>>> print(c[2])
[1, 2]
>>> print(c[:2])
['a', 10]
>>> print(c[0:])
['a', 10, [1, 2]]
>>>
  • a_list
  • shell
>>> a_list=[1]
>>> a_list=a_list+['a',2.0]
>>> a_list
[1, 'a', 2.0]
>>>
>>> a_list=[1]
>>> a_list=a_list+['a',2.0]
>>> a_list
[1, 'a', 2.0]
>>>
>>> a_list.append(True)
>>> a_list
[1, 'a', 2.0, True]
>>>
>>> a_list.insert(0,'y')
>>> a_list
['y', 1, 'a', 2.0, True]
>>>
>>> a_list.insert(1,'z')
>>> a_list
['y', 'z', 1, 'a', 2.0, True]
>>>
>>> a_list.count('x')
0
>>>
>>> a_list.extend(['x',4])
>>> a_list
['y', 'z', 1, 'a', 2.0, True, 'x', 4]
>>>
>>> a_list.count('x')
1
>>> a_list.insert(0,'y')
>>> a_list.count('y')
2
>>> a_list
['y', 'y', 'z', 1, 'a', 2.0, True, 'x', 4]
>>>
>>> 3 in a_list
False
>>> 'y' in a_list
True
>>> a_list.index('y')
0
>>> a_list.index(4)
8
>>> a_list
['y', 'y', 'z', 1, 'a', 2.0, True, 'x', 4]
>>> del a_list[0]
>>> a_list
['y', 'z', 1, 'a', 2.0, True, 'x', 4]
>>> a_list.remove(True)
>>> a_list
['y', 'z', 'a', 2.0, True, 'x', 4]
>>> a_list.remove(True)
>>> a_list
['y', 'z', 'a', 2.0, 'x', 4]
>>> a_list.pop()
4
>>> a_list
['y', 'z', 'a', 2.0, 'x']
>>> a_list.pop(0)
'y'
>>> a_list.pop(0)
'z'
>>> a_list
['a', 2.0, 'x']

在这里插入图片描述

  • multiple lists

  • comp() obsolete, use==

  • shell

>>> list1=[123,'xyz']
>>> list2=[123,'abc']
>>> list1==list2
False
>>> list1[0]==list2[0]
True
>>> list1[1]==list2[1]
False
>>> list1
[123, 'xyz']
>>> len(list1)
2
>>>
>>> str1=['abc','xyz','123']
>>> num1=[123,456,789]
>>> max(str1)
'xyz'
>>> max(num1)
789
>>> min(str1)
'123'
>>> min(num1)
123
>>>

在这里插入图片描述

  • reversed

  • sorted

  • shell

>>> list=[1,3,4,5,0,2]
>>> for x in reversed(list):
...     print (x)
...
2
0
5
4
3
1
>>>
>>> sorted(list)
[0, 1, 2, 3, 4, 5]
>>>
>>> sorted(list, reverse=True)
[5, 4, 3, 2, 1, 0]
>>> sorted(list, reverse=False)
[0, 1, 2, 3, 4, 5]
>>>
>>> sum(list)
15

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • tuple
  • shell
>>> a_tuple=('a','b','program','z','example')
>>> a_tuple
('a', 'b', 'program', 'z', 'example')
>>> a_tuple[2]
'program'
>>> a_tuple[-1]
'example'
>>> a_tuple[-2]
'z'
>>> a_tuple[1:3]
('b', 'program')
>>> a_tuple
('a', 'b', 'program', 'z', 'example')
>>> a_tuple.index('z')
3
>>> a_tuple.count('z')
1
>>> a_tuple.count('za')
0
>>> 'z' in a_tuple
True
>>> 'za' in a_tuple
False
>>>
>>> a_list=['a','b']
>>> tuple(a_list)
('a', 'b')
>>>
>>> v_tuple=(False,1,'a')
>>> x,y,z=v_tuple
>>> x
False
>>> y
1
>>> z
'a'

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • dictionary
>>> a_dict={'server':'db.org','database':'mysql'}
>>> a_dict
{'server': 'db.org', 'database': 'mysql'}
>>> a_dict['server']
'db.org'
>>> a_dict['database']
'mysql'
>>>
>>> for key in a_dict.keys():
...     print(key,a_dict[key])
...
server db.org
database mysql
>>>
>>> a_dict['user']='bob'
>>> a_dict
{'user': 'bob', 'server': 'db.org', 'database': 'mysql'}
>>> len(a_dict)
3
>>> 'database' in a_dict
True
>>> 'teacher' in a_dict
False
>>> del a_dict['server']
>>> a_dict
{'user': 'bob', 'database': 'mysql'}
>>>
>>> a_dict.pop('user')
'bob'
>>>
>>> a_dict['database']='sql'
>>> a_dict
{'database': 'sql'}
>>>
>>> a_dict['user']='sam'
>>> a_dict
{'user': 'sam', 'database': 'sql'}
>>>
>>> a_dict.clear()
>>>
>>> a_dict
{}
>>> a_dict['user']='sam'
>>>
>>> a_dict
{'user': 'sam'}
>>>
>>> del a_dict
>>>
>>> a_dict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a_dict' is not defined
>>>
  • score.py
score=[69,75,32,99,78,45,88,72,83,78]

a=0
b=0
c=0
d=0

#print all scores
print ("score")
for s in score:
    print(s)

#return
print()

#score count
for s in score:
    if s<60:
        d=d+1
    elif s<80:
        c=c+1
    elif s<90:
        b=b+1
    else:
        a=a+1

print ("A:",a, " B",b," C",c," D",d)
  • score2.py
studscore={"Bob":45,"Sam":78,"Mary":40,"Beth":96,"Paul":65,"Will":60,
           "Kim":50,"Ian":99,"Carol":80,"Norman":87}
maxscore=0
maxname=''
minscore=100
minname=''
avgscore=0
studcnt=len(studscore)
#print score
print("score")
for key in studscore.keys():
    print (key,studscore[key],";")
print()
#print score count
for key in studscore.keys():
    if studscore[key]>maxscore:
        maxscore=studscore[key]
        maxname=key
    if studscore[key]<minscore:
        minscore=studscore[key]
        minname=key
    avgscore=avgscore+studscore[key]

avgscore=avgscore/studcnt

print("total students:",studcnt,"; average:",avgscore)
print("max:",maxscore,maxname)
print("min:",minscore,minname)
  • posneg.py
x=int(input('input integer:'))

if x>0:
    print ('positive')
else:
    print('negative')

在这里插入图片描述
+shell

>>>
>>> 3+2
5
>>> 7%3
1
>>> 7/3
2.3333333333333335
>>> 3==3
True
>>> 3==4
False
>>> 2*3
6
>>> 2**3
8
>>> 'abc'=='abc'
True
>>> 2!=2
False
>>> 2!=3
True
>>> a=[1,2]
>>> b=[3,4]
>>> a==b
False
>>> 'a'>'b'
False
>>> 'a'=='a'
True
>>> 3>2
True
>>> 3>=3
True
>>> 3>3
False
>>> 'abc'>'aaa'
True
>>> 'Abc'.islower()=='abc'
False
>>> 'Abc'.lower()=='abc'
True
>>> 'Abc'.lower()=='aBc'.lower()
True
>>> 'Abc'.islower()
False
>>>
>>>> 'abC'.upper()=='aBc'.upper()
True
>>>
>>> a=[1,2,3]
>>> 1 in a
True
>>> 8 in a
False
>>> 8 not in a
True
>>> s='abcde'
>>> 'a' in s
True
>>> 'ab' in s
True
>>> a=[2,3,4]
>>> b=a
>>> a==b
True
>>> a is b
True
>>> b=[4,5,6]
>>> a is b
False
>>> a==b
False
>>> 3 and 0
0
>>> 3 or 0
3
>>> a='c'
>>> a and 0
0
>>> a or 0
'c'
>>> b=''
>>> a and b
''
>>> c=['a', 'b', 'c']
>>> b or c
['a', 'b', 'c']
>>> b and c
''
>>> not -2
False
>>> not 0
True
>>> not ''
True
>>> not '2'
False
>>>
>>> a=[]
>>> not a
True
>>> a=[2]
>>> not a
False
>>>
>>> score=int(input('enter integer:'))
enter integer:40
>>> score>=90 and score<=100
False

Python Basic 4 : Choice

在这里插入图片描述

在这里插入图片描述

  • Boolean

  • True, False

  • if

  • choice1.py

a=3
b=5
if a>b:
    t=a
    a=b
    b=t
print('list ascending:')
print(a,b)
  • circumference.py
import math

r=float(input('enter radius: '))

if r>=0:
    c=math.pi*(r**2)
    print('c=pi*r*r=',c)
  • evenOdd.py
score=int(input('enter grade:'))

if score<0 or score>100:
    print('invalid')
elif score<60:
    print('retake test')
elif score<80:
    print('average')
elif score<90:
    print('good')
else:
    print('excellent')
  • user split to input multiple values

  • x,y= input(‘x, y=’).split(’,’)

  • tickest1.py

n=int(input('enter number of tickets:'))
m=int(input('enter number of stops:'))

if m<=4:
    pay=3 *n
else:
    if m<=9:
        pay=4*n
    else:
        pay=5*n
print('total:', pay)

Python Basic 5 : Loop

在这里插入图片描述

  • while
endflag='yes'
sum=0.0
count=0

while endflag[0]=='y':
    x=int(input('enter integer:'))
    sum=sum+x
    count=count+1
    endflag=input("continue? y or n: ")

print('\naverage: ',sum/count)
  • while2
print('enter integers, stops loop when neg num entered')

sum=0
x=int(input('enter integer:'))
while x>=0:
    sum=sum+x
    x=int(input('enter integer:'))

print('sum: ',sum)
  • while 3
a=input('enter String: # to stop:')

while a!='#':
    print('String: ',a)
    a = input('enter String: # to stop:')
else:
    print('end')
  • while 4 sum 1…100
i=1
sum=0

while i<=100:
    sum=sum+i
    i+=1

print('1+...+100=',sum)
  • while5 , print list
a_list=['a','b','cde','z','jamie','kody','cart']
a_len=len(a_list)

i=0
while i<a_len:
    print("#", i+1, ': ',a_list[i])
    i+=1
  • while6

while True:
    a=input('enter string, # to end: ')
    if a!='#':
        print("String: ",a)
    else:
        break

  • while7
i=1

print('1-100 divisible by 7 but not 5:')

while i<=100:
    if i%7==0 and i %5!=0:
        print(i)
    i+=1
  • Narcissistic Number An - digit number that is the sum of the th powers of its digits is called an -narcissistic number. It is also sometimes known as an Armstrong number, perfect digital invariant (Madachy 1979), or plus perfect number.
  • 153=1^3 +53+33
import math
i=100
print('narcissus numbers:')
while i<=999:
    h=math.floor(i/100)
    t=math.floor((i%100)/10)
    d=math.floor(i%10)
    if h**3+t**3+d**3==i:
        print(i)
    i=i+1

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • for
a_list=input('enter integer list:').split(',')
sum=0

for x in a_list:
    a=int(x)
    if a>0 and a%2==0:
        sum=sum+a

print('sum of even numbers: ',sum)
  • for2, avg
score=[70,90,78,85,97,94,65,80]
print('scores: ',score)
avg=sum(score)/len(score)
print('avg:',avg)
  • for3.avg
score=[70,90,78,85,97,94,65,80]
sum=0
print('scores: ',score)

for i in range(len(score)):
    print(score[i])
    sum+=score[i]

avg =sum/len(score)
print('avg=',avg)
  • for 4
score=[70,90,78,85,97,94,65,80]
print('scores: ',score)

print('max:',max(score))
print('min:',min(score))

print('method2')
print('scores: ',score)
max_sc=score[0]
min_sc=score[0]
for i in score:
    if i>max_sc:
        max_sc=i
    if i<min_sc:
        min_sc=i
print('max: ',max_sc)
print('min: ',min_sc)
  • for 5
s=0.0
n=int(input('input integer:'))
for i in range(1,n+1,1):
    s=s+1.0/i

print('1+1/2...1/',n,'=',s)
  • for6
for i in range(1,10,1):
    for j in range(1,i+1,1):
        print(i,'*',j,'=',i*j, '\t')
    print()
  • for7
score=[70,90,78,85,97,94,65,80]
print('scores: ',score)

print('sorted:',sorted(score))

print('method 2, using for loop')
print('scores: ',score)

a=len(score)
for i in range(a-1):
    min_sc=score[i]
    k=i
    for j in range(i+1,a, 1):
        if min_sc>score[j]:
            min_sc=score[j]
            k=j
    t=score[i]
    score[i]=score[k]
    score[k]=t
print('sorted: ',score)

在这里插入图片描述

  • break1
for i in range(200,1, -1):
    if i% 17 ==0:
        break

print('largest num divisible by 17 within 200 is: ', i)
  • break2
x=int(input('input integer:'))
for i in range(2,x,1):
    if x% i==0:
        break
if i==x-1:
    print(x,':odd')
else:
    print(x,':even')

在这里插入图片描述

  • continue
s=0
print('divisible by 17, within 200:')
for i in range(1,201,1):
    if i%17!=0:
        continue
    print(i)
    s+=1
print('total number: ',s)

Python Basic 6 : String

  • list
Li=['abc','def','ghi','jkl','mno','pqr']
print(Li)
Li.sort(reverse=True)
print('decreasing:')
print(Li)
Li2=Li[:]
print(Li2)
print('increasing')
Li2.sort()
print(Li2)

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • string1
s=input('enter numbers, separated by , :').split(',')
print(s)

sum=0
for x in s:
    sum=sum+float(x)
print ('sum=',sum)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • shell
>>> a=3.4445
>>> '%7.3f'%a
'  3.445'
>>> i=99
>>> s='abc'
>>> x=1234
>>> so='%o'%x
>>> so
'2322'
>>> sh='%x'%x
>>> sh
'4d2'
>>> se='%e'%x
>>> se
'1.234000e+03'
>>> x
1234
>>> s
'abc'
>>> s[0]
'a'
>>> s[-1]
'c'
>>> s[:2]
'ab'
>>> s[2:3]
'c'
>>> s[:]
'abc'
>>>
>>>> s='abc,def,bcd,efg'
>>> s.find('def')
4
>>> s.find('efg')
12
>>> s.find('def',5)
-1
>>> s.find('def',4)
4
>>> s.find('def',4,13)
4
>>>
>>> li=s.split(',')
>>> li
['abc', 'def', 'bcd', 'efg']
>>>
>>> sep=','
>>> s=sep.join(li)
>>> s
'abc,def,bcd,efg'
>>>
>>> table=str.maketrans('abcdefg','hijklmn')
>>> s='1234abcde'
>>> s2=s.translate(table)
>>> s2
'1234hijkl'
>>>
>>> x=' python abc '
>>> y=x.strip()
>>> y
'python abc'
>>>
>>>
>>> s=str(90.123)
>>> s
'90.123'
>>> x=float('12.3')
>>> x
12.3
  • lower
names=['abc', 'def','ghi','jkl']
name='Abc'

if name.lower() in names:
    print ('found')
else:
    print('not found')

Python Basic 7 : Function

在这里插入图片描述
在这里插入图片描述

  • circum
a=2
area_a=3.14*a*a
perim_a=3.14*a*2
print('area:',area_a)
print('perimeter:',perim_a)

b=3
area_b=3.14*b*b
perim_b=3.14*b*2
print('area:',area_b)
print('perimeter:',perim_b)

c=4
area_c=3.14*c*c
perim_c=3.14*c*2
print('area:',area_c)
print('perimeter:',perim_c)
  • circum2
def circle(r):
    area=3.14 *r*r
    perimeter=3.14*r*2
    print('r:', r, )
    print('area',area)
    print('perimeter', perimeter)

# main
circle(2)
circle(3)
circle(4)
  • max
def printMax(a,b):
    if a>b:
        print(a,"is Max")
    else:
        print(b,"is Max")

#main
printMax(2,3)
x=4
y=9
printMax(x,y)

在这里插入图片描述

  • None

  • funct1

def func(x):
    print('x: ',x)
    x=2
    print('changed x: ',x)

#main
x=50
func(x)
print('x in main:',x)

在这里插入图片描述

  • funct global
def func():
    global x
    print('x: ',x)
    x=2
    print('changed x: ',x)

#main
x=50
func()
print('x in main:',x)
  • func3
def func(a,b=5,c=10):
    print('a:',a, 'b:',b, 'c',c)
#main
func(3,7)
func(25, c=24)
func(c=50,a=20)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • funct4
def func(pb, *pa):
    print(pb)
    print(pa)
#main
func('hello',1,2,3)
func(1,2,3)
func(1,2)
func(1)
  • **
def func(a,b,c=4, *aa, **bb):
    print(a,b,c)
    print(aa)
    print(bb)

#main
func(1,2,3,4,5,5,5,6,6,6,xx='1',yy='2')
  • return
def func(a):
    s=0
    for x in a:
        s+=x
    return s
#main
t=[1,2,3]
print(func(t))
  • func7
def func(a,b,c):
    return a+b+c
def func2(a,b,c,d):
    return a+b+c+d

#main
tu=(1,2,3)
s=func(*tu)
print(s)

li=[1,2,3]
s=func2(9,*li)
print(s)
  • rectangle
def rect(x,y):
    area=x*y
    perim=2*(x+y)
    print('area:',area)
    print('perim:',perim)

#main
a=float(input('enter length:'))
b=float(input('enter width:'))
rect(a,b)
  • leap year
def run(x):
    if(x%4==0 ) or (x%400==0):
        print('leap year')
    else:
        print('not leap year')

#main
a=int(input('enter year:'))
run(a)
  • strStat
def strStat(str):
    a=0
    b=0
    c=0
    d=0
    for x in str:
        if x>='A' and x<='Z':
            a+=1
        elif x>='a' and x<='z':
            b+=1
        elif x>='0' and x<='9':
            c+=1
        else:
            d+=1
    return (a,b,c,d)

#main
s=input('string:')
a_tuple=strStat(s)
print('Capital letters:',a_tuple[0])
print('small letters:',a_tuple[1])
print('Numbers:',a_tuple[2])
print('Others:',a_tuple[3])

Python Basic 8 : File

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • write
#coding=gb2312
f=open('D:\\python1.txt','w')
f.write('name'+'\tsex'+'\tphone'+'\tcity')

flag=1
while flag==1:
    name=input('name:')
    sex=input('sex:')
    phone=input('phone:')
    city=input('city:')
    s='\n'+name+'\t'+sex+'\t'+phone+'\t'+city
    f.write(s)
    flag=int(input('enter 0 to quit or 1 to enter more:'))
f.close()

在这里插入图片描述

  • read
f=open('D:\\python1.txt','r')

while True:
    line=f.readline()
    if line=='':
        break
    print (line)
f.close()

在这里插入图片描述
在这里插入图片描述

  • one chinese char =2 length
  • file3
s='a1@中中\n'
f=open('D:\\python2.txt','w')
f.write(s)
f.seek(0,2)
length=f.tell()
f.close()
print('length',length)
  • read
f= open('D:\\python2.txt','r')

s=f.read(5)
f.close()
print('s=',s)
print('length=',len(s))
  • write
#coding=GBK
f= open('D:\\python2.txt','r+')
f.seek(5)
f.write('f')
f.seek(1)
f.write('f')
f.seek(0,2)
f.write('gggg')
f.close()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • struct
  • pack
#coding=UTF-8
import struct
n=1300000000
x=99.99
b=True
s='a1@中中'
byt = s.encode()
sn=struct.pack('if?',n,x,b)
f=open('D:\\python1.dat','wb')
f.write(sn)
f.write(byt)
f.close()
  • unpack
#coding=GBK
import struct
f=open('D:\\python1.dat','rb')
sn=f.read(9)

tu=struct.unpack('if?',sn)
print(tu)
a=tu[0]
b=tu[1]
c=tu[2]

print('a:',a)
print('b:',b)
print('c:',c)
s=f.read(9).decode()
f.close()
print(s)

在这里插入图片描述

  • pickle.dump
#coding=UTF-8
import pickle
f=open('D:\\python2.dat','wb')
n=7
i=120000
a=99.99
s='123abc中中'
lst=[[1,2,3],[3,4,5]]
tu=(-2,3,5)
coll={5,6,7}
dic={'a':'apple','b':'banana'}
try:
    pickle.dump(n,f)
    pickle.dump(i, f)
    pickle.dump(a, f)
    pickle.dump(s, f)
    pickle.dump(lst, f)
    pickle.dump(tu, f)
    pickle.dump(coll, f)
    pickle.dump(dic, f)
except:
    print('exception')
f.close()

  • pickle load
import pickle

f=open('D:\\python2.dat','rb')
n=pickle.load(f)
i=0
while i<n:
    x=pickle.load(f)
    print(x)
    i=i+1
f.close()

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • FileCopy
def FileCopy(tar_file, res_file):
    try:
        f=open(res_file,'rb')
        f2=open(tar_file,'wb')
    except:
        print('exception')
        return -1
    s=f.read()
    f2.write(s)
    f.close()
    f2.close()
    return 0
  • filecopy2
from fileCopy import FileCopy
FileCopy('D:\\python2.dat','D:\\python1.dat')
FileCopy('D:\\python2.txt','D:\\python1.txt')
  • file10.py
f=open('D:\\python3.txt','w')
s='>abcdefABCDEF12345!@#$% '
f.write(s)
f.close()

f=open('D:\\python3.txt','r')
nA=0
na=0
n0=0
nr=0
while True:
    x=f.read(1)
    if x==' ':
        break
    if x.isupper():
        nA=nA+1
    elif x.islower():
        na=na+1
    elif x.isdigit():
        n0=n0+1
    else:
        nr=nr+1
f.close()
print('nA:',nA)
print('na:',na)
print('n0:',n0)
print('nr:',nr)
  • shell
>>> s1='中'
>>> s1
'中'
>>> s2=s1.encode('GBK')
>>> s2
b'\xd6\xd0'

在这里插入图片描述

  • shell
>>>
>>> import os.path
>>> os.path.exists('D:\\python3.txt')
True
>>> os.path.exists('D:\\python4.txt')
False
>>> import os
>>> os.rename('D:\\python3.txt','D:\\python33.txt')
>>> os.path.exists('D:\\python33.txt')
True
>>>
>>>> p='D:\\python4.txt'
>>> os.path.dirname(p)
'D:\\'
>>> os.path.split(p)
('D:\\', 'python4.txt')
>>> p='D:\\test\\python4.txt'
>>> os.path.dirname(p)
'D:\\test'
>>> os.path.split(p)
('D:\\test', 'python4.txt')
>>> os.path.splitdrive(p)
('D:', '\\test\\python4.txt')
>>> os.path.splitext(p)
('D:\\test\\python4', '.txt')
>>>
>>> import shutil
>>> shutil.copyfile('D:\\python33.txt','D:\\python33_2.txt')
'D:\\python33_2.txt'

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • os1.py
import os, os.path
filename='D:\\python33_2.txt'
if os.path.exists(filename):
    os.remove(filename)
else:
    print('%s does not exist'%filename)
  • os2.py
import os,os.path
fname='python33.txt'
rname='python3.txt'

fList=os.listdir('.')
print(fList)
if fname in fList:
    while(rname in fList):
        choice=input('repeat, continue? Y/N')
        if choice in ('Y','y'):
            rname=input('enter new name:')
        else:
            break
    else:
        os.rename(fname,rname)
        print('success')
else:
    print('file does not exist')
  • os3.py
import os, os.path
f_list=os.listdir('.')
print(f_list)

for fname in f_list:
    name_list=os.path.splitext(fname)
    if name_list[1]=='.txt':
        newName=name_list[0]+'.html'
        os.rename(fname,newName)
        print(fname+' changed to : '+ newName)

在这里插入图片描述

  • python333.txt
>abcdefABCDEF12345!@#$% 
  • python444.txt
>abcefABCDF1235!@#%
  • ? ndiff does not work
import difflib
import sys

a=open('D:\\python333.txt','r').readlines()
b=open('D:\\python444.txt','r').readlines()

diff=difflib.ndiff(a,b)
sys.stdout.writelines(diff)


  • ERROR: AttributeError: module ‘difflib’ has no attribute ‘ndiff’
  • not solved…
  • works in shell
>>> import difflib
>>> a=open('D:\\python333.txt','r').readlines()
>>> b=open('D:\\python444.txt','r').readlines()
>>> difflib.ndiff(a,b)
<generator object Differ.compare at 0x03E633C0>
>>> diff=difflib.ndiff(a,b)
>>> diff
<generator object Differ.compare at 0x03E63D20>
>>> import sys
>>> sys.stdout.writelines(diff)
- >abcdefABCDEF12345!@#$% ?     -      -    -    - -
+ >abcefABCDF1235!@#%>>>
>>>

在这里插入图片描述

  • shell
>>> os.listdir('D://')
['$RECYCLE.BIN',
...
 '迅雷下载']
>>> os.mkdir('D://pythonTest')
>>> os.listdir('D://')
['$RECYCLE.BIN', ...
 'pythonTest'...
  '迅雷下载']
>>> os.mkdir('D://pythonTest/Test1_1')
>>> os.listdir('D://pythonTest/')
['Test1_1']
>>> os.rmdir('D://pythonTest//Test1_1')
>>> os.listdir('D://pythonTest/')
[]

在这里插入图片描述

  • VisitDir.py
#coding=utf-8

import os


def visitDir1(path):
    for lists in os.listdir(path):
        sub_path=os.path.join(path,lists)
        print(sub_path)

        if os.path.isdir(sub_path):
            visitDir1(sub_path)

def visitDir2(path):
    list_dirs=os.walk(path)
    for root,dirs, files, in list_dirs:
        for d in dirs:
            print(os.path.join(root,d))
        for f in files:
            print(os.path.join(root,f))


if __name__=='__main__':
    print('#################call visitDir1')
    visitDir1("C:/Users/Administrator/PycharmProjects/test1")

    print('#################call visitDir2')
    visitDir2("C:/Users/Administrator/PycharmProjects/test1")

在这里插入图片描述

  • !? os.path.walk does not work

Python Basic 9 : OOP

在这里插入图片描述

class Triangle:
    def __init__(self,x,y,z):
        self.a=x
        self.b=y
        self.c=z

    def area(self):
        s=(self.a+self.b+self.c)/2
        return ((s*(s-self.a)*(s-self.b)*(s-self.c))**(1/2))

    def perim(self):
        return self.a+self.b+self.c

if __name__ == "__main__":
    t1=Triangle(6,6,6)
    t2=Triangle(3,4,5)

    print('triangle1:',t1.a,t1.b,t1.c)
    print('triangle1 perim:',t1.perim())
    print('triangle1 area',t1.area())

    print('triangle2:', t2.a, t2.b,t2.c)
    print('triangle2 perim:', t2.perim())
    print('triangle2 area', t2.area())

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • car
class Car:
    price=2000000
    def __init__(self,c):
        self.color=c

if __name__ =='__main__':
    car1=Car('red')
    car2=Car('blue')

    print (car1.color,Car.price)
    Car.price=1500000
    Car.name='Bugatti'

    car1.color='yellow'
    print(car2.color,Car.price,Car.name)
    print(car1.color,Car.price,Car.name)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • fruit.py
class Fruit:
    def __init__(self):
        self.__color='red'
        self.price=2

if __name__ == '__main__':
    apple=Fruit()
    apple.price=3

    print(apple.price,apple._Fruit__color)

    apple._Fruit__color='green'
    print(apple.price,apple._Fruit__color)

    peach=Fruit()
    print(peach.price,peach._Fruit__color)
  • fruit2.py
class Fruit:
    price=0
    def __init__(self):
        self.__color='red'
        self.__city='brazil'

    def __outputColor(self): #private method
        print(self.__color)

    def __outputCity(self):
        print(self.__city)

    def output(self):
        self.__outputCity()
        self.__outputColor()

    @ staticmethod
    def getPrice():
        return Fruit.price

    @ staticmethod
    def setPrice(p):
        Fruit.price=p

if __name__ =='__main__':
    apple=Fruit()
    apple.output()
    print(Fruit.getPrice())
    Fruit.setPrice(8)
    print(Fruit.getPrice())
  • instance
  • demo.py
class Demo:
    def hello(self):
        print('hello world')

if __name__ == '__main__':
    Instance1=Demo()

    def hello2(self):
        print ('hello again')

    Demo.hello2=hello2
    Instance1.hello()
    Instance1.hello2()

    @ staticmethod
    def hello3():
        print("hello again !")

    Demo.hello3=hello3
    Demo.hello3()

在这里插入图片描述

  • vector1.py
  • problem with division and multiplication
#coding=utf-8

import math

class Vector2(object):


    def __init__(self, x=0.0, y=0.0):
        (self.x, self.y) = (x, y)

    def __getitem__(self, item):
        if item == 0:
            return self.x
        if item == 1:
            return self.y

    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)

    def get_len(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

    def normalize(self):
        magnitude = self.get_len()
        self.x /= magnitude
        self.y /= magnitude

    def __add__(self, other):
        third = Vector2()
        third.x = self.x + other.x
        third.y = self.y + other.y
        return third

    def __sub__(self, other):
        third = Vector2()
        third.x = self.x - other.x
        third.y = self.y - other.y
        return third

    def __mul__(self, other):
        return Vector2(other * self.x, other *self.y)

    def __divmod__(self, other):
        if other != 0:
            return Vector2(self.x/other, self.y/other)
        else:
            return Vector2(self.x, self.y)

    def getpos(self):
        return (self.x, self.y)
  • vector2.py
from vector1 import Vector2

v1=Vector2(1.0,2.0)
v2=Vector2(3.0,4.0)
v3=v1+v2
v4=divmod(v1,3)

print(v1)
print(v2)
print(v3)
print(v4)
t=v4-v3
t=t.getpos()
print(t[0],t[1])
  • inheritance
  • person.py
class Person(object):
    sex='male'
    def __init__(self,s1,s2):
        self.IDcard=s1
        self.name=s2
        print('__init')

    def hello(self,friend):
        print('hello,',friend)

class Student(Person):
    def __init__(self,num):
        self.number=num

    def func(self):
        print(self.IDcard,self.name,self.number,Student.sex)

class Teacher(Person):
    def __init__(self,t,s1,s2):
        self.title=t
        super(Teacher, self).__init__(s1,s2)
    def func(self):
        print(self.IDcard, self.name,self.title,Teacher.sex)

if __name__=='__main__':
    stud1=Student('12345')
    stud1.IDcard='1111111'
    stud1.name='Bob'
    stud1.func()
    stud1.hello('Sam')

    teacher1=Teacher('compSci','33333333','Patti')
    Teacher.sex='female'
    teacher1.func()
    teacher1.hello('Bob')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值