Help on method_descriptor:
str.find()。find是str类的一个函数
找不到返回的是-1
另外python的string 类型是关键字是“str”
-
not关键字
>>> a=10>>> b=9>>>> if not a<b: print("Hello World")Hello Worldnot相当于其他语言里面的!
三 for 循环 一般for循环语法
for iter_var in iterable: suite_to_repeat3.1用于序列类型 如下代码返回的字符串的每个字符。对iterable执行迭代
>>> for eachLetter in 'Names': print ('curren letter:',eachLetter)curren letter: Ncurren letter: acurren letter: mcurren letter: ecurren letter: s3.1.1通过序列项迭代
>>> nameList=['walter','nicole','steve','henry']>>> for eachName in nameList: print(eachName)walternicolestevehenry3.1.2用序列索引迭代 C++,java属性的方式
>>> nameList=['walter','nicole','steve','henry']>>> for index in range(len(nameList)): print(nameList[index])walternicolestevehenry3.1.3使用项和索引迭代
class enumerate(object) | enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that supports | iteration. The enumerate object yields pairs containing a count (from | start, which defaults to zero) and a value yielded by the iterable argument. | enumerate is useful for obtaining an indexed list: | (0, seq[0]), (1, seq[1]), (2, seq[2]), ...使用enumerate()函数
>>> for index,each_name in enumerate(nameList): print ("%d %s Lee"%(index+1,each_name))1 walter Lee2 nicole Lee3 steve Lee4 henry Leeprint在3.0 才加的外扩号。 在3.0里面 xrange被去掉。并且range返回的不再是一个list而是一个range object
由于python没有大括号,有些需要用大括号来结束的地方。如果没写语言解释器会报语法错误,于是pass 就来填充这种情况。
在循环中使用else语句时,else子句只在循环完成后执行,也就是说break语句会跳过else块。
对比代码~ python 求最大约数。先对num进行折半,得到count。然后取num与count的余数,当count>1并且取余为0是,此时的count即为最大公约数。
这里的代码,else在每次执行完循环;也就当count<=1时,执行。
def showMaxFactor(num): count=int(num/2) while count>1: if num % count == 0: print('the lagest factor of %d is %d'%(num,count)) break count-=1 else: print(num,"is prime")for eachNum in range(10,21): showMaxFactor(eachNum)#这里有个点 关于python的/运算符>>> 10/25.0>>> 11/25.5>>> 10%50>>> 11%5.50.0#可以看到返回的时候一个浮点类型,而取余运算根据参与运算的类型来判断返回类型 #这里要做转换>>> int(11/2)5再来看没有while else的C++代码
void showMaxFactor(int num){ int count = num/2; while(count>1){ if(num%count==0){ printf("the lagest factor of %d is %d /n",num,count); break; } else{ count--; } }//python简化了代码,在结构上减少了一次判断,并使程序的逻辑变的清晰。 if(count<=1){ printf("%d is prime/n",num); }}int main(int argc, char** argv) { for(int i=10;i<21;i++){ showMaxFactor(i); } showMaxFactor(2); return 0;}以上代码输出结果均为:
try……expect在语法细节上与2.X也有些变化。暂且不表 这段代码要补充的就是文件读写关操作。
新闻热点
疑难解答