I've created a program requiring a validation component to make sure score numbers entered are between 1 and 10, and this function will be used later on to append a list. So far I've written this:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
score = raw_input("Please enter a valid score between 1 and 10 ")
if score > 1 and score < 11:
goodNum == True
else:
print "Invalid input"
return score
When I run the program it continuously loops, constantly asking me to input the score as if the false variable isn't turning to true, when it should stop after validating the score. How should I go about correcting this problem?
You are not actually changing the value of goodNum:
goodNum == True
just compares goodNum to True. What you meant was:
goodNum = True
However there are other issues: When you enter a wrong score the first time that cannot be converted to an int, you come into your except block and ask for input again. At that point the result of raw_input is not turned into an int, so the following if will not work. I would suggest you change your logic to:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
print "Invalid input could not convert to integer"
continue # Just start over
if score > 1 and score < 11:
goodNum = True
else:
print "Invalid input, score must be between 1 and 10"
return score
Note: I don't know what your setup or experience level is, but I would recommend for you to use an IDE that automatically recognizes statements like this (statements with no effect) and let you easily debug your script by placing break points
Related
import random
attempt =0
while attempt <=3:
rand = random.randint(1,18)
age = int(input(“please input your age:”))
if(int(age) == rand):
print(“great”)
elif age< rand:
print (“smaller than the true value”)
elif age > rand):
print (“larger than the true value”)
Generate a random age (1~18), let the user input the age for at most 3 times, if the input is the same as the random number, output 'Great', if it is smaller, output 'Smaller than the true value', if it is larger, output 'Larger than the true value'
my code works but it keep repeating even if it is already more than 3
You have to make sure you increase the value of attempt everytime you get an answer. Also, fix some indentation error:
import random
attempt = 0
while attempt < 3:
rand = random.randint(1,18)
age = int(input("Please enter your age"))
if(int(age) == rand):
print("Great")
elif age< rand:
print ("smaller than the true value")
elif age > rand:
print ("larger than the true value")
attempt += 1
Hope this helps!
problem1 = else not working when i type for example some character it crash
problem2 = when i win(guess number) it wont do anything (it should print (more in code))
import random
print("guess number 1,5")
player = int(input("type guess: "))
pc = random.randint(1, 5)
attemp = 1
while player != pc:
attemp = +1
if player != pc:
print("your guess", int(player), "pc", int(pc))
player = int(input("type guess: "))
pc = random.randint(1, 5)
elif player == pc:
print(
"you win with number",
int(player),
"you had",
int(attemp),
"attempts",
)
else:
print("please type int num only")
hráč = int(input("type type: "))
pc = random.randint(1, 5)
There are a few different places where the code doesn't work as intended.
int(input("type guess: ")) will crash if you type in something that is not an integer, because int(...) tries to convert it to an integer and fails. The easiest way to fix this is to catch the exception and ask again for a number in a loop:
while True:
try:
player = int(input("type guess: ")) # If this line fails, break won't be executed
break # If the conversion went well we exit the loop
except ValueError:
print('Invalid number')
while player != pc will exit the loop as soon as the user inputs the right number, and the code that prints the success message will not be executed. To fix this, change the loop in a while True and insert a break after you print the success message:
while True:
[...]
elif player == pc:
print("you win with number", [...])
break
You may also notice that the if...elif branches inside the loop cover every possible condition, so the final else part will never be executed. This is not a problem, since we are already handling the input error part when reading the number, so we can remove the else part completely. To simplify the code even more, the condition in the elif isn't necessary, since it's the opposite of the condition in the if, so the logic can be reduced to this:
<read number from user>
while True:
if player != pc:
<print failure message, get new number from the user and new random number>
else:
<print success message>
break
Finally, there is a small mistake in your code:
attemp = +1 probably doesn't do what you want it to do, in that it sets attemp to be equal to +1. I'm assuming you meant attemp += 1, which increments the value by 1
The final code becomes:
import random
print("guess number 1,5")
while True:
try:
player = int(input("type guess: "))
break
except ValueError:
print('Invalid number')
pc = random.randint(1, 5)
attemp = 1
while True:
attemp += 1
if player != pc:
print("your guess", int(player), "pc", int(pc))
while True:
try:
player = int(input("type guess: "))
break
except ValueError:
print('Invalid number')
pc = random.randint(1, 5)
else:
print(
"you win with number",
int(player),
"you had",
int(attemp),
"attempts",
)
break
This is not the cleanest possile way to do it (for example, reading a number from the user is a perfect candidate for a separate function, or you could restructure the logic so that in each iteration of the while True loop you first ask for a number, check it against the random number, print the right message and break if necessary), but I don't want to modify the code too much
I'm writing a simple warmer / colder number guessing game in Python.
I have it working but I have some duplicated code that causes a few problems and I am not sure how to fix it.
from __future__ import print_function
import random
secretAnswer = random.randint(1, 10)
gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
originalGuess = currentGuess
while gameOver == False and attempts <= 6:
currentGuess = int(input("Please enter a guess between 1 and 10: "))
attempts += 1
originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)
if currentDistance < originalDistance and currentGuess != secretAnswer:
print("Getting warmer")
elif currentDistance > originalDistance:
print("Getting colder")
if currentDistance == originalDistance:
print("You were wrong, try again")
if currentGuess == secretAnswer or originalGuess == secretAnswer:
print("Congratulations! You are a winner!")
gameOver = True
if attempts >= 6 and currentGuess != secretAnswer:
print("You lose, you have ran out of attempts.")
gameOver = True
print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)
It asks for input before I enter the loop, which is to allow me to set an original guess variable helping me to work out the distance from my secret answer.
However, because this requires input before the loop it voids any validation / logic I have there such as the if statements, then requires input directly after this guess, now inside the loop.
Is there a way for me to declare originalGuess inside the loop without it updating to the user input guess each iteration or vice versa without duplicating currentGuess?
Thanks
There doesn't seem to be a need to ask the user before you enter the loop... You can just check if guesses = 1 for the first guess...
gameOver=False
guesses = 0
while not gameOver:
guesses += 1
getUserInput
if guesses = 1 and userInput != correctAnswer:
print "try again!"
checkUserInput
print "good job!, it took you {} guesses!".format(guesses)
I'm attempting to create a simple Python game, 'higher or lower'. I'm extremely new to programming so please give me any improvements.
This is what I have so far:
import random
score = 0
def check_choice(lastcard, newcard, userInput):
if newcard >= lastcard:
result = "higher"
else:
result = "lower"
if result == userInput:
print("Correct! \n")
return True
else:
print("Incorrect! \n")
return False
def generate_card():
return str(random.randint(1,13))
def get_user_choice():
choice = input("Please enter 'higher' or 'lower': ")
return choice
def change_score(result):
global score
if result:
score += 1
else:
score -= 1
def play_game():
play = True
card = generate_card()
while play:
print ("Current card is: " + card)
choice = get_user_choice()
if choice == "stop":
play = False
newcard = generate_card()
result = check_choice(card, newcard, choice)
change_score(result)
card = newcard
play_game()
For the most part, everything works correctly. The majority of the game works and returns "Correct!" or "Incorrect!" based on the user's input. However, from time to time it will often report back as incorrect even when the user has chosen the correct choice.
For example, the previous card was 1. When the user entered higher, the next card was a 13 but it reported back as higher being incorrect.
Your cards are being stored as strings:
def generate_card():
return str(random.randint(1,13))
And string comparison isn't want you want here:
>>> '13' > '2'
False
This is a lexicographic comparison, which is what you want when, for example, you're putting things in alphabetical order. But for a higher/lower game, you want a numeric comparison. For that, you want to keep the card as a number, and change get_user_choice so that it converts the user input into a number:
def get_user_choice():
choice = input("Please enter 'higher' or 'lower': ")
return int(choice)
The result is unexpected because the cards are stored with strings, not integers:
def generate_card():
return str(random.randint(1,13))
Strings are compared lexicographical:
>>> 7 < 11
True
>>> "7" < "11"
False
I am a beginner Python programmer (Python 3) and I just made my first real working program. I encounter an issue with the try: except: part (ln 63), I can't manage to trigger the range_error condition in the usr_input() function. I'm probably not using exceptions the right way.
from random import randint
def gen_num():
magic_num = randint(1,100)
return magic_num
def usr_input(range_error = False):
if range_error == True: # If number is out of range, displays additionnal warning message
print("Make sure you enter a number between 1 and 100 !")
usr_num_guess = input("Please enter an integer between 1 and 100 : ")
return int(usr_num_guess)
def play_again():
# We ask the user to choose if he wants to play again or not (yes / no)
yes = set(['yes','y','ye','yeah',''])
no = set(['no','n'])
usr_choice = input("Do you wish t play again ? (Y/n):").lower()
if usr_choice in yes:
return True
elif usr_choice in no:
return False
else:
sys.stdout.write("Please write 'yes' or 'no'")
def player_level_initialize():
# Setting up the user's desired level
easy_level = set(['easy',1])
med_level = set(['medium','med',2,''])
hard_level = set(['hard','difficult',3])
level_choice = input("Please select your level (easy,MED,hard) :").lower()
if (level_choice in easy_level):
return "easy"
elif (level_choice in med_level):
return "med"
elif (level_choice in hard_level):
return "hard"
else:
sys.stdout.write("Please write 'easy', 'med' or 'hard'")
print("Hello and Welcome to this awesome game !")
player_name = input("Please enter your name : ")
level = player_level_initialize()
keep_playing = True
usr_score = 0
while (keep_playing == True):
num_to_guess = gen_num()
num_of_attempts = 1
too_m_attempts = False
max_number_of_attempts = {
"easy":10,
"med":6,
"hard":3
}
usr_num_guess = usr_input()
while (too_m_attempts == False or usr_num_guess != num_to_guess):
if (num_of_attempts < max_number_of_attempts[level]):
try:
(usr_num_guess >= 1 and usr_num_guess < 100)
except:
usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input
else:
if (usr_num_guess != num_to_guess):
if (usr_num_guess < num_to_guess):
print("It's more !")
else:
print("It's less !")
num_of_attempts += 1
usr_num_guess = usr_input()
elif (usr_num_guess == num_to_guess):
usr_score += 1
print("Good job", player_name, "you found the magic number in only", num_of_attempts, "attempts ! It was", num_to_guess, "You have a current score of", usr_score)
else:
print("Sorry, too many attempts ! The magic number was", num_to_guess)
too_m_attempts = True
keep_playing = play_again()
print("Thank you ! I hope you enjoyed the game !")
What you need is an if block instead of a try-except block:
if not (usr_num_guess >= 1 and usr_num_guess < 100):
usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input
The code in the except part will only be executed if the line (usr_num_guess >= 1 and usr_num_guess < 100) raises an exception.
On the use of exception, when you write
try:
...
except:
...
the code will catch every possible exception and execute th code in the except block which is supposed to fix the situation. This is probably not what you want most of the time. For example, mis-spelling a variable (e.g. usr_num_guesss) will raise a NameError, and whatever user_input() do will not fix the error -- it is an entirely different problem already than an out-of-range input. You should only catch and handle the exceptions that can be handled by your code, such as:
except ValueError:
...