Python Note 006--function

Source: Internet
Author: User

Function basics

Count the number of characters in a string

1 def countsubstring (s,ch): #s和ch为形参2C=03I=04      whilei<Len (s):5         ifs[i]==Ch:6c + =17i + =18 print (c)9Str='WUJIADONGJIANGRUISUIRSUIUIGJSJSIUISLDJSJEUIUI'Tenm= ' I ' OneCountsubstring (s,m) #调用函数传入的参数str和m为实参

Count Sub-string sub-number

1 def countsubstring (s,sub):2C=03I=04      whileI<=len (s)-Len (sub):5         ifS[i:i+len (sub)]==Sub:6c + =17# Print (s[i:i+len (sub)])8i + =19 print (c)TenStr='WUJIADONGJIANGRUISUIRSUIUIGJSJSIUISLDJSJEUIUI' One  ACountsubstring (str,'UI')

1 def myfind (s,sub):2I=03      whileI<=len (s)-Len (sub):4         ifS[i:i+len (sub)]==Sub:5 print (i)6              Break7i + =18     Else:9Print'-1')Ten  OneStr='Wujiadong' Asub=' on' -Myfind (Str,sub)

Find the maximum value

1li=[111,2,3,7,9, the,98, at, $]2 def Myfindmax (M):3I=04max=li[0]5      whilei<Len (LI):6         ifmax<Li[i]:7max=Li[i]8 9i + =1Ten print (max) OneMyfindmax (LI)

Find the second largest value

#这种情况两个最大都相等时是错误的
1li=[111,222,333,7,9,765,98, at, $]2 def max2 (t):3max1=t[0]4max2=t[0]5 forXinchT:6 ifX >Max1:7Max2=Max18max1=x9 Else:Ten ifX >MAX2: #这里添加上条件x! =max1 can be avoided OneMax2=x APrint'Max1', Max1) -Print'Max2', MAX2) -Max2 (LI)

Delete a value

#有bug, there are duplicate values that cannot be deleted

1li=[1,2,3,4,5,6,7,8,9]2 def delvalue (t):3 GlobalLi #没懂为什么一定要加这个4I=05 whilei<Len (LI):6 ifli[i]==T:7left=Li[:i]8 print (left)9right=li[i+1:]Ten # Print (i) Oneli=left+ Right Ai + =1 - -Delvalue (6)

Delete all the values

Python Note 006--function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.