Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What am i doing wrong??
#1
import csv
import sys
import random

def main():
   menu()


def menu():
    print("      ::::::::      :::    :::       ::::::::::       ::::::::       :::::::: ")
    print("     :+:    :+:     :+:    :+:       :+:             :+:    :+:     :+:    :+: ")
    print("     +:+            +:+    +:+       +:+             +:+            +:+         ")
    print("     :#:            +#+    +:+       +#++:++#        +#++:++#++     +#++:++#++   ")
    print("     +#+   +#+#     +#+    +#+       +#+                    +#+            +#+    ")
    print("     #+#    #+#     #+#    #+#       #+#             #+#    #+#     #+#    #+#     ")
    print("      ########       ########        ##########       ########       ########       ")

    choice = input("""
                      A: Play
                      Q: Quit
                      Please enter your choice: """)

    if choice == "A" or choice =="a":
        print("Im thinking of a number between 1-10")
        chances = 3
        secret = random.randint(1,10)
        life = "true"
        while life == "true":
            guess = int(input("Please enter your guess : "))
            chances = chances - 1
        if guess == secret:
            print ("Correct!")
            life = "false"
        else:
            if secret > guess:
                print("Higher")
            elif secret < guess:
                print("Lower")
        if chances == 0:
            print ("Unlucky" "You have ran out of chances! The secret number was",secret)
            life = "false"

   
main()
All help will be appreciated Smile
Reply
#2
Please don't only provide the code. Also describe the issue.
Reply
#3
Line 1-2: Not used imports
Line 5-6: Function with only one statement
Line 23: use choice.lower() == 'a'
Line 29: If the input is not a number, your program will throw an exception, use try/except
Line 30: Could be written as chances -= 1
Line 27: Don't use string literals, if you need a boolean True or False.

You should split your program in functions.
One function to get a valid integer input in range 1 - 10.
One function to ask if you want to repeat the game, which returns a boolean.


import random


def yes_no(question):
    while True:
        answer = input(question + ' ').lower()
        if answer in ('y', 'yes', 'j', 'ja'):
            return True
        if answer in ('n', 'no', 'nein'):
            return False
        else:
            print('Invalid answer, please repeat')


def choice(question, answers):
    while True:
        answer = input(question + ' ').lower()
        if answer in answers:
            return answer
        else:
            print('Your answer is invalid. Repeating..')


def input_guess():
    while True:
        guess = input('Please enter your guess: ')
        try:
            guess = int(guess)
        except ValueError:
            print('Guess "{}" is not a number'.format(guess))
            continue
        if 1 <= guess <= 10:
            return guess
        else:
            print('Your guess must be between 1 and 10')


def menu():
    print("      ::::::::      :::    :::       ::::::::::       ::::::::       :::::::: ")
    print("     :+:    :+:     :+:    :+:       :+:             :+:    :+:     :+:    :+: ")
    print("     +:+            +:+    +:+       +:+             +:+            +:+         ")
    print("     :#:            +#+    +:+       +#++:++#        +#++:++#++     +#++:++#++   ")
    print("     +#+   +#+#     +#+    +#+       +#+                    +#+            +#+    ")
    print("     #+#    #+#     #+#    #+#       #+#             #+#    #+#     #+#    #+#     ")
    print("      ########       ########        ##########       ########       ########       ")


def game_logic(chances=3):
    while True:
        if not yes_no('[y/n] Do you want to play the game?'):
            break
        print("Im thinking of a number between 1-10")
        secret = random.randint(1,10)
        for guess_number in range(1, chances + 1):
            guess = input_guess()
            if guess == secret:
                print('You won the game')
                break
            if secret > guess:
                print("Higher")
            elif secret < guess:
                print("Lower")
        else:
            # this block belongs to the for-loop
            # this else block is executed, if the for-loop was able
            # to finish the looping
            # if you break out of the loop, this block is not executed.
            print ("Unlucky! You have ran out of chances! The secret number was", secret)


def main():
   menu()
   game_logic(chances=5) # overwrite the default value of chances


if __name__ == '__main__':
    main()
Try to understand the for-loop/else, try/except, while True:, continue, break.

The try, except, else clause is also used for control flow.
For example if you enter a char instead of a number and you try to convert it to an int, the interpreter throws an exception. In this case, it's a ValueError. This means, you don't have to check, if the input is a valid number, the int function does this for you. If the builtin int function fails, it throws the error. You as the caller, catch this exception and repeat the input again. If the input could converted to an int, the else block is executed and the function returns this integer. Return from a function is immediately, even if your program is in a for-loop or while-true-loop.

The else-block of the for-loop is executed, if the for-loop was able to finish the iteration.
If you break out of the loop, the else-block isn't executed.
This feature is not well known.

So if the loop was able to iterate 5 times (i changed the chances) range(1, 6), all the chances are exhausted.
If you want to play more with input on terminal, you should try this package: https://github.com/kylebebak/questionnaire
Maybe it's useful for you.

By the way, the code is a little bit more, but also more fail-safe and splited into it's logic parts.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,539 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  python gives wrong string length and wrong character thienson30 2 2,993 Oct-15-2019, 08:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020