【网安别学成开发】之——python篇

经典入门编程题

1.猜数字

经典的猜数字游戏,几乎所有人学编程时都会做。

功能描述: 随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了,直到用户猜中。

#!/usr/bin/env python3

import random

result = random.randint(1,999)

while True:
  num = int(input("please input number between 0-999:"))
  
  if num == result:
    print ("you are right")
    break
  elif num > result:
    print("high")
  else :
    print("low")

2. FizzBuzz

另一道经典编程题。

功能描述:遍历并打印0到100,如果数字能被3整除,显示Fizz;如果数字能被5整除,显示Buzz;如果能同时被3和5整除,就显示FizzBuzz。结果应该类似:0,1,2,Fizz,4,Buzz,6……14,FizzBuzz,16……

for num in range(101):
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz", end=", ")
    elif num % 3 == 0:
        print("Fizz", end=", ")
    elif num % 5 == 0:
        print("Buzz", end=", ")
    else:
        print(num, end=", ")
#! /usr/bin/env python3

num = 0
while num < 100:
  num += 1
  if num % 3 == 0 && num % 5 == 0:
    print("FizzBuzz".",")
  elif num % 3 == 0:
    print("Fizz".",")
  elif num % 5 == 0:
    print("Buzz".",")
  else:
    print(num.",")
while num =100:
    print("Buzz")
    break

3.猜数字的AI

和猜数字一样,不过这次是设计一个能猜数字的AI

功能描述:用户输入一个单位以内的数字,AI要用最少的次数猜中,并且显示出猜的次数和数字。

import random

def guess_number():
    low = 1
    high = 100  # 可根据需要调整上下限

    target = int(input("请输入一个1到100之间的数字:"))
    count = 0

    while True:
        guess = random.randint(low, high)
        count += 1

        print("AI猜的数字是:", guess)

        if guess == target:
            print("AI猜中了!猜的次数是:", count)
            break
        elif guess < target:
            print("AI猜的数字太小了!")
            low = guess + 1
        else:
            print("AI猜的数字太大了!")
            high = guess - 1

guess_number()
#!/usr/bin/env python3

import random

answer = random.randint(0,999)

guess = random.randint(0,999)
count = 0

while True:
    if guess < answer:
        print("AI guess number is ",guess)
        print("but it is low")
        guess = random.randint(guess,999)
        count += 1
    elif guess > answer :
        print("AI guess number is ",guess)
        print("but it is high")
        guess = random.randint(0,guess)
        count += 1
    else :
        print ("AI guess number is ",guess)
        print("it is right ")
        count += 1
        break

print("it guess ",count,"times")

你可能感兴趣的:(python,开发语言,前端)