21番茄网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 21番茄网
查看: 928|回复: 0

python常用的思维方法

[复制链接]

646

主题

799

帖子

2686

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2686
发表于 2020-11-19 11:07:42 | 显示全部楼层 |阅读模式
编程常用的思维方法

1.循环是比较难的,因此循环的训练很重要,其中有一种方法,编程中常常用到,就是在循环外定义个空箱子,然后在循环时不断更新箱子中的内容
举例:
import random

# 出拳
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = '  '
user_choice = input('请出拳:(石头、剪刀、布)') # 请用户输入选择
while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
    print('输入有误,请重新出拳')
    user_choice = input('请出拳:(石头、剪刀、布)')

python常用的思维方法  Python基础语法 line2
                               
登录/注册后可看大图


2.函数的返回值往往是元组,因此调用函数内的参数时,可以用元组的偏移量来调用。
def estimated(my_input):
    # 把元组中的数据取出来
    size = my_input[0]
    number = my_input[1]
    time = my_input[2]

python常用的思维方法  Python基础语法 line2
                               
登录/注册后可看大图


3.在众多条件中,提取出关键条件,剩下的为其他条件。
print('—————结果—————')
if user_choice == computer_choice:  # 使用if进行条件判断
    print('平局!')
elif (user_choice == '石头' and computer_choice == '剪刀') \
or (user_choice == '剪刀' and computer_choice == '布') \
or (user_choice == '布' and computer_choice == '石头'):
    print('你赢了!')
else:
    print('你输了!')

python常用的思维方法  Python基础语法 line2
                               
登录/注册后可看大图


4.很多时候建立一个列表,在后面调用列表内容或列表偏移量。
import random

all = ['正面','反面']
guess = '  '

while guess not in all:
    print('------猜硬币游戏------')
    print('猜一猜硬币是正面还是反面?')
    guess = input('请输入“正面”或“反面”:')

toss = all[random.randint(0,1)]
# 随机抛硬币,all[0]取出正面,all[1]取出反面

python常用的思维方法  Python基础语法 line2
                               
登录/注册后可看大图


5.注意 i-1 的方法使用
deposit = [100,300,900,2000,5000,0,2000,4500]

for i in range(1, len(deposit)):
    if deposit[i-1] == 0:  
# 判断除数等于0时,特殊处理。
        print('你上次存款为 0 哦!')
    else:
        times = deposit/deposit[i-1]
        print('你的存款涨了%f倍'%times)






上一篇:python换行的方法
下一篇:index() 函数
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|21番茄网 ( 粤ICP备10099428号 ) 奇远富

GMT+8, 2024-4-24 11:51 , Processed in 0.483623 second(s), 34 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表