2024-01-14 12:53:07 | 我爱编程网
代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
b = 0
for a in range(101,201):
k = 0
for i in range(2,a):
if a % i == 0 :
k += 1
if k == 0 :
print a
b +=1
print "素数一共有",b,"个"
扩展资料:
Python语言的风格:
Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言。
设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。
这在由Tim Peters写的Python格言(称为The Zen of Python)里面表述为:There should be one-- and preferably only one --obvious way to do it. 这正好和Perl语言(另一种功能类似的高级动态语言)的中心思想TMTOWTDI(There's More Than One Way To Do It)完全相反。
Python的作者有意的设计限制性很强的语法,使得不好的编程习惯(例如if语句的下一行不向右缩进)都不能通过编译。其中很重要的一项就是Python的缩进规则。
一个和其他大多数语言(如C)的区别就是,一个模块的界限,完全是由每行的首字符在这一行的位置来决定的(而C语言是用一对花括号{}来明确的定出模块的边界的,与字符的位置毫无关系)。这一点曾经引起过争议。
因为自从C这类的语言诞生后,语言的语法含义与字符的排列方式分离开来,曾经被认为是一种程序语言的进步。不过不可否认的是,通过强制程序员们缩进(包括if,for和函数定义等所有需要使用模块的地方),Python确实使得程序更加清晰和美观。
核心代码给你,具体的功能还需要自己完善。
import time, random
class GuessNum:
def __init__(self):
self._num = ''
self.input_num = []
self.count = 1 #猜对所用次数
self.sec = 0 #猜对所用时间
self._generate_num()
def _generate_num(self): #产生不重复的四个数字
seq_zton = list(range(10))
for i in range(0, 4):
a = str(random.choice(seq_zton)) #选出一个数字
self._num += a
seq_zton.remove(int(a)) #注意a的类型
self.sec = time.clock() #开始计时
def check_answer(self):
return self._num
def check_input(self):
num_pos, num_value = 0, 0 #位置对和数值对的分别的个数
tmp = input("Please input the number you guess(No repetition),or 'c' to check the answer:")
if tmp == 'c':
print(self.check_answer())
tof = self.check_input()
return tof
elif not tmp.isalnum or not len(tmp) == 4:
print("Wrong format!")
tof = self.check_input() #需要优化
return tof
self.input_num = list(tmp)
lst_temp = list(self._num)
if self.input_num == lst_temp: #猜对
self.prt_vic()
return True
for i in lst_temp:
if i in self.input_num:
if lst_temp.index(i) == self.input_num.index(i): #位置也相同
num_pos += 1
num_value += 1
else:
num_value += 1
self.prt_state(num_pos, num_value)
self.count += 1
return False
def prt_state(self, num_pos, num_value):
print("You've got %d numbers with the right position and %d numbers with the right value only" % (num_pos, num_value))
def prt_vic(self):
t = time.clock()
self.sec = t - self.sec
print("Congratulations!You have successfully got the right number!")
print("%d times and %.2f sec in total to get the right answer" % (self.count, self.sec))
gn = GuessNum()
while True:
ss = gn.check_input()
if ss:
b = input("Continue? y/n:")
if b == 'n':
break
else:
gn = GuessNum()
continue我爱编程网
import random
num = random.randint(0, 100) #
随机数
N = 0 #访问次数
while True:
N += 1
x = int(input())
if x == num:
print("猜中了,用了{}次".format(N))
break
if x > num:
print("太大了")
else:
print("太小了")
2024-01-01 09:58:48
2024-01-02 22:06:16
2024-01-01 04:24:22
2023-12-23 12:08:32
2023-09-13 13:02:53
2024-01-08 06:28:32