Open HELLO-NIKHIL opened 3 years ago
Hi Nikhil
The statement some_random_character = rand(0, 127)
generates a random number ranging from 0 to 127. This is called inside a loop so that in every iteration, a new number is generated. The range of 0 to 127 is taken because of the ASCII characters range. Every number from 0 to 127 represents a character (like 65 represents A, 32 represents space). Notice how chr(some_random_character)
is used to convert a number to a character.
In other words, in each iteration, a random number is generated, that number is used to get the character which we will try to match with the expected character.
I have updated the method to make it more readable and standardised.
def print_string(current_string, expected_character):
while True:
some_random_character = rand(0, 127)
print("\r" + current_string + chr(some_random_character), end="")
sleep(0.1) # Comment this line to see the result instantly
if chr(some_random_character) == expected_character:
break
i want to know only one thing: why line 14 is important?
as you have already written the statement in line 8 so, why we have to write the statement after the break(line 14)
I was trying to use a do-while loop here. So, I initialized some_random_character
once before the body of the while loop begins, and then, update it to a new random number in each iteration of the loop.
In the function print_string()
, I am trying to generate a new random character infinite number of times until I get the expected character. For that, in every loop iteration, I would require a new character to match with expected_character
. So, statement 14 helps me to achieve that. It helps me to generate a new random character in each iteration of the while loop. Notice that statement 8 is outside the loop, while statement 14 is inside the loop. Statement 8 can be assumed as initialization, and statement 14 as an update command.
Also, as mentioned above, I have updated the function to make it easy and more readable.
from random import randrange as rand from time import sleep
A very beautiful function which will keep printing a string with a random character, until the expected character
is drawn
def print_string(current_string, expected_character): some_random_character = rand(0, 120) while True: print("\r" +current_string + chr(some_random_character), end="") sleep(0.001) # Comment this line to see the result instantly if chr(some_random_character) == expected_character: break some_random_character = rand(0, 120)
my_string = "Hello World" current_str = ""
Try to get the matching character for every character in the string. Good Luck!
for letter in my_string: print_string(current_str, letter) current_str += letter