Beefing up your Pyglatin code


#1

Hi evry one

Wanted to share my code just to show what you can do to make it better and more official.

# defines whether the user exits or not
exit = 0

# makes sure player puts a valid answer for ans. entered properly is 1 if he/she does.
entered_properly = 0

# defines end of the new word
pyg = 'ay'

# checks to make sure user puts correct choices in
while entered_properly == 0:
  # asks user if he wants to play pyglatin
  ans = raw_input("Would you like to play Pyglatin??!!: ")
  if ans == "y" or ans == "yes":
    print "Okay lets get started! :D"
    entered_properly = 1
  elif ans == "n" or ans == "no":
    print "Aww! Ok press run again if you change your mind. ;("
    entered_properly = 1
    start = 1
    exit = 1
  else:
    print "Please type yes or y if you want to play or no or n to not to."
    print "I'd recommend yes or y. .)"

while exit == 0:

  # get input of a word
  original = raw_input('Enter a word: ')

  # need to check word is not empty and only contains letters
  while len(original) == 0 or not original.isalpha():
    if len(original) == 0: # if empty
      print "Empty"
    else: # contains non-letter characters
      print "Type only alphabetical letters and no spaces or numbers"
    # prompt to type another word    
    original = raw_input("Enter a word: ")

  # get the original word and make them all small letters
  word = original.lower()

  # get the first letter of the word
  first = word[0]

  # construct the new word
  new_word = word[1:len(word)] + first + pyg
  
  # print the new word
  print new_word
  
  # Ask user if he/she would like to play again
  entered_properly = 0
  while entered_properly == 0:
    play_again = raw_input("Would you like to play again?: ")
    if play_again == "y" or play_again == "yes":
      entered_properly = 1
      print "Yay! :D"
    elif play_again == "n" or play_again == "no":
      entered_properly = 1
      exit = 1
      print "Ok bye! :)"
    else:
      print "Please type yes or y if you want to play again or no or n to not to."
      print "I'd recommend yes or y. .)"

#2

i would highly recommend to use Boolean values for variable like exit, entered_properly and so on


#3

good point, i’ll keep that in mind next time


#4

and i would swap variable, let me explain, i would name entered_properly to something like invalid_input and give it an initialize value of True, because then we can do:

while invalid_input:

vs:

while entered_properly == 0:

but you made the program better, just teaching you some simple things to improve even more.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.