1. 用户交互
鉴于本小节十分的基础,变不多做赘述啦!
1.1 输出第一个程序:“Hello World !”
1.2 输出字符串,重点是去除字符串中的前后的空格,使用strip()
代码如下:
# !/usr/bin/ python
# -*- coding:utf-8 -*-
print("Hello world!") name = raw_input("name:").strip() # 移除空格
age = raw_input("age:")
job = raw_input("job:").strip() msg = '''
information of : %s
Name:%s
Age:%s
Job:%s
'''%(name,name,age,job)
print(msg)
运行结果如下:
Hello world!
name:alex
age:33
job:it information of : alex
Name:alex
Age:33
Job:it
是不是so easy? OK,let's move on !
2. 条件判断与缩进
2.1 if 条件判断
if和while语句可以单独使用,也可以嵌套使用
句法:
if.......//此处是条件一
elif......//此处是条件二
else......//此处是其他情况
写个小游戏,来展示下判断语句的功力:
这个游戏是干嘛的呢?简单,猜数的!
限定猜的次数,并且有提示
# !/usr/bin/python
# -*- coding:utf-8 -*- Lucky_num=3
input_num=0
guess_count =0
while guess_count<3:
input_num = int(input("Lucky Num :"))
print("guess count :",guess_count)
if (input_num < Lucky_num):
print("Bigger than that !")
elif (input_num > Lucky_num):
print ("Lower than that !")
else:
print(" Bingo!")
break
guess_count +=1
else:
print("Game Over!")
运行结果:
Lucky Num :3
('guess count :', 0)
Bigger than that !
Lucky Num :78
('guess count :', 1)
Lower than that !
Lucky Num :33
('guess count :', 2)
Bingo!
OK,进入下一小节!
3.循环控制
3.1 while循环控制
语法格式是:
while 表达式:
........
3.2for循环
for循环用于遍历一个集合,语法格式是:
for 元素 in 集合
下面来改编下小游戏的程序,查看下区别吧:
# !/usr/bin/python
# -*- coding:utf-8 -*-
Lucky_num=3
input_num=0 for i in range(3):
input_num = int(input("Lucky Num :"))
print("guess count :",i)
if (input_num < Lucky_num):
print("Bigger than that !")
elif (input_num > Lucky_num):
print ("Lower than that !")
else:
print(" Bingo!")
break else:
print("Game Over!")
是不是感觉清爽很多?O(∩_∩)O~