A maneira estúpida de aprender a versão avançada do python, a maneira estúpida de aprender as anotações do python

Este artigo apresenta principalmente aprender python da maneira mais difícil (a maneira estúpida de aprender python), que tem certo valor de referência, e amigos que precisam podem consultá-lo. Espero que você ganhe muito depois de ler este artigo. Deixe o editor levá-lo para entendê-lo juntos.

Exercício 1.

Parece que no livro


rint('hello word !')#你好世界
print('hello again')#再次见到你
print('I like typing this.')#我想试试这个
print('this is fun.')#这个很有趣
print('Yay!printing')#打印
print(' I`d much rather you `not`.')#我控制不了
print('I "said" do  not touch this') #我说不要触摸这个

Exercício 2.#Comentários,

Sob o pycharm do Windows, você deve ver isso como mostrado na figura

Exercício 3. Números e operações


print('I will now count my chickens')#我要统计我的鸡肉
print("Hens", 25+30/6)#母鸡有30只
print("Roosters",100-25*3%4)#公鸡有100-3=97只,(75除以4=18....3)
print("Now I will count the eggs:")#鸡蛋共有多少个?
print(3+2+1-5+4%2-1/4+6)#6.75。过程是3+2+1-5+0-0.25+6,。4%2的余数是0
print("It is true that 2+3<5-7?")#5<-2可以是真的吗
print(3+2<5-7)#5<-2是假的
print("what is 3+2?",3+2)#3加2等于多少,5
print("what is 5-7?",5-7)#5-7等于多少,-2
print("Oh that`s why it is false")
print('How about some more,')
print("Is it greater or equal?",5-2)#这个数大于等于几吗? 等于3
print("Is is greater or equal?",5>=-2)#这个数字大于等于吗?是的
print("Is it less or equal?",5<=-2)#这个数小于等于吗? 不是

Exercício 4.

Encontrar variável variável e nome


cars=100#汽车100辆
space_in_car=4 #一个车可以拉4个人
drivers=30#司机30人
passengers=90#乘客90人
cars_not_driven=cars-drivers# 没司机的车
cars_not_driven=drivers#司机
carpool_capacity=cars_not_driven*space_in_car#4个人30个司机
average_passengers_per_car=passengers/cars_not_driven#90个人平均要多少司机

print('there are',cars ,'cars available')
print("there are",cars,"cars available")#车变量
print("there are  only",drivers,"drivers available")#司机变量
print("there will be",cars_not_driven,"empty cars today")#今天空70个车
print("we can transport",carpool_capacity,"people")#今天可以拉120人
print("we have",passengers,"to carpool today")#今天有90个乘客
print("we need to put about",average_passengers_per_car,"in each car")#我们大概需要30辆车

Resultado de saída:

Exercício 5. Mais variáveis ​​e impressão


my_name='mrfri'
my_age = 23
my_height=178
my_weight=60
my_eyes='Brown'#我的眼睛是棕色
my_teeth='white'#我的牙齿是白色
my_hair='Black'#我的头发是黑色
print("Let's talk about %s." %my_name)#我的名字
print('He is %s cm height' % my_height)#我的身高
print("He is %s kgs heavy."%my_weight)#我的体重
print("He's got %s eyes and %s hair,His teeth are %s"%(my_eyes,my_hair,my_teeth))
print("if I add %s,%s and %s,then I get: %s"%(my_age,my_weight,my_height,my_age+my_height+my_weight))
print("If I add %d,%d and %d,then I get: %d."%(my_age,my_weight,my_height,my_age+my_height+my_weight))

Formatação de caracteres:

%% O sinal de porcentagem # é para gerar um %

caractere %c e seu código ASCII

%s string

%d inteiro com sinal (decimal)

%u inteiro sem sinal (decimal)

%o inteiro sem sinal (octal)

%x inteiro sem sinal (hexadecimal)

%X inteiro sem sinal (caracteres maiúsculos hexadecimais)

%e número de ponto flutuante (notação científica)

%E número de ponto flutuante (notação científica, substitua e por E)

%f número de ponto flutuante (com símbolo decimal)

%g número de ponto flutuante (conforme o tamanho do valor, use %e ou %f)

%G número de ponto flutuante (semelhante a %g)

%p ponteiro (imprime o endereço de memória do valor em hexadecimal)

%n armazena o número de caracteres de saída na próxima variável na lista de argumentos

%r é impresso como está, por exemplo, strings imprimem aspas

Saída de formato em Baicizhan

A nova linha \n em Baicizhan e a tabulação de \t são quatro caracteres vazios

Concatenação de strings "+

Para encontrar o resto, use "%" 100%3 é igual a 1. Para encontrar um número inteiro, use "//" 100 //3 é igual a 33

Exercício 6 Cordas e Texto


= "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print(x)
print(y)

print("I said:%r," % x)  # %表示原样输出包括了上面的单引号
print("I also said:'%s' " % y)  # %s输出没有引号了,给%s加上“引号”
hiarious = False#
joke_evaluation = "Isn't that joke so funny?! %r"
print(joke_evaluation % hiarious)
w = "this is the left side of----"
e = "a string with a right side "
print(w + e)

Exercício 7 mais impressão


print("Mary had a little lamb,")
print("Its fleece  was white as %s" % 'snow')
print("And everywhere that Mary went,")
print("."*10)#输出10个。
end1 ="C"
end2 = "h"
end3 = "e"
end4 = "s"
end5 = "e"
print(end1+end2+end3+end4+end5)#多个变量用加号连接成一个字符窜

Exercício 8 continuar a imprimir


formatter = "%r %r %r %r"
print(formatter%(1,2,3,4))
print(formatter% ("one","two","three","four"))
print(formatter%(formatter,formatter,formatter,formatter))
print(formatter % (
    "I had this thing,",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
))
# 怎么不一样捏,第三个在前一种方案出现了双引号
# 原来是"But it didn't sing."这一句中已经出现了单引号,所以在格式化的时候为了避免认错,首尾换成了双引号

Não há diferença de significado entre usar aspas simples e aspas duplas em python. Quando houver aspas simples em uma frase, ela será forçada a usar aspas duplas

A declaração de julgamento condicional if em Baicizhan

O uso de if else em Baicizhan

9. Continue a imprimir


days = "Mon Tue Wed Thu Fri Sat Sun"#定义变量days
mouths = "Jan\n feb\n Mar\n "#定义变量mouths用“\n来换行
print("Here are the days:",days)#加“,”号导入变量days
print("Here are the mouths:",mouths)#加“,”导入变量mouths,print打印输出
print(""" there`s something #“”“   ”“”使用三 个引号来保持原样输出
going on here with the three double 
quotes
we`ll be able to type as much as we like 
Even4 lines if we want""")

Aspas duplas podem colocar texto multilinha

\n é o caractere de escape, nova linha

Exercício 10

Exercício 11, faça perguntas

Código Python3: depois que python2 é atualizado para python3, existem duas funções semelhantes a input e raw_input em 2, que são consideradas funções redundantes em 3, então 3 joga fora raw_input como lixo. Portanto, precisamos substituir todos os raw_input por input antes de executar o programa de 2.


age = input("How old are you?")#定义变量age,input里输入提示内容用引号括起来
height = input("How tall are you")#定义变量height加入input提示
weight = input("How much do you weight")#定义变量weight加入input输入提示,
print("So, you are %r old,%r tall and %r heavy,"%(age,height,weight))#打印输出%r格
# 式化原样输出且加入变量age ,height,weight

insira e pergunte

str = input("Digite: ");

print("Sua entrada é %r: ", str)

Exercício 13 Parâmetros, desempacotamento, variáveis


from sys import argv
#argv = input().split()
yi,er,san,si = argv
print('第一变量是:'yi)
print("第二个变量 是:"er)
print("第三个变量是:"san)
print("第四个变量是:"si)

Há um erro no pycharm e ele não pode ser executado, pode ser permitido no terminal do Windows, mas os parâmetros precisam ser reduzidos em dois, que originalmente são 4 parâmetros.

Nesta questão, você aprenderá outra maneira de passar variáveis ​​para variáveis ​​(scripts são arquivos *.py). Para executar um script python, podemos usar a linha de comando para inserir python ex13.py, onde python é o programa a ser executado e ex13.py é o parâmetro.

Primeiro prepare o script que vai passar os parâmetros


from sys import argv#导入argv

,first, second, third = argv #定义四个变量,一定要在终端执行,
#文件名是第一个,接着第二个是1,第三个是2,第四个是3
print("Your  is called:", )
print("Your third variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
print("\n")    # 夹

Análise do roteiro:

Linha 1:

O papel da declaração de importação é se referir aos programas e "funções" que já escrevemos (que vem com python e escritos por outros), para que essas "funções" possam ser usadas no script atual.

sys é a "função" introduzida desta vez, geralmente os chamamos de "módulo" ou "biblioteca". Ele fornece um conjunto de variáveis ​​e funções relacionadas ao ambiente de tempo de execução do Python.

A importação pode ser usada de duas maneiras:

Importar todos os módulos: import sys

Importe alguns módulos: from sys import argv

Desta vez, o segundo método é usado para introduzir "funções" específicas de argv do módulo sys (obter os parâmetros da linha de comando que estão sendo executados no momento)

Linha 3:

Esta linha descompacta argv. Unpacking é um termo especial para programação. Sua função é atribuir vários valores contidos em argv a várias variáveis ​​à esquerda, sucessivamente:, primeiro, segundo, terceiro

Linhas 5-8:

Imprimimos várias variáveis ​​depois de serem atribuídas.

Este script precisa ser executado separadamente na linha de comando após salvar: (deve ter 3 parâmetros)

python ex13.py primeiro 2º 3º

1

1from sys import argv

23 , primeiro, segundo, terceiro = argv

45print"O chama-se:",

6print"Sua primeira variável é:", primeiro

7print"Sua segunda variável é:", segundo

8print"Sua terceira variável é:", terceira

Tentamos vários parâmetros diferentes:

Link original: "Aprenda python3 de uma maneira estúpida" série de planos de exercícios - 13: parâmetros, desempacotamento, variáveis_Haha Restaurant's Blog-CSDN Blog

Exercício 14, passagem de parâmetros


from sys import argv
argv = input().split()
#传入的参数分配给变量
yi,er,san,si = argv
#输出
print('第一个变量',yi)
print('第二个变量',er)
print('第三个变量',san)
print('第四个变量',si)

Exercício 15


from sys import argv

 ,filename =argv #定义来变量

print ("We 're  going to erase %r ."%filename )#传递变量之前创建号的txt文件
print ("If you don't want that, hit CTRL-C(^C).")#输出打印
print ("If you do want that , hit RETURN.")#输出打印

input("?")#提示符

print ("Opening the file...")#打印输出
target =open (filename,'w')#对文件进行读写

print ("Truncating the file,Goodbye!")#打印输出
target .truncate()#清除之前的文件内容

print ("Now I'm going to ask you for three lines.")#打印输出

line1 =input ("line1:")#定义变量,提示语打印输出
line2 =input ("line2:")
line3=input ("line3:")

print ("I'm going to write these to the file.")#原文打印输出

target.write(line1)#写入第一行文件
target.write("\n")#换行
target.write(line2)#写入第二行文件
target.write("\n")#换行
target.write(line3)
target.write("\n")

print ("And finally ,we close it .")#原样输出提示,要关闭文件
target.close()#关闭文件

Exercício 16, um arquivo, txt copiado para outro arquivo txt

Método 1:


from sys import argv#导入argv
scrip,from_file,to_file = argv#给三个变量,在Windows终端输入from_file和to_file
print("copying form %s to %s"%(from_file,to_file))#字符串格式输出,1.txt和3.txt
raw_input=open(from_file)#把3.txt文件打开
indata= raw_input.read()#读取3.txt文件
print("The input file is %d bytes long"%len(indata))#打印输出3.txt数据的大小字节
print("Ready,hit RETURN to continue,CTRL-c to abort")#打印输出
input()#写入
output=open(to_file,'w')#1.txt文件写入
output.write(indata)#写入数据
print("Alright,all done,")
output.close()
raw_input.close()



Método 2:


from sys import argv
argv = input().split()
from_file,to_file = argv
indata = open(to_file,'w').write(open(from_file).read())
a = open(to_file)
print(a.read())
a.close()

argv é equivalente a uma lista e os parâmetros podem ser passados ​​usando subscritos

Exercício 15,


#从sys中使用argv列表
from sys import argv
#脚本本身名字,传入脚本的参数
, filename =argv
#打开filename这个参数所表示的文档,并将这个file传给txt
txt = open(filename)
#打印字符串,并代入文件名
print ("Here's your file %r :"%filename)
#打印字符串,并读取文件
print (txt.read())
#打印字串符,
print ("Type the filenanme again:")
#定义file,并使用input输入
file_again = input(">")
#定义txt_again,并打开file传给txt
txt_again =open (file_again)
#打印字符串,并读取文件
print (txt_again.read())

Exercício 14.


from sys import argv#导入argv

 ,user_name = argv#定义两变量
prompt ='~'#输入变量提示 符是~

print ("Hi %s ,I'm the %s  ." %(user_name,))#格式化变量打印
print ("I'd like to ask you a few questions.")#打印我有一个问题
print ("Do you like me %s ?"%user_name)#格式化输出,
likes = input(prompt)#变量

print ("Where do you live %s ?"%user_name)#格式输出
lives = input(prompt)#变量

print("What kind of computer do you have?")#输出
computer =input (prompt)#变量

print ("""
Alright , so you said %r about liking me.
You live in %r .Not sure where that is .
And you have a %r computer  .Nice.
"""%(likes,lives,computer))#三引号自动换行输出

  1. Certifique-se de entender que as aspas triplas """ podem definir uma string de várias linhas e % é uma ferramenta de formatação de string.
    sim

Exercícios para ler o conteúdo de um arquivo txt


from sys import argv
,filename = argv
txt = open(filename)
print("Here`s you file,%s"%filename)
print(txt.read())

Exercício 18.

Função, o comando que usamos é def, que significa "definir".As regras de nomenclatura de funções são semelhantes à nomenclatura de variáveis.

A passagem de parâmetros de função, a função também pode ser um pequeno script,

Isso é muito semelhante ao argv do script (que significa parâmetros), os parâmetros devem ser colocados entre parênteses () para funcionar corretamente.

Em seguida, terminamos a linha com dois pontos: e iniciamos a próxima linha de recuo.

Após os dois pontos, as linhas recuadas com 4 espaços são


def print_two(*args):#首行两冒号
    arg1,arg2, = args#缩进四个字符,一个tab
    print("arg1:%r,arg2:%r,"%(arg1,arg2))#缩进四个字符,一个tab。%r原样格式化输出,
def print_two_again(arg1,arg2):
    print("arg1:%r,arg2:%r"%(arg1,arg2))
def print_one(arg1):
    print("arg1:%r"%arg1)
def print_none():
    print("I got nothin.")
print_two("Zed,","shaw")#
print_two_again("Zed","shaw")#演示函数可以接受两个参数,直接用()里的名称来做参数不需要解包,
print_one("Fisrt!")#演示了函数接受一个参数
print_none()#演示了函数不接受任何参数

Exercício 19


def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print("You have %d cheeses!"%cheese_count)
    print("You have %d boxes of crackers! "%boxes_of_crackers)
    print("Man that`s enough for a part")
    print("Get a blanket.\n")
print("We can just give the fution numbers  directly:")#直接使用函数编码
cheese_and_crackers(20,30)
print("OR,we can use varables from our :")#在函数里使用脚本变量
amount_of_cheese=10
amount_of_crackers=50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print("we can even do math inside too:")
cheese_and_crackers(10+20,5+6)#直接在函数里面使用数学运算
print("And we can combine the two ,variables and math:")
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
#把变量和数学运算相结合。

Exercício 20


from sys import argv#从sys库导入argv
,input_file=argv#解包argv,把参数依次付给左边变量
def print_all(f):#定义函数print_all,定义形参f
    print(f.read())#以只读的方式读取f中的内容
def rewind(f):#定义函数rewind,且设置参数f
    f.seek(0)#移动文件读取指针至f中内容开头的位置
def print_a_line(line_count,f):#定义函数print_a_line.且设置形参t,f
    print(line_count,f.readline())#打印出文件的所有,读取222文件内容打印出来
current_file=open(input_file)#把222文件参数传递给 currtent_fle.读取222文件内容
print("First let`s print the whole file:\n")#打印当前内容换行
print_all(current_file)#,调用前文print_all函数,打印curre_file文件内容
print("Now let`srewind,kinds of like a tape")
rewind(current_file)#调用前文定义的函数rewind,将文件读取指针至开头位置
print("Let`s print three lines:")#打印字符串,打印三行
current_line=1#设置文本行号第一行
print_a_line(current_line,current_file)#打印第一行行号,和当前文件,
current_line=current_line+1#设置文本第二line+,行数增加第二行,,
print_a_line(current_line,current_file)#打印第二行行号和当前文件
current_line=current_line+1#设置文本第三line+1,行数增加读取第三行,
print_a_line(current_line,current_file)#打印第三行行号和当前文件

Toda vez que print_a_line é executado, você passa uma variável chamada current_line. Cada vez que a função é chamada, imprima a current_line para e rastreie como ela se torna line_count em print_a_line.

Resposta Aqui, line_count é realmente chamado de parâmetro posicional.A razão pela qual o parâmetro current_line no momento da chamada se torna o line_count no momento da definição da função é porque eles estão na mesma posição quando são definidos e chamados.

Se invertermos a posição dos dois parâmetros quando a função for definida e mantivermos a ordem de chamada inalterada

Exercício 20

função de retorno


def add(a,b):#定义函数add,
    print("ASSING %d +%d"%(a,b))#打印输出ASSING 30+5
    return a+b #计算a+b
def subtract(a,b):#定义函数subtract,
    print("SUBTRACTING %d -%d"%(a,b))#打印输出SUBTRACTING 78-4
    return a-b#计算a减去b
def multiply(a,b):#定义函数multiply,
    print("MULTIPLYING %d *%d"%(a,b))
    return a*b#计算a乘b
def divide(a,b):#定义函数divide,
    print("DIVIDIG %d / %d"%(a,b))
    return a/b#计算a除b
print("Let`s do some math wiht just funtions!")#让我们来做一些数学函数
age = add(30,5)#调用函数add,返回值赋给age
height = subtract(78,4)调用函数subtract,返回值赋给height
weight = multiply(90,2)调用函数multiply,返回值赋给weight
iq = divide(100,2)调用函数divide,返回值赋给iq
print("Age;%d,height:%d,weight:%d,IQ:%d"%(age,height,weight,iq))#格式化打印输出
print("Here is a puzzle")#这是一个难题
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
#函数的返回值用作了另外一个函数的参数,非常难懂得
print("That becomes:",what,"can you do it by hands")#看我们能做出来吗

Acho que você gosta

Origin blog.csdn.net/chatgpt001/article/details/132134942
Recomendado
Clasificación