Python基本数据类型及循环语句

字符串的格式化符号:


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

注意:

 a=001
 print "%.3d" %(a)                               ###输出为001

"%4.3d" %1                                       ###4:字符总占有的宽度,3:补充为0
' 001'

['130%.3d'%(i) for i in range(1,30)]             ###前面加上130
'130001',
'130002',

mem_percent=0.3
"%.2f%%" %(mem_percent)                           ###第3个%是转义后面的%
'0.30%'

数据内型


整形:

 anInt = 12
 print type(anInt)
 结果:
 <type 'int'>

长整形:

 aLong = 12l
 aLong = 12L
 print type(aLong)

 print type(anInt + aLong)                      ###整形和长整形相加,得到为长整形
 结果:
 <type 'int'>
 <type 'long'>
 <type 'long'>

Float类似C语言的double内型:

 aFloat = 3.14
 print type(aFloat)
 结果:
 <type 'float'>
 指数Float
 bFloat = 1.2e10
 bFloat = 1.2E10
 print bFloat
 结果:
 12000000000.0

复数:

aComplex = 2+3j
print aComplex.real                             ###实部
print aComplex.imag                             ###虚部
print aComplex.conjugate()                      ###共轭复数
print type(aComplex)
结果:
2.0
3.0
(2-3j)
<type 'complex'>

数值类型是不可变的

 a=1
 b=1
 print id(a),id(b)
 结果:
 15039592 15039592

我们不难可以发现pyhton的内存分配机制,数值相同时会指向同一个地址,当改变数值的时候,将会重新分配一个内存地址,不会在原有内存地址中修改数值

删除数字对象


 c=1
 print c
 结果:
 1

 del c
 print c
 结果:
 NameError: name 'c' is not defined

布尔型变量: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
 out:False
 (1>2) == False
 out:True

逻辑运算符: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)

if语句


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

    if 表达式:
        if-suite
    if 表达式:
        if-suite
    else:
        else-suite 
判断输入用户名密码是否正确:
 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!!!"
ATM 管理 :

注意:由于加入了getpass来隐藏密码,但是此不能在pycharm中运行,我们可以在shell中运行此脚本

 import getpass
 Username = raw_input("username: ")
 Passwd = getpass.getpass("password: ")
 if (Username == "root") and (Passwd == "redhat"):
     print """                              ATM admin systemc
                        1.get money
                        2.save money
                        3.check balances
                        4.quit
    """
     while True:
         choice = input("please input your choice:")
         if choice == 1:
             pass
         elif choice == 2:
             pass
         elif choice == 3:
             pass
         elif choice == 4:
             exit(0)
         else:
             print "please input again!!!"
 else:
     print "username and passwd is not correctly!!!"

while循环语句


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

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


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

 while 1:
     死循环的语句
登陆三次自动退出:
 trycount = 0
 while trycount < 3:
     print "登陆…………"
     trycount += 1
 else:
     print "登陆次数超过3次,请稍后再试!!"

for循环


求和1000偶数
 import time
 start_time=time.time()
 sum=0
 for i in range(2,1001,2):                      ###range类似于shell的seq命令,这里是2到1001,每隔1位显示(2,4,6...1000)
     sum+=i
 print sum
 end_time=time.time()
 print "%s " %(end_time)
用内置库函数sum:
 import time
 start_time=time.time()
 print sum(range(2,1001,2))
 end_time=time.time()
 print "%s " %(end_time)

continue和break和exit的区别:


continue:

 for i in range(5):
     if i == 3:
         continue
     print i
 print "dream"
 结果:
 0
 1
 2
 4
 dream

break:

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

exit:

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

从中我们不难可以看出continue是遇到这个关键字跳出本次循环;而break是遇到这个关键字跳出当前循环;不再继续执行循环;exit是直接结束

Test


1.变量赋值:

(1)赋值语句 x, y, z = 1, 2, 3 会在 x、y、z 中分别赋什么值?
答:123
(2).执行 z, x, y = y, z, x 后,x、y、z 中分别含有什么值?
答:312

2.带循环和条件判断的给定一个数值num, 用户输入使用raw_input()函数来提示用户输入一个1和100之间的数,如果用户输入的数等于num, 显示成功并退出。否则显示一个错误信息然后再次提示用户输入数值,直到满足条件为止。

 #!/usr/bin/env python
 num = 10
 while True:
     num_input = input("please input num 1~100:")
     if num_input == num:
         print "input correct!"
         break
     else:
         print "input error!"

3. (if..elif..elif..else考察, 循环语句的考察)

带文本菜单的程序写一个带文本菜单的程序,菜单项如下
(1) 取五个数的和
(2) 取五个数的平均 值

(X)退出。(exit())

由用户做一个选择,然后执行相应的功能.当用户选择退出时程序结束。这个程序的有用之处在于用户在功能之间切换不需要一遍一遍的重新启动你的脚本。

 #!/usr/bin/env python
 from __future__ import division
 Num1 = input("please input num1:")
 Num2 = input("please input num2:")
 Num3 = input("please input num3:")
 Num4 = input("please input num4:")
 Num5 = input("please input num5:")
 while True:
     print """
                     Calculate
             1.add
             2.sub
             3.mul
             4.avg
             5.exit
     """
     Action = input("please input Action:")
     if Action == 1:
         print "sum:%.2f" %(Num1+Num2+Num3+Num4+Num5)
     elif Action == 2:
         print "sub:%.2f" %(Num1-Num2-Num3-Num4-Num5)
     elif Action == 3:
         print "mul:%.2f" %(Num1*Num2*Num3*Num4*Num5)
     elif Action == 4:
         print "div:%.2f" %((Num1+Num2+Num3+Num4+Num5)/5)
     elif Action == 5:
         exit()
     else:
         print "ERROR:input error,please input again!"

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

 #!/usr/bin/env python
 Times = 0
 for a in range(1,5):
     for b in range(1,5):
         for c in range(1,5):
             if (a != b) and (b != c) and (a !=c):
                 print("%d%d%d") %(a,b,c)
                 Times+=1
 print "the sum is:%.f" %(Times)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wielun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值