Tuesday, March 12, 2024

starting of Libraries

 

Libraries

Libraries are collections of code that other people have written. Video games often use massive libraries (for example: game engines) to create the epic water reflections, 3-D graphics, etc.

We are going to start a bit smaller by just generating random numbers. (After all, random numbers are the basis of most games).

Random Library

We can use a library by writing import and then the library name.
This should always be one of the first lines of code.

Let's import a library that will generate random numbers:  

import random

How random works 

In the code below, we have created a variable, 'myNumber'. making it equal to a random number given to  by the randint (random integer) library. I add the lowest number (1) and the highest number (100) that can be picked and the computer will generate a number at random.

import random
myNumber = random.randint(1,100)
print(myNumber)

The way libraries work. The names of functions and variables in libraries may be similar to the names I chose for my functions and variables. The way to access functions and variables in other libraries is to put random. in front of the library name.


Now the computer knows to "go in the random library, find randint, and give me a number between 1-100."

import random
for i in range(10):
myNumber = random.randint(1, 100)
  print(myNumber)

Number guess challenge :-
Make the number generator completely random between 1 and 1,000,000. Now, the game will always have the user guess a random number each time (now the user can't cheat...
Totally Random One-Million-to-One
What is your guess?: 500000
Too low
What is your guess?: 750000
Too high
What is your guess?: 600000
Too low
What is your guess?: 650000
Correct!
It took you 4 guesses to get the number correct.
Click 'run' to try again with a different number.

print("Totally Random One-Million-To-One")
print()
import random
rand_number= random.randint(1,10000)
attempt=1
for i in range(1000): 
  guess_number= int(input("Guess a number between 1 to 10000:"))
  if rand_number == guess_number :
    print("you guess it right ")
    attempt += 1
    break
  elif rand_number > guess_number and rand_number - guess_number>5000:
    print("you guess it wrong and it is too low ")
    attempt += 1
    #continue
  elif rand_number > guess_number and rand_number - guess_number<=500:
    print("you guess it wrong and it is low ")
    attempt += 1
    #continue
  elif rand_number < guess_number and  guess_number-rand_number >5000:
    print("you guess it wrong and it is too high")
    attempt += 1
    #continue
  elif rand_number < guess_number and rand_number - guess_number<=500:
    print("you guess it wrong and it is high ")
    attempt += 1
    #continue
print("total attempt is",attempt)

No comments:

Post a Comment

  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...