Python基本知识回顾(基于《“笨方法”学Python3》——ex1-ex22)

本文介绍了Python的基础语法,包括print函数的使用、注释方法、变量与打印、浮点数四舍五入、字符串操作、format函数、转义字符、input函数等。还讲解了参数解包和变量赋值,以及文件的读取、写入、清空等操作,同时说明了open函数的不同打开方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

print(“要打印的文本”)或print(‘要打印的文本’)
程序中的注释使用的是#

  • 整行快捷注释 Ctrl + /
  • 整行快捷取消注释 Ctrl + /
    print()中可以直接进行计算,但不可加“”
    变量和打印
  • print(f"He’s {变量的名字} manager")
  • 浮点数的四舍五入函数:round() ,如 round(1.7333)
    字符串和文本
  • 例:
w = "abc"
e = "def"
print(w)
print(e)
print(w + e)

得到的结果为

abc
def
abcdef

  • print()会在最后自动加一个换行符,可以使用end=’ ',将换行舍去

format()函数的使用

formatter = "{}"
print(formatter.format("one")
  • 在这里,format函数传递一个参数,该参数会和formatter中的{}匹配

""" ________"""三个引号之间可以表示多行打印

print(""""
There's something going on here
With the three double-quotes
We'll be able to type as much as we like 
""")

转义字符的记忆

input()的使用——“参数 = input()”即可实现对参数的赋值
其中,强转有 “参数 = int(input())”
可以通过input中有字符串进行提示作用

age = input("How old are you?")

这里不会将 “How old are you?” 也做为变量输入

参数、解包和变量

from sys import argv
script,first,second,third = argv

print("The script is called:",script)
print("Your first variable is:",first)
print("Your second variable is:",second)
print("Your third variable is:",third)

这里,要在cmd中输入

python 文件路径 first 2nd 3rd

python表示进入python环境
文件路径赋值给script
first赋值给 first
2nd 赋值给 second
3rd 赋值给 third
读取文件

from sys import argv#导入库

script,filename = argv#输入数据

txt = open(filename)#打开文件

print(f"Here's your file {filename}")#打印文件名
print(txt.read())#打印文件内容
txt.close()

print("Type the filename again:")#再次打印文件
fille_again = input(">")#输入文件地址

txt_again = open(fille_again)#将文件打开的内容赋值给txt_again
print(txt_again.read())#打印数据
txt_again.close()

需要在cmd里输入

python .py文件的路径 .txt文件的路径

读取文件的函数

open:打开文件
close:关闭文件
read:阅读文件
readline:阅读其中一行,并且在阅读完后自动换行
truncate:清空文件
write(‘stuff’):将“sutff”写入文件
seek(0):移动读写位置到开头

关于open的方式:
‘r’ open for reading (default)
‘w’ open for writing, truncating the file first
‘x’ create a new file and open it for writing
‘a’ open for writing, appending to the end of the file if it exists

target = open(filename,'w')

函数、变量、代码和函数

def print_two(*args):
    arg1,arg2 = args
    print(f"arg1:{arg1},arg2:{arg2}")

def print_two_again(arg1,arg2):
    print(f"arg1:{arg1},arg2:{arg2}")

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")

其中,*arg表示把参数放到名叫arg的列表里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值