mercredi 31 mars 2021

Why can't I seem to mix argv and randint?

So I had my guessing game working and It wouldn't break regardless of input. i understand I can use the int function on the input but if the user decides to enter anything but an integer you get a runtime error so I did it different it was working until I decided I wanted to allow the user to add CLI arguments to define the value range for the integer generation it looks as below but it doesn't work...

from sys import argv
import random
lower, upper = argv
lower = int(lower)
upper = int(upper)
secret_number = random.randint(lower, upper)

Output:

Traceback (most recent call last):
  File "guess.py", line 3, in <module>
    lower, upper = argv
ValueError: too many values to unpack (expected 2)

I ran it with python guess.py 1 100

this is the working version

import random
secret_number = random.randint(1,100) #assigns a random integer to secret_number
count = int(0) #starts the guess counter at 0
#print(f"the secret number is: {secret_number}")
print("Try and guess the number between 1-100")
number = input("please enter your guess: ")
while number != secret_number:
    try:
        count += 1  #same as count = count + 1
        number = int(number)
    except:
        print(f"you entered: {number}")
        number = input("please enter an integer only!: ")
    else:
        if number < secret_number:
            print(f"you entered: {number}")
            number = input("To Small! try again: ")
        elif number > secret_number:
            print(f"you entered: {number}")
            number = input("To big! try again: ")

print(f"you entered: {number}")
print("You Win! Congratulations!")
print(f"You took a total of {count} attempts to guess the number!")



Aucun commentaire:

Enregistrer un commentaire