python学习记录(第六天)
时间:2010-11-11 来源:simonchia
一个简单的交互式循环:
>>> while True:
... reply=raw_input('Enter text:')
... if reply=='stop': break
... print reply.upper()
...
Enter text:fsdjkl
FSDJKL
Enter text:open
OPEN
Enter text:stop
对用户输入数据做数学运算
#!/usr/bin/env python
while True:
reply=raw_input('Enter text:')
if reply=='stop': break
print int(reply) ** 2
print 'Bye'
这个必须写在脚本里面~~否则运行不成功~!
用测试输入数据来处理错误
#!/usr/bin/env python
while True:
reply=raw_input('Enter Text:')
if reply=='stop': break
elif not reply.isdigit():
print 'Bad!' * 8
else:
print int(reply) ** 2
print 'Bye'
用try语句处理错误
#!/usr/bin/env python
while True:
reply=raw_input('Enter Text:')
if reply=='stop': break
try:
num=int(reply)
except:
print 'Bad!'*8
else:
print int(reply)**2
print 'Bye'
嵌套代码三层
#!/usr/bin/env python
while True:
reply=raw_input('Enter Text:')
if reply=='stop': break
elif not reply.isdigit():
print 'Bad!'*8
else:
num=int(reply)
if num < 20:
print 'low'
else:
print num**2
print 'Bye'
相关阅读 更多 +