Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5673
  • 博文数量: 3
  • 博客积分: 1465
  • 博客等级: 上尉
  • 技术积分: 40
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-14 17:02
文章分类

全部博文(3)

文章存档

2011年(1)

2010年(2)

我的朋友
最近访客

分类: LINUX

2010-08-19 10:57:51

今天学习if语句和其他语言也没有其他区别,唯一需要提出的是用到 raw_input 函数,在调用该函数的过程中要注意函数的类型,例如int等
eg.
#!/usr/bin/python
# Filename: if.py

number = 23
guess = int(raw_input('Enter an integer : '))

if guess == number:
    print 'Congratulations, you guessed it.' # New block starts here
    print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
    print 'No, it is a little higher than that' # Another block
    # You can do whatever you want in a block ...
else:
    print 'No, it is a little lower than that'
    # you must have guess > number to reach here

print 'Done'

运行结果:

[root@www jerry]# python if.py
Enter an integer : a
Traceback (most recent call last):
  File "for.py", line 5, in ?
    guess = int(raw_input('Enter an integer : '))
ValueError: invalid literal for int(): a
[root@www jerry]# python if.py
Enter an integer : 12
No, it is a little higher than that
Done
[root@www jerry]# python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done
[root@www jerry]# python if.py
Enter an integer : 24
No, it is a little lower than that
Done
[root@www jerry]#

但是如果去掉类型int呢?

guess = int(raw_input('Enter an integer : ')) 改成guess = raw_input('Enter an integer : ')

运行结果:

[root@www jerry]# python if.py
Enter an integer : a
No, it is a little lower than that
Done
[root@www jerry]#

PS:在Python中没有switch语句。你可以使用if..elif..else语句来完成同样的工作

阅读(543) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:python 学习 二

给主人留下些什么吧!~~