【Python3学习笔记】week1.基础语法,对象与类型,循环语句,文件读取

# print
print()  # =print(end = "\n")
print(end="")  # 去掉换行
print("\n")  # 两个换行
print("a\tb")  # 转义字符,中间空格
print("hellow world", 10 * 10)  # 两个部分连接
# 使用变量
str1 = 'helow world'
print(str1)
print(f"ray:{str1}")  # format 采用print(f"{变量}")形式
print("format:{} {}".format("hellow", "world"))
# 三引号应用场景:函数注释或者多行参数
str2 = '''
hellow
comp9021
'''
print(str2)
#input
print(input("what do you want to print?"))

# 空白:
print("制表符:\t")
print("空格: ")
print("换行符:\n")

#type
'''
types:
Integer (int). A whole number, positive or negative, including zero (i.e. ..., -2, -1, 0, 1, 2, ...).
Floating-point number (float). A positive or negative number, not necessarily whole, including zero (e.g. 3.14, -0.12, 89.56473).
String (str). A sequence of characters (e.g. 'Hello', 'we34t&2*').  Used to store text.
Boolean (bool). A truth value, either true or false.
List (list). An ordered container of objects.
Tuple (tuple). An immutable list (i.e. one that cannot be changed).
Set (set). An unordered container of unique objects.
Dictionary (dict). A set of key-object pairs.
Function. A piece of code that can be run by calling it.
Class. A user-defined type of object.
'''
#查询类型
print(type(1))
print(type(3.14))
print(type('Hello'))
print(type(None))
print(type(print))
#验证类型
print(isinstance(1, int)) # True
print(isinstance(1, float)) # False
print(isinstance(3.14, float)) # True
print(isinstance(3.14, int)) # False
print(isinstance('Hello', str)) # True
print(isinstance('Hello', float)) # False
#attributes/methods
print("hellow".upper())

#同时赋值
a,b = "hellow" , "world"
print(a,b)

#类型转换
#int(), float(), str(), bool(), list(), tuple(), set(), and dict()
print(1)
print(float(1))#转换为浮点数
#将input进行类型转换(默认str)
# number will be a string:
number = input('Enter a number: ')
print(number, type(number))
# number will be an integer:
number = int(input('Enter a number: '))
print(number, type(number))
# number will be a float:
number = float(input('Enter a number: '))
print(number, type(number))
#int转换浮点数会直接去掉小数位
print(1.2)
#命名规范:不变量全大写,变量小写

# 整数运算
print(100 + 3)
print(100 - 3)
print(100 * 3)
print(100 / 3)
print(100 % 3)
print(100 // 3)  # 整除
print(100 ** 3)  # 乘方
print(100 ** 0.5)  # 开方
# 内置函数
print(abs(-10))  # 取绝对值
print(divmod(100, 33))  # 求除数和余数
print(bin(111))  # 求二进制 binary
print(int(0.9))  # 取整数位
print(int(1.9))
print(int(bin(111), 2))  # 求十进制
#浮点数
#精确到小数点位数
print(round(0.1 + 0.2, 1))
print(round(0.3, 1))
print(round(0.1 + 0.2, 1) == round(0.3, 1))
#取整保留向偶数的一边(python3)(2保留到离0远的一端)
print(round(4.5,0))
print(round(5.5,0))
print(round(-4.5,0))
print(round(-5.5,0))
#数值函数
print(int('3') + float('2.0')) # Convert strings to numbers and add them
print(abs(-5)) # Absolute value of -5
print(pow(2, 4)) # 2 to the power of 4.  This is the same as **
print(round(3.567, 2)) # Round 3.567 to 2 decimal places
# bool
print(True == 1, False == 0)
print(True == 0, False == 1)
print(True + 1, False + 1)

# 字符串
a = 'hellow'
b = 'python'  # 定义
print(a + b)  # 连接
print(a * 2)  # 重复
print(a[1])  # 索引获取字符串中字符(-1 -2 -3倒123)
print(a[0:2])  # 获取字符,左闭右开,空前面从第一个开始,空后面到最后一个
print(len(a))  # 长度(索引中第一个0最后一个len-1)
print(a[::-1])  # 反转字符串
#转义字符
# Backslash used to escape a quote mark
print('Penny\'s dog')
# Backslash used to escape a new line symbol
print('This is one line.\nThis is a second line')
# Backslash used to escape a tab symbol
print('Here\tThere')
#混用单双引号来转义单双引号
print("Penny's dog")
print('Penny said, "This is my dog".')
#连接字符串
#1
first_name = 'Leo'
last_name = 'Tolstoy'
full_name = first_name + ' ' + last_name
print(full_name)
#2
name = 'Leo'
name += ' '
name += 'Tolstoy'
print(name)
#10个a
print('a' * 10)
#字符串比较
'''
str1 == str2 is True if str1 and str2 are the same sequence of characters, otherwise it is False
str1 != str2 is True  if str1 and str2 are not the same sequence of characters, otherwise it is False
str1 in str2 is True if str1 appears as a substring in str2, otherwise it is False
str1 not in str2 is True if str1 does not appear as a substring in str2, otherwise it is False
str1 < str2 is True if str1 is lexicographically less than (i.e. would appear earlier in the dictionary) the value of str2, otherwise it is False
Similarly we have str1 <= str2, str1 > str2, and str1 >= str2
'''
# 字符串格式化
z = "tencent"
print(f'{z}')
w = {'name': 'tencent', 'url': 'www.qq.com'}
print(f'{w["name"]}:{w["url"]}')
# f的其他用法
print(f"{100}")  # 这是一百
print(f"{100:b}")  # b=base即进制 求二进制 b前加数字是限制长度,没有的前补空白,010b将前面空白用0取代
lenth = 10
print(f"{100:{lenth}b}")  # 传递长度参数
# 字符串函数,还有很多在菜鸟教程里
strl = "abcdabcdabc"
print(strl.count("a"))  # a的出现次数
print(strl.find("c"))  # 返回第一个位置 0开始,找不到返回-1
print("1".join("abcd"))  # 前者添加到后者中
print(strl.replace("a", "0"))  # 用后者替换前者
print(strl.split("c"))  # 按c截取

# 例题:求数字除零之后左边的个数
# 循环法
a = 12837903388000000
count = 0
m = a
while m != 0:
    m, x = divmod(m, 10)
    if x != 0:
        count += 1
print(count)
# 字符串函数法
print(len(str(a).rstrip("0")))  # rstrip去掉前后的某字符

# None等价于False

# if-elif-else
'''
if condition:
    1.to do first
elif:
    2.to do second
else:
    3.to do others
'''

# 比较,返回True或者False
a = 10
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)

# 逻辑运算
'''
1.与运算a and b
  TT为T,TF为F,FF为F
  有False返回False,否则返回b值
2.或运算a or be 
  TT为T,TF为T,FF为F
  有False返回Falsw,否则返回a
3.否运算not a
  返回相反TF
'''

# 成员
strl = "abcd"
if "a" in strl:
    print("a is in")
if "e" not in strl:
    print("e is not in")

# for循环
# range函数
# range(start,end,step)
# 返回可迭代(等价于可遍历:把每个元素依次取出)对象,而不是打印列表
print(range(10))  # 默认从零开始,从零到10,不包含10
print(range(1, 10))  # 指定开始和结束
print(range(1, 10, 3))  # 每三个
print(list(range(10)))  # 打印range里的内容
print(list(range(1, 10, 3)))
# for-range迭代遍历索引
for i in range(5):
    print(i)
# 迭代字符串
strl = "abcde"
for index in range(len(strl)):
    print(index, strl[i])
# for-item遍历元素
for item in strl:
    print(item)
# for enumerate遍历索引和元素
for index, item in enumerate(strl):
    print(index, item)
# if-continue:跳过后续进入下一循环
# if-break:中止跳出
# for-else:没有break就执行,有break就不执行
for num in range(10, 20):
    for i in range(2, num):
        if num % i == 0:
            j = num / i
            print("%d等于%d*%d" % (num, i, j))
            break
    else:
        print("%d是一个质数" % num)
#例题:数偶数数字的个数
a="193738008"
for index,item in enumerate(a):
    if int(item) % 2 == 0:#类型转换
        print(index)
'''
注意
1.格式化(code-reformat)
2.参数名有意义
3.注释
'''

#while语句
#标准形式
'''
1.初始化状态
index = 0
2.判断条件
while index < 10
    3.内容
    print(index)
    4.更新状态
    index += 1
'''
#使用while保持程序持续运行
while True:
    name = input('What is your name? (Enter x to stop) ')
    if name == 'x':
        break
    print('Hello', name)

#文件操作
# Open a file for writing
f = open('myfile', 'w')
# Write to the file
f.write('some text')
# Close the file after we are done
f.close()
# Open the file again for reading
f = open('myfile', 'r')
# read returns all the data in the file
data = f.read()
# Close the file after we are done
f.close()
print(data)
#使用with语句来保证关闭文件
# Open a file for writing
with open('myfile', 'w') as f:
    f.write('some text')
# f is automatically closed when control exits the with block
# Open the file again for reading
with open('myfile', 'r') as f:
	# read returns all the data in the file
	data = f.read()
print(data)
#open语句
'''
1.默认打开根目录文件,默认为文本文件
2.w会重写,没有该文件自动创建;r只读取,没有该文件出错;a续写,没有该文件会创建
3.wt rt at确定为文本文件,wb rb ab确定为二进制文件
'''
#逐行读取
# Set up a file for reading
with open('myfile', 'w') as file:
    file.write('Line 1: Some text\n')  # Note: you have to include the newline character when writing to the file
    file.write('Line 2: Some more text')
# Demonstrate the readline() method
with open('myfile', 'r') as file:
    line_one = file.readline()
    line_two = file.readline(a)
print(line_two)  # Just print the second line of the file
print(line_one.endswith('\n'))  # The last character of line_one is the newline character
print(line_two.endswith('\n'))  # line_two does not end in a newline character
#注:read和readline是累计的,已被读取的不会再读取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值