How do I clear the screen in Python 3? - python-3.x

Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.

It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()

Related

How can I generate new random numbers each time in my while loop in Python for a number game?

I've created a number game where it asks the user if they want to play again and then the loop continues. My program uses import random but I want to know how I'd generate new random numbers without having to make variables each time. (I'm a beginner and I don't know what solution to use pls help)
My code works for the most part it's just that when the loop restarts the same number from the last playthrough repeats so the player ends up getting the same results. Here's my code:
`
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random
random_number_two = random.randint (0, 100)
print(random_number_two)
if random_number_two > random_number_one :
print("You are correct! It was higher!")
play_again_h = input("Would you like to play again? ('Yes'/'No') ")
if play_again_h == 'Yes' or play_again_h == 'yes' :
continue
else:
break
else:
play_again = input("You were wrong, it was lower. Would you like to play again? ('Yes'/'No') ")
if play_again == 'Yes' or play_again == 'yes' :
continue
else:
break
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
play_again_l = input("Would you like to play again? ('Yes'/'No') ")
if play_again_l == 'Yes' or play_again_l == 'yes' :
continue
else:
break
else:
play_again_2 = input("You were wrong, it was higher. Would you like to play again? ('Yes'/'No') ")
if play_again_2 == 'Yes' or play_again_2 == 'yes' :
continue
else:
break
else:
print("Invalid response. You Lose.")
break
elif start_game == 'No' or start_game == 'no':
print("Okay, maybe next time.")
break
else:
print("Invalid response. You Lose.")
break
`
You have to initialize the random number generator with a seed.
See here: https://stackoverflow.com/a/22639752/11492317
and also: https://stackoverflow.com/a/27276198/11492317
(You wrote, you're a beginner, so I give you some hints for cut a few things short...)
import random
#import time #redundant
def get_random(exclude: int = None):
next_random = exclude
while next_random is exclude:
next_random = random.randint(0, 100)
return next_random
#random.seed(time.time())
random.seed() # uses system time!
username = input("Greetings, what is your name? ")
start_game = None
while start_game is None:
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes'/'No') ".format(username))
if start_game.lower() in ("yes", "y", ""):
print("Let's begin!")
number_for_guess = get_random()
running = True
elif start_game.lower() == "no":
print("Ok, bye!")
running = False
else:
start_game = None
while running:
print(number_for_guess)
next_number = get_random(exclude=number_for_guess)
user_guess = ""
while user_guess.lower() not in list("lh"):
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess.lower() == "h":
print("You guessed higher. Let's see: ")
print(next_number)
if next_number > number_for_guess:
print("You are correct! It was higher!")
else:
print("You were wrong, it was lower.", end=" ")
else:
print("You guessed lower. Let's see: ")
print(next_number)
if next_number < number_for_guess:
print("You are correct! It was lower!")
else:
print("You were wrong, it was higher.", end=" ")
play_again = "-"
while play_again.lower() not in ("yes", "y", "", "no"):
play_again = input("Would you like to play again? ('Yes'/'No') ")
if play_again.lower() == "no":
running = False
print("Well played, bye!")
You are creating random_number_one only once, when the program starts.
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
...
So this number is used all the time:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
86
You are correct! It was higher!
Would you like to play again? ('Yes'/'No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
82
You are correct! It was higher!
Would you like to play again? ('Yes'/'No')
You have to create new random number each time the while loop repeats:
import random
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
random_number_one = random.randint (0, 100) # <-- MOVED HERE
print(random_number_one)
...
Then it will work as you except:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
96
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
7
You were wrong, it was lower. Would you like to play again? ('Yes'/'No') Yes
Let's begin!
67
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: L
You guessed lower. Let's see:
7
You are correct! It was lower!
Would you like to play again? ('Yes'/'No')
Some other small things:
Looks like you missed randint call within the lower option:
...
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
random_number_two = random.randint (0, 100) # missing in your code
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
...
You don't need to import random module each time you want to use function from it:
...
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random # line not needed
random_number_two = random.randint (0, 100)
print(random_number_two)
...
You may change the line:
if user_guess == 'H' or user_guess == 'h':
into:
if user_guess.lower() == 'h':
or:
if user_guess in ('H', 'h'):
Try to split your code into smaller parts with functions.

Guessing random number project

I'm a newbie of coding. I'm trying to create a guessing random number game by python. The thing is I get stuck at limited users by 5 turns guessing only. Here is my code so far. Thank you
print("""
WELCOME TO GUESSING NUMBER GAME!!!
You have 5 turns to guess a random number. Good luck!
""")
def play():
import random
random_numnber = random.randint(0, 20)
guess_count = 0
while True:
try:
guess = int(input("Please enter an integer from 1 to 20: "))
guess_count += 1
except ValueError:
print("Invalid Input\n")
continue
else:
break
while random_numnber != guess and guess_count < 5:
if int(guess) < random_numnber and int(guess_count) < 5:
print("Your number is too low\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) > random_numnber and int(guess_count) < 5:
print("Your number is too high\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) == random_numnber and int(guess_count) < 5:
print("Congratulation! You Win!\n")
break
else:
print("You have guessed 5 times and all Wrong. Good luck on next game!")
break
while True:
answer = input("Do you want to play? ")
if answer == 'yes' or answer == 'y':
play()
elif answer == 'no' or answer == 'n':
break
else:
print("I don't understand\n")
This is how I would go about doing this, I have modified your code and omitted some trivial error handling for non-integer inputs, etc.
The trick is that the code section between the # *** comments will be exited automatically if the guess_count value exceeds the maximum_tries, so we can actually remove a lot of the conditionals you were performing in-line which cluttered the real logic we care about.
You can also see that the only way that we can reach the line where we print "All out of guesses" is if the user has not already guessed the correct number.
Finally, since you mentioned you are just starting out I included a main() function as well as the Pythonic block at the end, which is just a special way to tell Python which part of the program you want to start with when you run the script. Happy coding!
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()

How to access the variable delcared inside a function outside the function in Python 3?

I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')

Why doesn't my hangman game work the way it's supposed to

import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()

How to simplify elif in Python

I don't have a lot of experience with python but I think this can be much simpler. If anything available for the same result. Using a dictionary mapping to functions instead of all those elif maybe?
choice = input("Select an option: ")
if choice == "1":
try:
new_contact = create_contact()
except NotAPhoneNumberException:
print("The phone number entered is invalid, creation aborted!")
else:
contacts[new_contact['name']] = new_contact
save_contacts(contacts, filename)
elif choice == "2":
print_contact()
elif choice == "3":
search = input("Please enter name (case sensitive): ")
try:
print_contact(contacts[search])
except KeyError:
print("Contact not found")
elif choice == "0":
print("Ending Phone Book.\nHave a nice day!")
break
else:
print("Invalid Input! Try again.")

Resources