AI训练营Python-阿里云天池-task1

# https://tianchi.aliyun.com/notebook-ai/detail?postId=169961
import decimal
from decimal import Decimal
import random

# 这是一个注释
print("Hello world")
# Hello world



'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
print("Hello china")
# Hello china

"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号 
这是多行注释,用三个双引号
"""
print("hello china")
# hello china



print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8



print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True


print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False



print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1



x, y = 4, 5
if x < y:
    small = x
else:
    small = y

print(small)  # 4

x, y = 4, 5
small = x if x < y else y
print(small)  # 4

letters = ['A', 'B', 'C']
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')

# A exists
# h not exists

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

print(-3 ** 2)  # -9
print(3 ** -2)  # 0.1111111111111111
print(1 << 3 + 2 & 7)  # 0
print(-3 * 2 + 5 / -2 - 4)  # -12.5
print(3 < 4 and 4 < 5)  # True

a = "hello"
b = "hello"
print(a is b, a == b)

teacher = "老马的程序人生"
print(teacher)  # 老马的程序人生

first = 2
second = 3
third = first + second
print(third)  # 5

myTeacher = "老马的程序人生"
yourTeacher = "小马的程序人生"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher)  # 老马的程序人生,小马的程序人生

# 运行一下就好啦
set_1 = {"欢迎", "学习","Python"}
print(set_1.pop())

a = 1031
print(a, type(a))
# 1031 <class 'int'>

b = dir(int)
print(b)

a = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11

print(1, type(1))
# 1 <class 'int'>

print(1., type(1.))
# 1.0 <class 'float'>

a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07

a = decimal.getcontext()
print(a)

b = Decimal(1) / Decimal(3)
print(b)

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

print(True + True)  # 2
print(True + False)  # 1
print(True * False)  # 0

print(type(0), bool(0), bool(1))
# <class 'int'> False True

print(type(10.31), bool(0.00), bool(10.31))
# <class 'float'> False True

print(type(True), bool(False), bool(True))
# <class 'bool'> False True

print(type(''), bool(''), bool('python'))
# <class 'str'> False True

print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True

print(type([]), bool([]), bool([1, 2]))
# <class 'list'> False True

print(type({}), bool({}), bool({'a': 1, 'b': 2}))
# <class 'dict'> False True

print(type(set()), bool(set()), bool({1, 2}))
# <class 'set'> False True

print(isinstance(1, int))  # True
print(isinstance(5.2, float))  # True
print(isinstance(True, bool))  # True
print(isinstance('5.2', str))  # True

print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10 + 10))  # 20
print(str(10.1 + 5.2))  # 15.3

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
    print(item, end='&')
print('hello world')

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')

print(bin(3))  # 0b11
print(bin(-3))  # -0b11

print(bin(-3 & 0xffffffff))
# 0b11111111111111111111111111111101

print(bin(0xfffffffd))
# 0b11111111111111111111111111111101

print(0xfffffffd)  # 4294967293

if 2 > 1 and not 2 > 3:
    print('Correct Judgement!')

# temp = input("猜一猜小姐姐想的是哪个数字?")
# guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
# if guess == 666:
#     print("你太了解小姐姐的心思了!")
#     print("哼,猜对也没有奖励!")
# else:
#     print("猜错了,小姐姐现在心里想的是666!")
# print("游戏结束,不玩儿啦!")

hi = 6
if hi > 2:
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')

# temp = input("猜一猜小姐姐想的是哪个数字?")
# guess = int(temp)
# if guess > 8:
#     print("大了,大了")
# else:
#     if guess == 8:
#         print("你太了解小姐姐的心思了!")
#         print("哼,猜对也没有奖励!")
#     else:
#         print("小了,小了")
# print("游戏结束,不玩儿啦!")

# temp = input('请输入成绩:')
# source = int(temp)
# if 100 >= source >= 90:
#     print('A')
# elif 90 > source >= 80:
#     print('B')
# elif 80 > source >= 60:
#     print('C')
# elif 60 > source >= 0:
#     print('D')
# else:
#     print('输入错误!')

# my_list = ['lsgogroup']
# my_list.pop(0)
# assert len(my_list) > 0

# count = 0
# while count < 3:
#     temp = input("猜一猜小姐姐想的是哪个数字?")
#     guess = int(temp)
#     if guess > 8:
#         print("大了,大了")
#     else:
#         if guess == 8:
#             print("你太了解小姐姐的心思了!")
#             print("哼,猜对也没有奖励!")
#             count = 3
#         else:
#             print("小了,小了")
#     count = count + 1
# print("游戏结束,不玩儿啦!")

string = 'abcd'
while string:
    print(string)
    string = string[1:]

count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = count + 1
else:
    print("%d is not less than 5" % count)

count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    break
else:
    print("%d is not less than 5" % count)

for i in 'ILoveLSGO':
    print(i, end=' ')  # 不换行输出

member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
    print(each)

# 张三
# 李四
# 刘德华
# 刘六
# 周润发

for i in range(len(member)):
    print(member[i])

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in dic.items():
    print(key, value, sep=':', end=' ')

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key in dic.keys():
    print(key, end=' ')

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for value in dic.values():
    print(value, end=' ')

for num in range(10, 20):  # 迭代 10 到 20 之间的数字
    for i in range(2, num):  # 根据因子迭代
        if num % i == 0:  # 确定第一个因子
            j = num / i  # 计算第二个因子
            print('%d 等于 %d * %d' % (num, i, j))
            break  # 跳出当前循环
    else:  # 循环的 else 部分
        print(num, '是一个质数')

for i in range(2, 9):  # 不包含9
    print(i)

for i in range(1, 10, 2):
    print(i)

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)

languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
    print('I love', language)
print('Done!')
# I love Python
# I love R
# I love Matlab
# I love C++
# Done!


for i, language in enumerate(languages, 2):
    print(i, 'I love', language)
print('Done!')

# secret = random.randint(1, 10) #[1,10]之间的随机数
#
# while True:
#     temp = input("猜一猜小姐姐想的是哪个数字?")
#     guess = int(temp)
#     if guess > secret:
#         print("大了,大了")
#     else:
#         if guess == secret:
#             print("你太了解小姐姐的心思了!")
#             print("哼,猜对也没有奖励!")
#             break
#         else:
#             print("小了,小了")
# print("游戏结束,不玩儿啦!")

for i in range(10):
    if i % 2 != 0:
        print(i)
        continue
    i += 2
    print(i)

x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)

x = [i ** 2 for i in range(1, 10)]
print(x)

x = [(i, i ** 2) for i in range(6)]
print(x)

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)

a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
print(a)

x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)
# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

x[0][0] = 10
print(x)

a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)

a = (x for x in range(10))
print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)

c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)

e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>

print(next(e))  # 0
print(next(e))  # 1

for each in e:
    print(each, end=' ')

s = sum([i for i in range(101)])
print(s)  # 5050
s = sum((i for i in range(101)))
print(s)  # 5050

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError:
    print('打开文件出错')

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))

try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
    print('类型出错\n原因是:' + str(error))
except ValueError as error:
    print('数值出错\n原因是:' + str(error))

dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except LookupError:
    print('查询错误')
except KeyError:
    print('键错误')
else:
    print(x)

dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except KeyError:
    print('键错误')
except LookupError:
    print('查询错误')
else:
    print(x)

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('出错了!\n原因是:' + str(error))

def divide(xy, yx):
    try:
        result = int(xy) / int(yx)
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")

divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")

try:
    fh = open("testfile.txt", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print("Error: 没有找到文件或读取文件失败")
else:
    print("内容写入文件成功")
    fh.close()

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')


print("over")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值