WSQ06 – pick a number

this time the program has to pick a number at random from 1 to 100 and ask the user to gues the number, after the user makes a guess the program will give hints if the number the user gave is too high or too low in relation with the number picked by the program.

for the program to choose a number at random you can use the random function of python:

import random

and give a variable for the value, if we want a number from 1 to 100 set the range (1,101) because the range goes from the first number to the number before the last.

import random

x = random.randrange(1,101)

with that you should get a random number between 1 and 100. now ask the user for an integer to continue with the program and open a “while” loop so the program doesn’t stop until the number from the user is the same as the random:

y = int(input(“number”))

while y != x:     ——- (“!=” means not equal to)

and to give the hints to help the user use if statements and ask for anothe number:

if y > x:

   print (“too high”)

   y = int(input(“again”))

make another for a number below the random. when the user hits the number tell the program to print it:

print (“correct it is “,y)

if you want to add a counter to know how many times you tried make a variable with 0 and do this inside the while loop:

z = 0

while y != x:

    z += 1

and tell the program to print the result at the end:

print (z)

my code is in github:

https://github.com/nazare52/progra/commit/2515ed92aae442c058c6c1c325ed6bbe2a24cb0d

this video helped me to understand loops in python:

https://www.youtube.com/watch?v=9AJ0uoxtdCQ

 question- how do I tell the program to run again after completing the condition of the while loop?

CC BY 4.0 WSQ06 – pick a number by sergio is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.