我的代码工作,从它运行我想要它做的事情,但一旦用户正确猜测数字,终端结束,不循环

时间:2017-09-02 18:43:53

标签: python loops while-loop

import random

number = random.randint(1,100)


while True:
    pick = input("Choose a number between 1 and 100. ")
    pick = int(pick)
    if pick == number:
        print("You are correct, great job! ")

    while True:
        if pick > number:
            print("That was too high of a guess. Try again. ")
            break       
        elif pick < number:
            print("That was too low of a guess. Try again. ")
            break

代码以我喜欢的方式运行,但是在一次正确的猜测后停止,并且我想在用户正确猜出数字后重新启动循环

3 个答案:

答案 0 :(得分:2)

使用一次和一次休息:

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-84-93098709c7a5> in <module>()
      1 w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
----> 2 grads, cost = propagate(w, b, X, Y)
      3 print ("dw = " + str(grads["dw"]))
      4 print ("db = " + str(grads["db"]))
      5 print ("cost = " + str(cost))

<ipython-input-82-e28b1a4b33cb> in propagate(w, b, X, Y)
     45     ### END CODE HERE ###
     46 
---> 47     assert(dw.shape == w.shape)
     48     assert(db.dtype == float)
     49     cost = np.squeeze(cost)

AssertionError: 

测试用例:

import random

number = random.randint(1,100)

while True:
    pick = int(input("Choose a number between 1 and 100. "))
    if pick == number:
        print("You are correct, great job! ")
        break # correct guess, break
    elif pick > number:
        print("That was too high of a guess. Try again. ")
    else: # one possibility left, so no need for another elif
        print("That was too low of a guess. Try again. ")


如果您在正确猜测后不想让它停止,请删除中断,然后再次猜测:

Choose a number between 1 and 100. 80
That was too high of a guess. Try again.
Choose a number between 1 and 100. 60
That was too high of a guess. Try again.
Choose a number between 1 and 100. 40
That was too low of a guess. Try again.
Choose a number between 1 and 100. 50
That was too low of a guess. Try again.
Choose a number between 1 and 100. 55
That was too high of a guess. Try again.
Choose a number between 1 and 100. 53
That was too low of a guess. Try again.
Choose a number between 1 and 100. 54
You are correct, great job!

答案 1 :(得分:0)

你需要将随机数生成放在循环中,否则它只会反复测试相同的数字:

import random

while True:
    number = random.randint(1,100)

    pick = input("Choose a number between 1 and 100. ")
    pick = int(pick)
    if pick == number:
        print("You are correct, great job! ")

    while pick != number:
        if pick > number:
            print("That was too high of a guess. Try again. ")
            break
        elif pick < number:
            print("That was too low of a guess. Try again. ")
            break

请注意,我已将while True无限循环替换为正确性测试。

编辑:

但是,您可以进一步简化它:

import random

pick = 0
while True:
    number = random.randint(1,100)

    while pick != number:
        pick = input("Choose a number between 1 and 100. ")
        pick = int(pick)
        if pick == number:
            print("You are correct, great job! ")
            break
        elif pick > number:
            print("That was too high of a guess. Try again. ")
        else:
            print("That was too low of a guess. Try again. ")

答案 2 :(得分:-1)

只需添加继续修复它。我使用数字5来测试代码。

    var renderer    = new THREE.WebGLRenderer({
        antialias   : true
    });
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    renderer.shadowMapEnabled   = true

    var onRenderFcts= [];
    var scene   = new THREE.Scene();
    var camera  = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 100 );
    camera.position.z = 1;

    var light   = new THREE.AmbientLight( 0x222222 )
    scene.add( light )

    var light   = new THREE.DirectionalLight( 0xffffff, 1 )
    light.position.set(5,5,5)
    scene.add( light )
    light.castShadow    = true
    light.shadowCameraNear  = 0.01
    light.shadowCameraFar   = 15
    light.shadowCameraFov   = 45

    light.shadowCameraLeft  = -1
    light.shadowCameraRight =  1
    light.shadowCameraTop   =  1
    light.shadowCameraBottom= -1
    // light.shadowCameraVisible    = true

    light.shadowBias    = 0.001
    light.shadowDarkness    = 0.2

    light.shadowMapWidth    = 1024
    light.shadowMapHeight   = 1024

    //////////////////////////////////////////////////////////////////////////////////
    //      added starfield                         //
    //////////////////////////////////////////////////////////////////////////////////

    var starSphere  = THREEx.Planets.createStarfield()
    scene.add(starSphere)

    //////////////////////////////////////////////////////////////////////////////////
    //      add an object and make it move                  //
    //////////////////////////////////////////////////////////////////////////////////

    // var datGUI   = new dat.GUI()

    var containerEarth  = new THREE.Object3D()
    containerEarth.rotateZ(-23.4 * Math.PI/180)
    containerEarth.position.z   = 0
    scene.add(containerEarth)
    var moonMesh    = THREEx.Planets.createMoon()
    moonMesh.position.set(0.5,0.5,0.5)
    moonMesh.scale.multiplyScalar(1/5)
    moonMesh.receiveShadow  = true
    moonMesh.castShadow = true
    containerEarth.add(moonMesh)

    var earthMesh   = THREEx.Planets.createEarth()
    earthMesh.receiveShadow = true
    earthMesh.castShadow    = true
    containerEarth.add(earthMesh)
    onRenderFcts.push(function(delta, now){
        earthMesh.rotation.y += 1/32 * delta;       
    })

    var geometry    = new THREE.SphereGeometry(50, 32, 32)
    var material    = THREEx.createAtmosphereMaterial()
    material.uniforms.glowColor.value.set(0x00b3ff)
    material.uniforms.coeficient.value  = 0.8
    material.uniforms.power.value       = 2.0
    var mesh    = new THREE.Mesh(geometry, material );
    mesh.scale.multiplyScalar(1.01);
    containerEarth.add( mesh );
    // new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)

    var geometry    = new THREE.SphereGeometry(0.5, 32, 32)
    var material    = THREEx.createAtmosphereMaterial()
    material.side   = THREE.BackSide
    material.uniforms.glowColor.value.set(0x00b3ff)
    material.uniforms.coeficient.value  = 0.5
    material.uniforms.power.value       = 4.0
    var mesh    = new THREE.Mesh(geometry, material );
    mesh.scale.multiplyScalar(1.15);
    containerEarth.add( mesh );
    // new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)

    var earthCloud  = THREEx.Planets.createEarthCloud()
    earthCloud.receiveShadow    = true
    earthCloud.castShadow   = true
    containerEarth.add(earthCloud)
    onRenderFcts.push(function(delta, now){
        earthCloud.rotation.y += 1/8 * delta;       
    })

    //////////////////////////////////////////////////////////////////////////////////
    //      Camera Controls                         //
    //////////////////////////////////////////////////////////////////////////////////
    var mouse   = {x : 0, y : 0}
    document.addEventListener('mousemove', function(event){
        mouse.x = (event.clientX / window.innerWidth ) - 0.5
        mouse.y = (event.clientY / window.innerHeight) - 0.5
    }, false)
    onRenderFcts.push(function(delta, now){
        camera.position.x += (mouse.x*5 - camera.position.x) * (delta*3)
        camera.position.y += (mouse.y*5 - camera.position.y) * (delta*3)
        camera.lookAt( scene.position )
    })





       var marker2 = new THREE.Object3D();
                var loader = new THREE.OBJLoader( );
                loader.load( 'Pin.obj', function ( object2 ) {                 
                    object2.traverse( function ( child ) {
                        if ( child instanceof THREE.Mesh ) {
                            child.material = new THREE.MeshPhongMaterial( { 
                                color: 0x790811, 
                                specular: 0x050505,
                                shininess: 100
                            } );
                        }
                    } );

                    object2.position.set(0.57,-0.15 ,-0.07); // rotating obj should set (X > 0, 0, 0)
                        object2.receiveShadow   = true
    object2.castShadow  = true
    object2.quaternion.setFromUnitVectors(
                    new THREE.Vector3(8, 1, 3.5), new THREE.Vector3(1, 0, 0));
                    object2.scale.set(0.0003,0.0003,0.0003);


                containerEarth.add( object2 );

                });



    scene.add(marker2);


    var rad = Math.PI / 180;

    marker2.quaternion.setFromEuler(
        new THREE.Euler(0, 105 * rad, 45 * rad, "YZX")); 

  navigator.geolocation.watchPosition(function (pos) {


     var lat2 = 42.3125, lon2 = -86.1131;
        marker2.quaternion.setFromEuler(
            new THREE.Euler(45, lon2 * rad, lat2 * rad, "YZX")); 
        });

    //////////////////////////////////////////////////////////////////////////////////
    //      render the scene                        //
    //////////////////////////////////////////////////////////////////////////////////
    onRenderFcts.push(function(){
        renderer.render( scene, camera );       
    })

    //////////////////////////////////////////////////////////////////////////////////
    //      loop runner                         //
    //////////////////////////////////////////////////////////////////////////////////
    var lastTimeMsec= null
    requestAnimationFrame(function animate(nowMsec){
        // keep looping
        requestAnimationFrame( animate );
        // measure time
        lastTimeMsec    = lastTimeMsec || nowMsec-1000/60
        var deltaMsec   = Math.min(200, nowMsec - lastTimeMsec)
        lastTimeMsec    = nowMsec
        // call each update function
        onRenderFcts.forEach(function(onRenderFct){
            onRenderFct(deltaMsec/1000, nowMsec/1000)
        })
    })

我进一步简化了以下代码

import random

number = 5

while True:
    pick = input("Choose a number between 1 and 100. ")
    pick = int(pick)
    if pick == number:
        print("You are correct, great job! ")
        continue

    while True:
        if pick > number:
            print("That was too high of a guess. Try again. ")
            break
        elif pick < number:
            print("That was too low of a guess. Try again. ")
            break