Python入门碰到的坑

格式化

price = 10
weight = "20"
print(" %.02f weight= %s" % (price, weight))

当同时打印多个参数时,这里务必要在参数外面添加(),否则报错。

if和缩进关系

age = 16
name = "guchuanhang"
if age > 18:
    print("%s should get see adult hot" % name)
    print("%s should not enter net bar " % name)
print("this will print no matter your age")

两个缩进的都是 if条件满足时要执行的。

逻辑运算符

两个条件的时候,需要在每个条件中使用()

age = int(input("input age: "))
if (age >= 0) and (age <= 120):
    print("age is %d" % age)
else:
    print(" too strange")

函数内部不能修改全局变量的值

num = 10


def gabian():
    num = 20


print(num)
# gabian()
print(num)

函数内部在改变变量前,需要声明global num。否则,创建一个局部变量

Python 中 == 用于判断数值相等

和Java截然不同,Python中使用 is 判断是不是同一个对象,java使用 == 来判断。

避免通过对象访问类成员

class Person:

    count = 0

    def __init__(self):
        self.count += 1


class Shen(Person):

    def __init__(self):
        Person.count +=1


xx =Shen()

xx2 =Shen()

print(xx.count)
xx2.count = 100

print(xx2.count)   //100

print(Person.count)   //2


猜你喜欢

转载自blog.csdn.net/guchuanhang/article/details/83189026