Skip to content

Instantly share code, notes, and snippets.

@camh96
Last active November 12, 2017 23:21
Show Gist options
  • Save camh96/e45fac32cfb6c0b8cd09014913badbf2 to your computer and use it in GitHub Desktop.
Save camh96/e45fac32cfb6c0b8cd09014913badbf2 to your computer and use it in GitHub Desktop.
James Andersen python stuff
__author__ = 'Cam Hovell'
var = True
while var:
my_input = input('Enter a letter: ')
my_input = my_input.lower() # make input lowercase so easier to make logic for it
if my_input[0] == 'n' or my_input[0] == 'y': # get first letter of input, so y, yes, yeah, nah, nope all work
print('You entered {}'.format(my_input)) # prints formatted, with my_input var as a paramter
var = False # set var to false so we stop looping
else:
print('Try again') #any other input, loop again
input()
__author__ = 'Cam Hovell' # use a header to attribute the author of the code
from random import randint # import just randint method from random class
my_num = randint(1,10) # get random integer between 1 and 10 and assign it to my_num variable
notGuessed = True # set loop variable to True
count = 0 # initalize counter to see how many attempts it took
while notGuessed: #while True, the number hasn't been guessed
count +=1 # increment guess counter by 1 each time the loop is iterated
try: #use a try/except block to catch a ValueError, for example the user may enter a value that's not an integer, and when Python tries to cast it to an integer, it will break
guess = int(input('Enter a number between 1 and 10: ')) #get user input as an integer and store it in a variable called guess
if guess == my_num: #check strict equality between guess and random number
print('{} is correct! It took you {} attempts'.format(my_num, count)) # when number is guessed, print message displaying what number was and how many attempts it took
break # Answer was guessed, we can exit out of the loop using break
else:
print('Nope, try again') # If num is wrong try again
except ValueError: #if a ValueError is returned, tell the user the input was invalid, loop back to try again
print('Invalid value entered. Try again')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment