Lesson 12 - Python Programming (Automate the Boring Stuff with Python)

preview_player
Показать описание


Рекомендации по теме
Комментарии
Автор

Thanks again for taking the time to make these videos. Your effort is very much appreciated. Not many people would bother to rewrite code already produced just to assist in understanding. That kind of thing is what makes a difference.

paulbaker
Автор

After a few "what else can I do to improve this", here is what I ended up with:

# Repeatable guess game

import sys

def guess_game():
# Take a guess game

import random

# Generate random number:
print('I am thinking of a number between 1 and 20.')
number = random.randint(1, 20)

# Uncomment to show the number for debugging purposes:
#print('(DEBUGGING) the number is ' + str(number))

# Ask to guess 5 times:
for guesses in range(1, 6):
print('\n' + 'Take a guess:')
try:
guess = int(input())
except ValueError:
print('You must enter a number!')
continue

if guess < 1 or guess > 20:
print('I said between 1 and 20!')
elif guess < number -10:
print('That is way too low!')
elif guess > number + 10:
print('That is way too high!')
elif guess < number:
print('That is too low.')
elif guess > number:
print('That is too high.')
else:
break # guess == number

# Print the result:
if guess == number:
print('\n' + 'Congratulations, ' + name + ', you have guessed my number in ' + str(guesses) + ' guesses!')
else:
print('\n' + 'Sorry, you took too long! The number I was thinking of was ' + str(number) + '.')


# Ask for player name:
print('Hi, what is your name?')
name = input()

# Run the guess game:
print('\n' + 'Hi, ' + name + ', ', end='')
guess_game()

# Ask to play again:
while True:
print('\n' + 'Do you want to guess again?')
answer = input()

if answer == 'yes' or answer == 'Yes':
print('\n' + 'Once again, ', end='')
guess_game()
elif answer == 'no' or answer == 'No':
print('\n' + 'Oh, that is too bad! Bye!')
sys.exit()
else:
print('Please answer yes or no!')

Автор

Good tutorial! I added some additional functions, such as printing an error if the user enters a number higher than 20 or lower than one, and a different error if they enter something else entirely. Great lessons so far, Al!

AmericanDash
Автор

def main():

import random, sys
print('Hello, what is your name?')
name = input()

print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())

if guess < 0:
print('That number is less than 1. Pick another.')
elif guess < secretNumber:
print('Your guess was too low.')
elif guess > 20:
print('That number is more than 20. Pick another.')
elif guess > secretNumber:
print('Your guess was too high.')
else:
break

def restart():
print('Do you want to play again?')
print('Press y to continue. Press n to quit.')

if guessesTaken == 1:
print('Wow, ' + name + '! You got it in the first try.')
restart()
elif guess == secretNumber:
print('Congratulations, ' + name + '! You made it in ' + str(guessesTaken) + ' guesses!')
restart()
else:
print('Nope, the number I was thinking of was ' + str(secretNumber) + '.')
restart()

while True:
while True:
answer = input()
if answer in ('y', 'n'):
break
print('Invalid input.')
if answer == 'y':
main()
else:
print('Goodbye.')
sys.exit()
main()

lolmomz
Автор

This made me so happy! So as soon as you said what the goal of this lesson was I immediately opened up my own window and attempted it to see if I could do it without just copying your code. This is what I came up with:

import sys
import random

tries = 0

secretNumber = random.randint(1, 10)

print('Hello, what is your name?')
name = input()

print('Hello ' + name + ', would you like to play a game?')
response = input()

if response == 'yes':
print('Okay, I am thinking of a number between 1 and 10.')
print('Have a guess: ')
answer = input()
tries += 1
if answer == secretNumber:
print('You guessed it! The number was ' + str(secretNumber) +
' and it only took you ' + str(tries) + 'tries.')

while answer != secretNumber and tries <= 6:
print('Try again. ')
answer = input()
tries += 1
if int(answer) < secretNumber:
print('Guess higher.')
elif int(answer) == secretNumber:
print('You guessed it! The number was ' + str(secretNumber) +
' and it only took you ' + str(tries) + ' tries.')
sys.exit()
elif int(answer) > secretNumber:
print('Guess lower.')

else:
print('Perhaps we can play another time then.')
sys.exit()

print('You ran out of guesses! The number I was thinking of was ' + str(secretNumber) + '.')

It's a bit spaghetti but it works and I was really happy with it, especially after spending a good amount of time working out bugs. I only just started trying to learn how to program like two weeks ago so this is a major step for me. Thanks so much Al! Your tutorials are amazing and I look forward to watching the rest of them!

brycegriffin
Автор

i copied the base of this and started modifying on a low level, i added exceptions to keep from crashing as well as a new game option that keeps the inputted name. i might try adding different things and see what i can do with this, great video series, easy to follow.

dylanking
Автор

You can cast it twice to allow it to be more forgiving:
guess = int(float(input()))
It will truncate the number to an integer

delengen
Автор

Lots of extra pieces one could add on, a specific outcome should you guess correctly on the 1st try, for example. Also, outcomes for guesses that are out of the specified range (greater than 20, negative numbers) or for tries that are not integers at all (Try, except).

Gregorydeon
Автор

The player will always win if they are smart about their number choices. It only takes 5 guesses to win every time. log2(19) < 5

kryler
Автор

Your voice sounds awsome. It is like the world is at peace and everything will be okay.

liluna
Автор

we can also add a if, else function so when we guess on the first attempt we get a message ending with "... in 1 guess" and not "... in 1 guesses" :)

if guess == secretnumber:
if guesstaken == 1:
print("Good job, " + name + "! You guessed the number in " + str(guesstaken) + " guess")
else:
print("Good job, " + name + "! You guessed the number in " + str(guesstaken) + " guesses")
else:
print("Nope, the number I was thinking of was " + str(secretnumber))

masterlouis
Автор

i had so much fun with this, when you said we could do this with everything we've learned, I paused the video and only referenced from what was sent in the shell and tried to work backwards. It ended up bothering me that guesses could be made outside the 1 to 20 range, so i had it send a passive aggressive comment in that circumstance. And also it bothered me when the program couldn't differentiate between a singular or plural amount of guesses lmfao, so I used an extra two lines so that the if-elif statements could account for it.

dandyspacedandy
Автор

I heard his idea and decided to code this on my own then come back and compare. This is what i came up with. I used a while True: line instead of a For loop. Opinions appreciated.

import random

secret_number = random.randint(1, 20)

print("Hello, what is your name?")
name_input = input("Name: ")
print("Welcome to the Random Number game, " + name_input + "!")

while True:
print("In this game you will try to guess the number, from 1 to 20, in the least ammount of guesses possible.")

guess_input = input("Enter your guess: ")

if int(guess_input) == secret_number:
print("You got the number correct! The number is " + str(secret_number) + ".")
break

if int(guess_input) < 1:
print("Invalid input (Must be a number between 1 and 20)")
elif int(guess_input) > 20:
print("Invalid input (Must be a number between 1 and 20)")
break

if int(guess_input) > secret_number:
print("Your guess was too high! Guess again!")
elif int(guess_input) < secret_number:
print("Your guess was too low! Guess again!")

BLINC
Автор

This is better:
import random
sNum = random.randint (1, 100)
print ('Hello, I am thinking of a random number from 1 to 100')
print ('Guess:')
guess = int(input())
while guess != sNum:
print ('Guess again')
if guess > sNum: #optional... if you remove an optional line, remove them all.
print ('Too high') #optional
elif guess < sNum: #optional
print ('Too low') #optional
guess = int(input())
if guess == sNum:
print ('Good Job! I was thinking of ' + str(sNum) + '.')

Joenah
Автор

I did it with a while loop. Here is the code. Mind you, i have taken an Geargia Tech online course via edx.


print("hello what is your name")
name = input()
print("hello "+name+" can you guess a number between 1 and 20?")
import random
secret_number = random.randint(1, 20)
i = 0
while i < 6:
print("Type in some number")
number = int(input())
if number > secret_number:
print("your guess is too high")
elif number < secret_number:
print("your guess is too low")
else:
print("your guess is correct")
break
i += 1
print("you are out of tries, the number i was thinking of is " + str(secret_number))

bozhidarmadzharov
Автор

I've made a guessing game that trolls the player, has a scoring system and a secret ending.
If the player does not guess the number right in 3 tries, it asks them if they want to know the secret number.
If they say 'Y', the machine suggests the secret number and lets the player input it. If they input it, the program will make the exit message appear and no points are scored.
If after knowing the secret number they keep inputting the wrong answer, the machine keeps insisting on the secret number until 10 tries, where it also makes the exit window pop out.
The main way of winning and getting a score is by answering right in the first 3 tries or saying anything but 'Y' to the cheat temptation (I'm struggling making it multiple choice). Your score is your secret number divided by the times you tried. But if you couldn't guess it in the first 3 tries, you get deducted every extra try as well.
There's also a secret ending if you input '777' after knowing the secret number which allows scoring points based on the secret number divided by 777 multiplied by the length of the name written at the beginning of the game.
I've actually spent more time making this simpler, it was working before in a more convoluted way.
I'm having a lot of fun with this (!) Never thought I'd get into playing with code. Thanks for the course, I got it from udemy.

import random
print ('Hello, please present yourself')
name = input()
print('Greetings, ' + name + ', want to play a game? Y/N')
answer1 = input()
if answer1 == 'Y':
print ('Very good')
else:
print ('You cannot escape')
numb = random.randint (1, 50)
print ('I am thinking of a number between 1 and 50')

#troll hint, reveals secret number but makes the game end if that number is input
def timesguess2():
try:
for stubbornness in range (1, 10):
guess3 = int(input())
if guess3 == numb:
print('Why would you trust me?')
exit()
elif stubbornness == 5:
print('I am telling you, it is ' + str(numb))
elif stubbornness == 9:
print('Why do you not believe me? ' + str(numb) +' is your answer')
quit()
elif guess3 == 777:
print('Secret Ending unlocked')
special_score =
print('You scored ' + special_score + ' point(s)')
elif guess3 > numb:
print ('Too high')
elif guess3 < numb:
print('Too low')

except ValueError:
print ('You are not very good at instructions either')

#first try
def firsttry():
try:
global try1
for try1 in range (1, 4):
print('Take a guess')
guess1 = int(input())
if guess1 == numb:
print('Very good, it only took ' + str(try1) + ' tries(s)')
print('You scored ' + str(numb/try1) + ' points')
elif guess1 < numb:
print('Too low')
elif guess1 > numb:
print ('Too high')
else:
break
except ValueError:
print ('Seems you do not understand the concept of number')

#second try
def secondtry():
try:
for try2 in range (1, 6):
global guess2
print('Take a guess')
guess2 = int(input())
if guess2 == numb:
print('Took you long enough, specifically ' + str(try1+try2) + ' tries(s)')
print('You scored ' + str(numb/try2+try1) + ' points')
break
elif guess2 < numb:
print('Too low')
elif guess2 > numb:
print ('Too high')
else:
break
except ValueError:
print ('Seems you do not understand the concept of number')

firsttry()

print ('You do not seem very good at this, do you want the answer? Y/N?')
answer2 = input()
if answer2 == 'Y':
print ('I would go for ' + str(numb))
timesguess2()
else:
print('You are so brave, then try again')
secondtry()

print('Try harder next time')

Sakenra
Автор

if guessesTaken == 1:
print('Very good job, ' + name + '! You guessed my number in the first try!')
elif guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')

UnknownUser
Автор

#Take a Guess Game

import random

print('Olá, como te chamas?')
name = input()

print ('Olá ' + name + ' estou a pensar num número entre 1 e 20 !')
number = random.randint(1, 20)


for tentativas in range(1, 7):
print('Tenta adivinhar!!')
tentativa = int(input())

if tentativa > number :
print('Número muito alto!')

if tentativa > 20 :
print('Tem que inserir uma tentativa entre os números 1 e 20 !')

elif tentativa > 20:
print('Tem que inserir uma tentativa entre os números 1 e 20 !')


elif tentativa < number :
print('Número muito baixo!')

if tentativa > 20 :
print('Tem que inserir uma tentativa entre os números 1 e 20 !')

elif tentativa > 20 :
print('Tem que inserir uma tentativa entre os números 1 e 20 !')



else:

break # acertou

if tentativas == 1 :
print('Parabéns, adiviinhaste o meu número a primeira!')

elif tentativa == number :
print('Parabéns, ' + name + ' você acertou, em ' + str(tentativas) + ' tentativas !')


else :

print('Você não acertou em 6 tentativas possiveis, o número correcto era o número ' + str(number) + ' !')

duarteborges
Автор

This code can handle string or decimal and still only counts the integer guesses

import random
print('hello what is your name?')
name = input()
print('Well ' + name +' i am thinking of a number between 1 and 20')
num = random.randint(1, 20)
print('secret number is ' + str(num))
def game(i):
try: #input validation for string or decimal
while i < 7:
print('Take a guess')
guess = int(input())
if guess < num:
i = i+ 1
print('Your guess is too low'+ str(i))
elif guess >num:
i = i+ 1
print('Your guess is too high'+ str(i))
else:
break
if num == guess:
print('You took '+ str(i) +' guesses')
else:
print('Nope the number i was thinking is '+ str(num))
except ValueError:
print('please input a valid number')
game(i)

game(1)

AGRIMJAIN
Автор

These instructions have helped me the most so far thank u sm

sarvenaz