4.1 猜数字(含猜测次数)
target = 425
guess, count = 0, 0
while True:
guess = eval(input("请输入一个猜测的整数(1-1000):"))
count += 1
if guess > target:
print("猜大了")
elif guess < target:
print("猜小了")
else:
print("猜对了,总共猜了{}次".format(count))
break
4.2 不同字符统计
s = input()
Eng, num, space, other = 0, 0, 0, 0 #英文,数字,空格,其他
for i in s:
if 'a' <= i <= 'z':
Eng += 1
elif '0' <= i <='9':
num += 1
elif i == " ":
space += 1
else:
other += 1
print(Eng, num, space, other)
4.3 最大公约数和最小公倍数
def gcd_lcm():
a, b = map(int, input().split())
def gcd(x,y): #最大公约数
while y:
x, y = y, x%y
return x
def lcm(x,y): #最小公倍数
return x*y // gcd(x,y)
g, l = gcd(a,b), lcm(a,b)
print("最大公约数是{},最小公倍数是{}".format(g,l))
gcd_lcm()
4.4 猜数游戏续1
import random
target = random.randint(1,1000)
guess = 0
while guess != target:
guess = eval(input("请输入一个整数(1-1000):"))
if guess > target:
print("猜大了")
elif guess < target:
print("猜小了")
else:
print("猜对了")
4.5 猜数游戏续2
import random
target = random.randint(1,1000)
guess = 0
while True:
try:
guess = int(input("请输入一个整数(1-1000):"))
if guess > target:
print("猜大了")
elif guess < target:
print("猜小了")
else:
print("猜对了")
except ValueError:
print("输入内容必须为整数!")