这一章比较简单,和中学时期学的流程图类似,值得一提的是程序的异常处理try-except,可以让程序有更好的用户体验。书前面的基础解释有什么问题可以私信我讨论!
import random
target = random.randint(1,1000)
count = 0
while True:
guess = eval(input('请输入一个猜测的整数(1-1000):'))
count = count + 1
if guess > target:
print('猜大了')
elif guess < target:
print('猜小了')
else:
print('猜对了')
break
print("此轮的猜测次数是:", count)
#改良版:由于使用eval函数获得用户输出,可能会出现用户输入非数字产生运行错误
import random
target = random.randint(1,1000)
count = 0
while True:
try:
guess = eval(input('请输入一个猜测的整数(1-1000):'))
except:
print('输入有误,请重试,不计入次数哦!')
continue
count = count + 1
if guess > target:
print('猜大了')
elif guess < target:
print('猜小了')
else:
print('猜对了')
break
print("此轮的猜测次数是:", count)
n = int(input("请输入一个年份:"))
if n%4==0 and n%100!=0 or n%400==0:
print("是闰年")
else:
print("不是闰年")
# 2
a = int(input("请输入第一个整数:"))
b = int(input("请输入第二个整数:"))
x, y = a, b
if x >= y:
pass
else:
x, y = y, x
while x%y != 0:
x, y = y, x%y
print("最大公约数为:{},最小公倍数为{}".format(y, int(a*b/y)))
x = input("请输入一串字符:")
counts = {}
for i in x:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse = True)
for i in range(len(items)):
word, counts = items[i]
print("{0:<10}{1:>5}".format(word,counts))
import random
target = random.randint(1,1000)
count = 0
while True:
try:
guess = eval(input('请输入一个猜测的整数(1-1000):'))
except:
print('输入有误,退出程序')
break
count = count + 1
if guess > target:
print('猜大了')
elif guess < target:
print('猜小了')
else:
print('猜对了')
print("此轮的猜测次数是:", count)
from random import*
times = 1000000
my_first_choice_n=0#初始化不改选择的次数
my_change_choice_n=0#初始化更改选择的次数
for i in range(times):
car_inDoor = randint(0,2)#车在随机的门后面
my_guess = randint(0,2)
if car_inDoor == my_guess:
my_first_choice_n+=1#猜对了
else:
my_change_choice_n+=1#没猜对,肯定改变选择的猜对了
print("不改选择:{}".format(my_first_choice_n/times))
print("更改选择:{}".format(my_change_choice_n/times))