6、上机练习:体验Python程序

2021-04-18  本文已影响0人  看远方的星

目录
一、输入代码并运行成功
二、报错

一、输入代码并运行成功

注意对齐和缩进
注意字母大小写、空格
注意左右括号的配对

#输入某年某月某日,判断这一天是这一年的第几天?
import datetime

dtstr = input('Enter the datetime:(20170228):')
dt = datetime.datetime.strptime(dtstr,"%Y%m%d")
another_dtstr = dtstr[:4] + '0101'
another_dt = datetime.datetime.strptime(another_dtstr,"%Y%m%d")
print(int((dt - another_dt).days) +1)
#输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
import string

s = input('input a string:')
letter = 0
space = 0
digit = 0
other = 0
for c in s:
    if c.isalpha():
        letter += 1
    elif c.isspace():
        space += 1
    elif c.isdigit():
        digit += 1
    else:
        other += 1
print('there are %d letters, %d spaces,%d digits \
      and %d other characters in your string. '\
      % (letter , space , digit , other))
# merge sort
# 归并排序
import random

def merge_sort(date_list):
    if len(data_list)<=1:
        return data_list
    middle = int(len(data_list) / 2)
    left = merge_sort(data_list[:middle])
    right = merge_sort(data_list[middle:])
    merged = []
    while left and right:
        merged.append(left.pop(0) if left [0] <= right[0] else right.pop(0))
        merged.extend(right if right else left )
        return merged

    data_list = [random.randint(1,100) for _ in range(50)]
    print(merge_sort(data_list))
#猜数字游戏
import random

secret = random.randint(1,100)
print('''猜数游戏!我想了一个1-100的整数,你最多可以猜6次,看看能猜出来吗?''')
tries = 1
while tries <= 6:
 guess = int(input("1-100的整数,第%d次猜,请输入:" %(tries,)))
 if guess == secret:
    print("恭喜答对了!你只猜了%d次! \n 就是这个:%d! " %(tries,secret))
    break
 elif guess > secret:
    print("不好意思,你的数大了一点儿!")
 else:
     print("不好意思,你的数小了一点儿!")
 tries += 1
else:
    print("哎呀!怎么也没猜中!再见!")

二、报错

1、invalid syntax:空格缩进不对(参考文章)
2、猜数字游戏 is not allowed to run in parallel. Would you like to stop the running one?(参考文章

image.png
image.png
上一篇下一篇

猜你喜欢

热点阅读