pythonpython-3.xnumbersreal-time-clock

When I print this python code , only the first code gets executed. please help me fix this issue


# code 1
import time
while True:
    from datetime import datetime
    print(" Time: "+ "%d:%d:%d " % (datetime.now().hour,datetime.now().minute,datetime.now().second),
    end = "\r")
    time.sleep(1)



# code 2
name = input("Your good name please: ")
print("Hi "+name)
print('''Lets Play Guessing number game
    ''')

import random
import math
print("you have only 1 chance to guess the number")
original_no = random.randint(0,10)
player_input = input("Guess a number from 1 to 10: ")
if str(player_input) == original_no:
    print("you have entered the correct number!")
elif str(player_input) != original_no:
    print("you have entered wrong number")
print(str("the correct number is ") + str(original_no))

when the code gets executed, it only prints the code 1 and doesn't print the code 2. I want to display time over the number guessing game. I'm just a beginner ,please help me resolve this issue.


Solution

  • You need to end the while loop, you can do it by simply including a break statement in the loop or just remove while loop in case you want the time to be displayed only once.

    while True:
        from datetime import datetime
        print(" Time: "+ "%d:%d:%d " % (datetime.now().hour,datetime.now().minute,datetime.now().second),
        end = "\r")
        break
        time.sleep(1)