将程序从QBasic转换为Python

时间:2013-06-14 17:14:33

标签: python qbasic

我试图转换我在Basic中制作的程序! (iOS上的QBASIC)到Python。我正在慢慢地通过Python for Dummies,但我仍然坚持如何转换FOR循环。有人可以帮忙吗?贝娄是QB代码。

REM Prime Numbers v2

REM Av 2.2 seconds for 1000
REM Av 5.3 seconds for 2000

INPUT "Prime numbers upto";limit
PRINT
t1 = TickCount
PRINT "2 3 ";
count = 2
FOR posprime = 3 TO limit STEP 2
    posfactor = 3
    prime = 1
    GOSUB testing
    IF prime = 1 THEN
        PRINT posprime " ";
        count = count + 1
    END IF
NEXT posprime
t2 = TickCount
PRINT
PRINT
PRINT count " prime numbers found"
PRINT USING "####.#"; "Completed in" t2 - t1 " seconds"
END

testing:
IF posprime/posfactor = INT(posprime/posfactor) THEN
    prime = 0
    RETURN
ELSE
    posfactor = posfactor + 2
    IF posfactor > SQR(posprime) THEN
        RETURN
    ELSE
        GOTO testing

这是我和我儿子在Basic上制作的节目! (QBasic for iOS)显示所有素数,直到用户输入的限制,其中一些附加部分跳过明显的非素数。哦,它包括一点速度检查,我们曾经看到iPhone和iPad处理器之间的区别。

1 个答案:

答案 0 :(得分:4)

FOR posprime = 3 TO limit STEP 2

以上行可以转换为以下Python代码(限制独占):

for posprime in range(3, limit, 2):

http://docs.python.org/2/library/functions.html#range