Friday, November 8, 2013

Python Lab


Scripting is my very least skill in computers. I found bash to be very difficult to learn but I have somewhat knowledge about it. Comparing to python, I would say this is easier and faster to learn. Although, this is still a challenge for me.

I looked at some of the blog posts to help me understand the 'guess' script and I found amartinenco's script to be the most understandable. So I tried to modifying my script and trying it on my own and this is what I came up:

#!/usr/bin/python
#
# Modify this script to be a number-guessing
# game.
# 1. The secret number should be random (1-100)
# 2. Input should be handled if it's not numeric
# 3. The user should be asked to guess until they
#    get the right number.
# 4. When the user guesses the right number, the
#    number of guesses should be printed
#
# Bonus: Make the script give up if the number hasn't
#        been guessed in 15 tries.

# imports sys program to script
import sys
# imports random program to the sript
import random
secret=random.randint(1,100)



game_finished = 0
count = 1
print "Guess the number from 1-100. You have 15 tries"

while (game_finished == 0):
  try:
     guess=int(raw_input("Enter a guess: "))

     if guess < 1 or guess > 100:
        print "Must be in the (1-100) range"
     else:
        if guess < secret:
           count = count + 1
       print "Too low!"        
        elif guess > secret:
           count = count + 1
       print "Too high!"        
        else:
           print "Correct!"
           game_finished = 1
           print "It took you %i tries to guess the correct number" % (int(count))
     if count == 16:
       print "number of tries exceeded(15). exiting"
       sys.exit()
  except ValueError:
     print "The entered input is invalid"

The only difference from where the script I got from was the exit script when the tries have been exceeded. Python is easier and more exciting to learn compared to other scripts I have learned. As for the future, I would try to have an in depth look at this language as this would be a great skill for the future.

End.


No comments:

Post a Comment