alb="abcdefghijklmnopqrstuvwxyz"
number="0123456789"
n1,n2,n3,n4=0,0,0,0 #n1、n2、n3分别统计数字、字母、空格和其它字符的个数
str=input("Enter your string:")
for c in str:
if c in alb:
n1+=1
elif c in number:
n2+=1
elif c==' ':
n3+=1
else:
n4+=1
print("The {}-character-string has:\n".format(len(str))
+"{} letters\n".format(n1)
+"{} numbers\n".format(n2)
+"{} ' '\n".format(n3)
+"{} other characters.".format(n4))
a=eval(input("Input the 1st number:"))
b=eval(input("Input the 2nd number:"))
div =1
for i in range(2,min(a,b)+1):
if a%i==0 and b%i==0:
div=i
mul=int(a*b/div)
print("For {} and {}:".format(a,b)+
"the greatest common divisor is {}; ".format(div)+
"the lowest common multiple is {}.".format(mul))
import random
x=random.randint(0,100)
while True:
a=input("Enter a number you guess between 0 and 100:")
try:
if eval(a)>100 or eval(a)<0:
print("Your number is out of range! Try again!")
continue
else:
if eval(a)>x:
print("Your number is too large, try again!")
continue
elif eval(a)<x:
print("Your number is too low, try again!")
else:
print("Congratulation! Your number {} is correct!".format(x))
break
except TypeError:
print("Wrong format!")
except NameError:
print("Wrong format!")
import random
a,b,c="car","goat1","goat2" #a、b、c代表三扇门
sum=1000000 #样本量
#不提前开门的情况:
win1=0
for i in range(sum):
choice=random.choice([a,b,c])
if choice=='car':
win1+=1
print("The rate of winning on the 1st condition is {}".format(win1/sum))
#提前开门且改变选择的情况:
win2=0
for i in range(sum):
choice=random.choice([a,b,c])
if choice=='car':
#prdoor=b/c
choice=c #此时选b和c都一样
elif choice=='goat1':
#prdoor=c
choice=a
else:
#prdoor=b
choice=a
if choice=='car':
win2+=1
print("The rate of winning on the 2nd condition is {}".format(win2/sum))
输出结果:
The rate of winning on the 1st condition is 0.332045
The rate of winning on the 2nd condition is 0.667128