课后作业1

课后作业1

  • 设计”过7游戏“的程序,打印出1-100之间除了含7和7的倍数之外的所有数字
for i in range(1, 101):
    if i % 7 == 0 or i % 10 == 7 or i // 10 == 7:
        continue
    print(i, end=' ')
    
1 2 3 4 5 6 8 9 10 11 12 13 15 16 18 19 20 22 23 24 25 26 29 30 31 32 33 34 36 38 39 40 41 43 44 45 46 48 50 51 52 53 54 55 58 59 60 61 62 64 65 66 68 69 80 81 82 83 85 86 88 89 90 92 93 94 95 96 99 100     
  • 编写程序用户登录且仅有三次机会(if 和 for)
uname = 'liyue'
password = '4396'
for i in range(3):
    uname1 = input("请输入用户名:")
    password1 = input("请输入密码:")
    if uname1 == uname and password1 == password:
        print("输入正确")
        break
    else:
        print("用户名密码错误,还有", 2 - i, "次机会")
        
        
请输入用户名:liyue
请输入密码:4396
输入正确
  • 编写程序实现,判断一串字符串是否为有效变量名。
import keyword
str1 = input("请输入变量名:")
if str1 in keyword.kwlist:
    print('与关键字重复,无效变量名')
else:
    if str1[0] == '_' or 'Z' >= str1[0] >= 'A' or 'z' >= str1[0] >= 'a':
        for i in str1:
            if i == '_' or '9' >= i >= '0' or 'Z' >= i >= 'A' or 'z' >= i >= 'a':
                continue
            else:
                print("无效字符,存在特殊字符")
                break
        else:
            print('有效变量名')
    else:
        print('无效变量名,第一个字符必须为_,数字,字母')
  • 最多猜10次数字的游戏,猜测范围1~100,根据input内容提示猜大或者猜小,如果猜中,结束循环
import random
num0 = random.randint(1,100)
for i in range(10):
    num1 = int(input("请猜测数字:"))
    if num1 == num0:
        print("回答正确")
        break
    elif num1 > num0:
        print("偏大")
    elif num1 < num0:
        print("偏小")
  • 使用while循环实现输出2-3+4-5+6…+100的和
flag = 1
sum1 = 0
count = 2
while count <= 100:
    sum1 += count * flag
    flag *= -1
    count += 1
print(sum1)

51
  • 使用循环实现九九乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print(i, '*', j, '=', i * j, end=' ')
    print()
1 * 1 = 1 
2 * 1 = 2 2 * 2 = 4 
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 
  • 已知列表li=[22478,24066,23398,38498],利用字符串拼接及遍历,输出结果“城市学院”
str1 = ''
li = [22478,24066,23398,38498]
for i in li:
    str1 += chr(i)
print(str1)

城市学院

你可能感兴趣的:(python作业)