2-1
>>> name = 'my name is ahwho ?'
>>> name
'my name is ahwho ?'
>>> print name
my name is ahwho ?
- name 输出的是 该对象的字符串表示形式
- print name 输出的是 name 的字符串的值
- 以name形式输出是为了非字符串也可以以字符串形式输出
>>> print '%s%s' % ('adc',123)
adc123
>>> print '%s+%s' % ('adc',123)
adc+123
>>> print '%s+%s' % ('adc',123*4)
adc+492
>>> print '%s+%s' % ('adc','123'*4)
adc+123123123123
2-2
- a) 做数字运算
- b) 输出结果 9
- c) 没有输出结果
- d) 单独执行,没有输出结果,交互解释器中输出结果为9
- e) 如果想在程序中输出9,需要有输出语句print
2-3
>>> u = 12
>>> i = 2.6534
>>> u - i
9.3466
>>> u + i
14.6534
>>> u * i
31.8408
>>> u / i
4.522499434687571
>>> u % i
1.3864
>>> u ** i
730.2970027975604
<b><i>注意: u % i 结果也是浮点数</i></b>
2-4
__author__ = 'Yuriy'
name = raw_input('what\'s your name ?\nplease input:>>>')
print 'my name is %s' % name
results:
what's your name ?
please input:>>>black
my name is black
name = raw_input('please input a number')
print 'the num is %d' % int(name)
print type(int(name))
results:
please input a number24
the num is 24
<type 'int'>
2-5
n = 0
while(n<=10):
print n, n += 1
0 1 2 3 4 5 6 7 8 9 10
num = [ x for x in range(11)]
i = 0
for i in num:
print num[i],
i += 1
0 1 2 3 4 5 6 7 8 9 10
2-6
num = int(raw_input("please input a num:\n"))
if num > 0:
print 'positive num'
elif num < 0:
print 'negative num'
else:
print 'the num is 0'
2-7
myStr = raw_input("please input a num:\n")
i = 0
while i< len(myStr):
print myStr[i],
i += 1
please input a num:
it's my tiem
i t ' s m y t i e m
myStr = raw_input("please input a num:\n")
i = 0
for i in range(len(myStr)):
print myStr[i],
i += 1
please input a num:
it's my time to do something
i t ' s m y t i m e t o d o s o m e t h i n g
2-8
li = []
while True:
ch = raw_input(">>>")
if ch == 'end':
break
elif ch == 'help':
print 'Enter \'end\' to finish the input'
elif ch.isdigit():
li.append(ch)
else:
print 'Please input numbers!'
print li
i = 0
values = 0
for i in range(len(li)):
values += int(li[i])
i += 1
print values
>>>adc
Please input numbers!
>>>21
>>>34
>>>22
>>>12356
>>>bda
Please input numbers!
>>>BAT
Please input numbers!
>>>END
Please input numbers!
>>>end
['21', '34', '22', '12356']
12433
__author__ = 'Yuriy'
# -*- coding : utf-8 -*-
li = []while True:
ch = raw_input(">>>")
if ch == 'end':
break
elif ch == 'help':
print 'Enter \'end\' to finish the input'
elif ch.isdigit():
li.append(ch)
else:
print 'Please input numbers!'
print li
i = 0
values = 0
while i < len(li):
values += int(li[i])
i += 1print values,
>>>20
>>>18
>>>21
>>>df
Please input numbers!
>>>end
['20', '18', '21']
59