python基本数据类型与循环语句

输入与输出
• print + 字符串...

• raw_input输入的内容为字符类型;

input输入的内容为数值类型

练习:
写一程序,录入信息包括hostname、IP、used_year、CPU、Memory、manager_name,如果使用年限超过10年,直接显示警告信息“该服务器使用年限太久!”,如果使用年限不超过10年,显示该服务器信息如下面的格式如下:
        主机信息
主机名: hostname
IP:IP
使用年限:used_year
CPU:CPU

Memory:Memory

运行结果:


字符串的格式化符号:


 %f                                             ###小数, 浮点数
 %.2f                                           ###保留两位小数点的浮点数
 %d                                             ###整形数
 %s                                             ###字符串 
 %o                                             ###八进制
 %x                                             ###十六进制
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6


布尔型变量:True(1) False(0)

运算符号:
 =                                           ###赋值
 +=                                          ###a+=2等于a=a+2
 -=                                          ###a-=2a=a-2
 /=                                          ###a/=2等于a=a/2(取整)
 *=                                          ###a*=2等于a=a*2
 %=                                          ###a%=2等于a=a%2(求余)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
关系运算符:>,>=,<,<=

运算后将会返回一个布尔值

 1>2
 out:False
 (1>2) == False
 out:True
  • 1
  • 2
  • 3
  • 4

逻辑运算符:and or not

判断是否为闰年:

 Year = input("please input year: ")
 a = ((Year % 4 == 0) and (Year % 100 != 0)) or (Year % 400 == 0)
 if a:
     #pass 是占位关键字
     print "%s 是闰年" %(Year)
 else:
     print "%s 不是闰年" %(Year)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

if语句


注意缩进(每个4个空格)

    if 表达式:
        if-suite
    if 表达式:
        if-suite
    else:
        else-suite 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

判断输入用户名密码是否正确:

 Username="root"
 Passwd="dream"
 Username = raw_input("username: ")
 Passwd = raw_input("password: ")
 if (Username == "root") and (Passwd == "dream"):
     print "welcom!!!"
 else:
     print "username and passwd is not correctly!!!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

运行结果;

石头剪刀布小游戏:

运行结果:

while语句

while 表达式:
     循环执行的语句

 while 表达式:
     循环执行的语句
 else:
     不符合循环条件执行的语句


 死循环:
 while True:
     死循环的语句

 while 1:
     死循环的语句

举例:打印九九乘法表:

运行结果:


for循环语句

有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

运行结果:



break,continue,exit的区别

continue:

 for i in range(5):
     if i == 3:
         continue
     print i
 print "guodong"
 结果:
 0
 1
 2
 4
 guodong
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

break:

 for i in range(5):
     if i == 3:
         break
     print i
 print "guodong"
 结果:
 0
 1
 2
 guodong
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

exit:

 for i in range(5):
     if i == 3:
         exit()
     print i
 结果:
 0
 1
 2

猜你喜欢

转载自blog.csdn.net/gd0306/article/details/81031400