Convert program from QBasic to Python

China☆狼群 提交于 2019-12-10 13:23:13

问题


Im trying to convert a program that I made in Basic! (QBASIC on iOS) to Python. I am slowly working my way through Python for Dummies but I am stuck on how to convert FOR loops. Can someone help? Bellow is the QB code.

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

It is a program that me and my son made on Basic! (QBasic for iOS) that displays all the prime numbers up to the limit entered by the user with some added parts that skip obvious non-prime numbers. Oh and it includes a little speed check that we used to see the difference between iPhone and iPad processors.


回答1:


FOR posprime = 3 TO limit STEP 2

Above line could be translated into following Python code (limit exclusive):

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

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



来源:https://stackoverflow.com/questions/17113886/convert-program-from-qbasic-to-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!