Python学习(第二章)

一、 变量

1. type(变量名)  可以查看该变量的类型

2. 关于字符串的两个运算符 +* ,分别执行 拼接 和 重复 操作

3. 格式化输出

%s 字符串
%d 整型 (%06d 保留六位前面补0)
%f 浮点数 (%.2f 保留小数点后2位)
%% 百分号%
name = '小明'
print('我的名字叫%s,请多多关照!'%name)

student_no = 100
print('我的学号是%06d'%student_no)

price = 8.5
weight = 7.5
money = price * weight
print('苹果单价%.2f元/斤,购买了%.3f斤,需要支付%.4f元,'% (price,weight,money))
#定义一个小数scale。输出是数据比例是10.00%
scale = 0.25
print('数据比例是%.2f%%'%(100*scale))
-----------------------------------------

我的名字叫小明,请多多关照!
我的学号是000100
苹果单价8.50元/斤,购买了7.500斤,需要支付63.7500元,
数据比例是25.00%

4. 变量命名:字母、数字、下划线 数字不可以开头, 不能与关键字重名

# 查看Python的关键字列表
import keyword
print(keyword.kwlist)
--------------------------------------
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

5. 三个逻辑运算符:and、or、no

二、 随机数的处理

1. 导入随机数模块

import random

2. 在IPython中直接在模块名后面加一个 . 再按Tab键会提示包中的所有函数

image

3. 例如

random.randint(a, b),返回[a, b]之间的整数,包含a, b

三、while语句基本用法

1. 指定次数执行: while + 计数器  (在while开始之间初始化计数器 i = 0)

2. continue 不会执行本次循环中 continue 之后的部分,注意:避免死循环,在coninue条件(if)里面再写一遍计数器 i = i+1

i = 0
result = 0
while i<5:
    if i ==3:
        i = i+1
        continue
    print(i)
    i = i+1
print('循环结束后i=',i)
---------------------------------------------------

0
1
2
4
循环结束后i= 5

四、 print知识点

print()输出内容时,会默认在输出的内容后面加上一个 换行

如果不希望有换行,可以在后面增加 ,end=””

print('*')
print('*')

print('*',end='')
print('*')

print('*',end='---')
print('*')
---------------------------------------------------

*
*
**
*---*

取消这种格式的方法,再加一个print(“”)

print('*',end='')
print('') # 此时换行会加上
print("123")
---------------------------------------------------

*
123

猜你喜欢

转载自www.cnblogs.com/btschang/p/9383703.html