1.for重新实现:1+2+3…+100=?
运行结果:
Python代码:
点击(此处)折叠或打开
- #use for to compute 1+2+3+...+100
- final=0
- for i in range(1,101):
- final=final+i
- print '1+2+3+...+100 =',final
释义:
range(1, 101)表示从1开始,到101为止(不包括101),取其中所有的整数。
相比昨天的while,这里不再需要一个单独变量记录循环的次数。
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
2. 字符串格式化输出
运行结果:
代码:
点击(此处)折叠或打开
- from random import randint
- num=randint(1,100)
- print 'Guess what I think?'
- final=False
-
- while final==False:
- answer=input()
-
- if answer<num:
- print '%d is too small!'%answer
- if answer>num:
- print str(answer)+' is too big!'
- if answer==num:
- print "Good, you guess it! It's %d."%answer
- final=True
两种格式化方法:
1) str():把数字转换成字符串
2) 用%对字符串进行格式化:
%d替换整数;
%f替换小数(想保留两位小数, %.2f);
%s来替换一段字符串
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
补个基础知识:字符串的用法
运行结果:
代码:
点击(此处)折叠或打开
- print 'Method 1;',"Yiyi's mom."
- print 'Method 1:','Yiyi is a "good" baby.'
- print 'Method 2:','''"What's your name?" "I'm Yiyi."'''
- print 'Method 2:', """"And you?" "I'm Iris." """
- print 'Method 3:','I\'m a \"good\" baby.'
- print 'Method 3:','This is \
- same line.'
知识点:
最常用的字符串表示方式是单引号(‘’)和双引号(“”):’string’和”string”效果一样
一定必须得是英文字符!
输出中本身有单双引号,咋办?见上栗,能看出有3种方法不?
Question: ‘\n’用来做什么呢?
点击(此处)折叠或打开
- print 'Well study,\nwell think,\nwell listen,\n\
- well do,\nwell speak\n --come on!'
- print '^_^ @_@ *_* '
结果:
程序运行版本:
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
刚开始运营的微信公众号,欢迎拍砖,欢迎交流~~
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26129555/viewspace-2142637/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26129555/viewspace-2142637/