Python 0614

  • windows自带截图快捷键:win+shift+s
  • vscode 弹出终端的快捷键: Ctrl + ~
  • 可以在终端中通过输入 python xxx.py 来运行程序
  • 快速运行代码:下载coderunner,然后快捷键Ctrl + Alt +N,注意每次先保存代码,再运行
  • 单行注释:Ctrl + /
  • 取消单行注释: Ctrl + A + U
  • 多行注释:Alt + Shift + A
  • 取消多行注释: Alt + Shift + A
  • 变量规则
    – 变量名只能包含字母、数字和下划线。变量名只能以字母或下划线打头
    – 变量名不能有空格,但可用下划线来分隔其中的单词
  • 字符串
    – 可用单引号或双引号括起来
    – 修改字符串的大小
    –合并字符串:“+”连接字符串
    – \n \t
name.title() #首字母大写显示每个单词
name.upper() #全部大写
name.lower() #全部小写
# 删除空白
msg = ' python '
//rstrip():暂时去除字符串末尾的空白
print(msg.rstrip()) 
//lstrip():暂时去除字符串开头的空白
print(msg.lstrip()) 
//strip():暂时去除字符串两端的空白
print(msg.strip()) 
//永久性删除字符串末尾空白
msg = msg.rstrip()
print(msg)

  • 数字
 print(0.1 + 0.1)

str(a):将数值转换为字符串

  • 列表 [ ]
    – 列表是由一系列按特定顺序排列的元素组成的。
    – 有序,可重复,可修改
    – 索引为0是开头,-1是最后一个列表元素,当列表为空的时候,不能用-1去访问最后一个元素
#访问列表元素
bicycles = ["trk",'cannondale','redline','specialized']
print(bicycles[0])
print(bicycles[-1])//返回最后一个列表元素
#修改列表元素
bicycles[0]='aaa'
#增加元素
bicycles.append('bbb')
#插入元素
bicycles.insert(1,'bbb') //在索引为1的位置处插入bbb
#删除指定位置的元素
del bicycles[-1]
#删除末尾元素,并接着使用其值
temp = bicycles.pop()
#弹出任意位置的值
temp1 = bicycles.pop(2)
#根据值删除元素
bicycles.remove('bbb')
//若有重复元素,只删除先前一个的重复元素
#永久性排序
cars.sort()
cars.sort(reverse=True)//与字母相反顺序
#临时排序
sorted(cars)
sorted(place,reverse=True)//与字母相反顺序
#反转列表排序顺序
cars.reverse()
#列表长度
len(cars)
  • 循环
#循环:每次获取magicians中的值,然后存储在变量magician中
magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician)
  • 创建数值列表
    – range():创建一个整数列表。生成从指定的第一个数值开始,到指定的第二个值前结束
    – 输出数字列表
numbers = list(range(1,6))
numbers = list(range(1,6,2))//从1开始数,不断加2,直到到达或超过6
print(min(squares)) //最小值
print(max(squares)) //最大值
print(sum(squares)) //总和

– 列表解析

#指定了一个列表名叫squares,定义了表达式value**2,用于生成要存储到列表中的值,接下来编写一个for循环,用于给表达式提供值
 squares = [value**2 for value in range(1,11)]

– 切片

players[0:3] #前三个即索引为012
players[:4]  #没有指定起始索引,从列表开头提取
players[2:]  #没有指定末尾索引,提取到末尾
players[-3:] #-1表示最后一个,这里表示提取最后三名
#复制切片
friend_foods = my_foods[:]
//易错:friend_foods = my_foods,这样不对,两个都指向同一块地址
  • 元组
    – 不可修改
#定义元组
dimensions = (200,50)
#访问元组元素
print(dimensions[0])
#要想改变元组,只能给元组变量赋值
dimensions=(100,200,30)
  • 条件判断
#检查特定值是否在列表中 in / not in
banned_users = ['andrew','carolina','david']
user = 'marie'
user1 = 'david'
if user1 in banned_users:
    print(user1 + 'is in here!')
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")
    
#if-else 语句
age = 17
if age >= 18:
    print("You are old enough to votel")
    print("Have you registered to vote yet?")
else:
    print("Sorry,you are too young to vote")
    print("Please register to vote as soon as you turn 18!")

# if - elif - if 语句
if age < 4:  //小于4岁
    print("free")
elif age < 18:  //4-18岁
    print("charge 5 dollara")
else:    //18岁以上
    print("charge 10 dollars")
  • 字典
alien_0 = {'color':'green','points':5}
print(alien_0)
#访问字典的值
print(alien_0['color'])
print(alien_0['points'])
#增加键值对
alien_0['x_position'] = 0
print(alien_0)
#修改字典中的值
alien_0['color'] = 'yellow'
#删除键值对(永久性操作)
del alien_0['points']  
  • 遍历字典
    –遍历所有的键值对
#items的方法是以列表的形式返回 (键,值)
for key,value in info.items():
    print("\nKey:" + key)
    print('Value:' + str(value))

– 遍历字典中所有键

for word in info.keys():
    print(word)

–按顺序遍历字典中所有键

for word in sorted(info.keys()):
    print(word)

– 遍历字典中所有值

for num in info.values():
    print(num)

– 找出字典中不同的值(不重复)

for num in set(info.values()):
    print(num)
  • 嵌套:将一系列字典存储在列表中,或将列表作为值存储在字典中
    – 字典列表
alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

– 在字典中存储列表

pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
}
print('You ordered a ' + pizza['crust'] + '-crust pizza' + 'with the following toppings:')
for topping in pizza['toppings']:
    print('\t'+topping)

– 字典中存储字典

users = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    }
}
for username,user_info in users.items():
    print("\nUsername:"+username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    
    print("\tFull name:"+ full_name.title())
    print("\tLocation:" + location.title())

- 遇到的问题
vscode安装code runner扩展后,Python的input无法输入问题
解决办法:
1、shift + command + p , 输入 settings , 打开工作区设置(Workspace settings)
2、搜索 code-runner
3、下拉找到 “Run In Terminal” 勾选

  • input() 工作原理
    – 让程序法暂停运行,等待用户输入一些文本
name = input("Please enter your name: ")
print("Hello, "+ name + "!")

– 当提示过长时,可用变量进行存储

prompt = "If you tell us who you are , we can personlize the messages you see."
prompt += '\nWhat is your first name?'

name = input(prompt)
print('\nHello, ' + name + "!")

– 注意: 使用input()时,python将用户输入解读为字符串

  • 求模运算符 %

number = input("Enter a number, and I'll tell you if it's even or odd:")
number = int(number)

if number % 2 == 0:
    print("\nThe number" + str(number)+ " is even.")
else:
    print("\nThe number" + str(number) + 'is odd.')

  • while循环
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number+=1
  • break:立即退出while循环,不再运行循环中余下的代码
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)
  • contiune:返回到循环开头,并根据条件测试结果决定是否继续执行循环
current_number = 1
while current_number <= 5:
    current_number+=1
    if current_number % 2 == 0:
        continue
    print(current_number)
  • 如果程序陷入无限循环,可按Ctrl + C
  • 怎么查看Anaconda内置的python版本
    1、激活anaconda环境
conda activate
    2、查看python版本号
pythpn -V
  • pytorch环境激活
    打开anaconda prompt,输入conda activate pytorch
    退出时deactivate
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值