Python 程式設計/迴圈/解決方案
外觀
< Python 程式設計 | 迴圈
< 返回問題
1. 編寫一個程式,用素數計數。要求使用者輸入一個數字,然後打印出小於該數字的每個素數。
對於這個程式,我們將建立一個包含所有可能的數字列表,直到使用者的輸入,然後使用費馬小定理測試每個數字,驗證它是素數,然後將該素數新增到素數列表中。最後,我們列印素數列表。
註釋:所有素數都滿足費馬小定理,但有些返回的結果是“偽素數”,它們不是素數(例如,341=11*31,在 python 中:(((2**341)-2)%341 == 0)). 有關尋找素數和證明素性的更多資訊
primes = []
# Creates a list that we will throw our prime numbers into.
user = 1 + int(raw_input("What number would you like to count primes up to? "))
# 1 is added on to the user's number so that their number
# is counted.
list = range(2,user)
# 0 and 1 are not prime, but our algorithm registers them
# as prime, so we start with two
for possibility in list:
if ((2**possibility)-2)%possibility == 0:
# Our algorithm (Fermat's little theorem) states
# that if "i" is an integer and i^p-i divides evenly
# into p, p is prime. We are using 2 in place of i.
# See Python Programming/Basic Math for more info.
isprime = True
test = 2
while test < possibility and isprime:
# Here we verify that the number is in fact prime by
# starting at 2 and dividing it by every number lower
# than the potential prime. See comment above.
if (possibility%test) == 0:
# This ends the while loop causing the next number
# to be tested.
isprime = False
test = test + 1
if isprime:
# We add each prime to the primes list.
primes.append(possibility)
print ("The prime numbers from 0 to", user-1, "are: ")
for possibility in primes:
print possibility
# Print out all the primes!
2. 指示使用者從 1 到 100 中選擇一個任意數字,然後在七次嘗試內猜出該數字。每次猜完之後,使用者必須告訴您他們選擇的數字是比您的猜測高、低還是等於您的猜測。
print "\nIn your head, pick a number between 1 and 100, \ni'll guess it with some hints:\n"
letsstart = raw_input("ready? input anything...\n")
uppers = 100
lowers = 0
guess = 50
boom = 0
for c in range(1,10):
if boom == 0:
print "guess: ",guess
answer = raw_input("Was that\na. too low\nb. too high\nc. thats right!\n")
if answer == "c":
print "I got it! Thanks for playing.\n"
boom = 1
elif answer == "a":
lowers = guess
blah = int((uppers-guess)/2)
guess = guess + blah
elif answer == "b":
uppers = guess
blash = int((guess-lowers)/2)
guess = guess-blash
"其他"
Python 的 9 年級作業是這樣的,這是一個猜數字的遊戲,包括了 python 的大多數方面。
print("welcome")
YourName = input("what is your name?")
print("hi",YourName,"do you want to play my game?")
import random
number = random.randrange(100)
guess =int(input("please guess the number"))
if guess == number:
print("You've WON!!!!!")
elif guess > number:
print("Too Big!")
else:
print("Too Low!")
while guess!= number:
guess =int(input("please guess the number again"))
if guess == number:
print("You've Won!!")
elif guess > number:
print("too big")
else:
print("too low")