improve your python code(6)

1. i+=1不等于++i

python解释器会将++i解释为+(+i),同理将--i解释为-(-i)。其中+表示正数符号而不是自增,-表示负数符号而不是自减。这样有:

>>>-2
-2
>>>--2
2
>>>-----2
-2

因此你需要明白++i在python中语法上时合法的,但并不是我们理解的通常意义上的自增操作

2. 使用with自动关闭资源

你在IDE中这样写:

f = open("test.txt",'w')
f.write("test")

时,真的创建了文件,并且把”test”写进了文件里,这是IDE替你做的,事实上,如果你在ipyhton中这样写,打开文件后,里面并没有test.因为你没有关闭文件
因此,你可以用下面的语法来“优雅”的操作文件:

with open('test.txt','w') as f:
    f.write('test')

这里写图片描述

3. 异常处理的基本原则

这里写图片描述
这里写图片描述
1. 注意异常粒度,不推荐在try中放入过多代码。
2. 谨慎使用单独的except语句处理所有异常
3. 注意异常的捕获顺序:将继承结构中子类异常在前面的except语句中抛出,而父类异常在后面的except语句中抛出。
4. 异常应该在适当的位置处理:如果异常能够在被捕获的位置处理,那么应该及时处理,不能处理的,应该以合适的方式向上层抛出。如

try:
    some_code()
except:
    revert_stuff()
    raise

做个试验验证一下:
1:如果这样写,则在fun()中,异常就已经被处理了:

#!/usr/bin/env python
# encoding: utf-8


"""
@python version: python3.6.1
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@site: http://blog.youkuaiyun.com/github_36326955
@software: PyCharm
@file: pyexceptions.py
@time: 5/2/2017 9:24 PM
"""


def fun():
    try:
        a=0
        b=1
        print(b/a)
    except:
        print("exception has been handled in fun")
        #raise 


def usefun():
    try:
        fun()
    except BaseException as b:
        print("exception in fun has been handled in usefun:",b)

if __name__ == '__main__':
    usefun()

得到的结果证明确实是在fun中处理了:

output:
exception has been handled in fun

Process finished with exit code 0

如若把上面的代码中,注释掉的”raise”使用,把”raise”上面的print语句注释掉,则异常被raise抛出到上一层,在usefun中处理:

output:
exception in fun has been handled in usefun: division by zero

Process finished with exit code 0
### Python Code Examples for Expressing Love Certainly! Below are some creative and thoughtful ways to express love through Python code: #### Simple Heart Shape Using Print Statements A straightforward way to show affection is by printing a heart shape. ```python print(" *** ") print(" ***** *****") print(" *********** ") print("*** ***") print("* *") ``` This creates a visual representation of a heart using asterisks[^1]. #### Personalized Message Generator Creating personalized messages can add an extra layer of sentimentality. ```python def generate_love_message(name): message = f"Dear {name},\n\nYou mean the world to me." return message partner_name = "Alice" print(generate_love_message(partner_name)) ``` The function `generate_love_message` takes a name as input and returns a heartfelt message directed at that person[^2]. #### Interactive Love Calculator (for Fun) An interactive program where users can enter their names along with their partner's name to get a fun score indicating compatibility. ```python import random def calculate_love_score(your_name, partner_name): combined_names = your_name + partner_name score = sum(ord(char.lower()) - ord('a') + 1 for char in combined_names if char.isalpha()) final_score = score % 100 + 1 return min(final_score, 100) your_name = input("Enter your name: ").strip() partner_name = input("Enter your partner's name: ").strip() score = calculate_love_score(your_name, partner_name) print(f"\nThe love score between you and {partner_name} is {score}%!") if score >= 85: print("That’s incredibly high! True love might be found here.") elif score >= 60: print("It looks promising!") else: print("Keep nurturing this relationship; it has potential.") ``` In this script, user inputs two names which then go into calculating a pseudo-love percentage based on character values from ASCII codes. The result provides playful feedback about the likelihood of true love existing between those named individuals[^3]. --related questions-- 1. How do I modify these scripts to include more personal details? 2. Can such programs help improve communication within relationships? 3. What other types of symbolic patterns could one create using Python print statements besides hearts? 4. Is there any library specifically designed for generating romantic content via programming languages like Python?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值