I'm not sure what I'm doing wrong here. I'm trying to limit user input to 1-6 (dice game). The logic is working but when a ValueError() is raised it doesn't prompt the user again.
try:
while True:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Because you're exiting your loop at Exception. You should write a code like this:
while True:
try:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Use while loop before try code which will keep looping try and catch block like this
while True:
try:
# Your Code
except ValueError:
# Your Code
Related
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!')
I'm trying to validate multiple user inputs, can be of diff. data types.
Is there any better way to do User Input validation in Python3 ? or Improve this block of code.
def validate_number(message):
i = 0
while i < 4:
try:
userInput = int(input(message))
except ValueError:
i += 1
if i == 4:
print('Max try reached !!!')
return False
else:
print("Not an integer! Try again.")
continue
else:
return userInput
break
#------------------------------------------
a = validate_number('Enter 1st No: ')
if a:
b = validate_number('Enter 2nd No: ')
if a and b:
sum = a + b
print('Result is : %s' %(sum))
print('Result is : {} '.format(sum))
print(f'Result is : {sum}')
this is my suggestion:
def validate_number(message):
for i in range(4):
try:
return int(input(message))
except ValueError:
print("Not an integer! Try again.")
print("Max try reached !!!")
a simple for loop in order to count the number of tries.
as it is the function will return None if no valid input is given. you may have to tweak that according to your needs.
I am trying to create a menu here. The menu allows the user to enter options. There is also a validate function to check if the option the user input was valid or not.
def menu():
while True:
display_menu()
user_input = validate("Choose Option")
if user_input == 1:
pass
elif user_input == 2:
exit()
def display_menu():
print("1) Application")
print("2) Quit Application")
def validate1(q):
user_input = input(q)
if len(user_input) == 0:
return False
elif user_input != "1" or user_input != "2": # Error is likely here
print("Invalid option, please choose another option")
return False
else:
return user_input
When you run this code, you get:
1) Application
2) Quit Application
Choose Option
However after entering 1, the validate function thinks the input 1 is invalid and you get:
Invalid option, please choose another option
1) Application
2) Quit Application
Choose Option
This should not be the case as 1 should be valid. At first I thought that it was an error regarding the type of the variable user_input and I have tried to change it (from line 22):
elif user_input != 1 or user_input != 2:
However the error still persists.
What is the error here?
elif user_input != "1" or user_input != "2":
lets, assume that your user input is "1" then that will make this statement true as
user_input (1) is not equal to (2)
Therefore you need to change that statement to something else like this :
def validate(q):
user_input = input(q)
if len(user_input) == 0:
return False
if user_input == str(1) or user_input == str(2): # Valid Options
return user_input
else:
print("Invalid option, please choose another option")
return False
I am getting an infinite loop. I am not sure on how to covert the result as the new number variable and put it back in the while loop.
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except:
ValueError
print('Please type an integer')
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
**result = number**
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
The following works:
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except ValueError:
print('Please type an integer')
sys.exit(1)
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
number = result # set the number to the result
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
Notice that I set the number to the result, in your code the number never changed, and so kept hitting the same block of code over and over. I also added a sys.exit call in the exception, we don't want to continue if someone entered in a bad value.
I am trying to search for a certain number within a Text Document. It reads the file fine, and using the same code later can print fine, but when I tell it to find a certain number in the Text Document it tells me TypeError: list indices must be integers, not _io.TextIOWrapper. I have looked all around but all questions say 'not str' whereas mine says 'not _io.TextIOWrapper'
This is my code (I am going down route 'A' under 'menuOptions'
import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
print("Please enter the fixture number you are looking for... ")
fixtureQuestion = input(int())
fixtureQuestion = int(fixtureQuestion)
fixtureQuestion = fixtureQuestion - (1)
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\\firesideFixtures.txt")
lines = searchData.readlines()
print(lines[searchData])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press B to view outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'B':
print("~~incomplete~~")
elif menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions == 'B':
print("Searching for fixtures...")
time.sleep(3)
data = [line.strip() for line in open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()]
for line in data:
print(line)
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press A to search for a fixture")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'A':
fixtureQuestion = input(int("Please enter the fixture number you are looking for... "))
fixtureQuestion = fixtureQuestion - 1
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()
lines = searchData.readlines()
print(lines[fixtureQuestion])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuOptions == 'C':
while RetryForC == "Yes":
RetryForC == "No"
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
for line in fireRead:
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
InfoOne = line.split(',')[0]
InfoTwo = line.split(',')[1]
InfoThree = line.split(',')[2]
InfoFour = line.split(',')[3]
PointCounter = int(line.split(',')[2])
PointCounter = PointCounter * 3
fireRead.close()
print("Player:",InfoOne,"Has played:",InfoTwo,", has won:",InfoThree,", has lost:",InfoFour,", and therefore has",PointCounter,"many points.")
print("Retry?")
RestForC = str(input("Yes/No "))
print("The program will now close...")
time.sleep(5)
exit()
elif menuOptions == 'Q':
print("Exiting Applicaion...")
time.sleep(2)
exit()
And this is my result:
Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Please enter the fixture number you are looking for...
016
Traceback (most recent call last):
File "E:\Python\Python Work\League\League3.py", line 33, in <module>
print(lines[searchData])
TypeError: list indices must be integers, not _io.TextIOWrapper
What can I do to fix this?
This line:
print(lines[searchData])
Doesn't make any sense. Indices of a list must be integers, so you can do:
>>> my_list = [1, 2, 3]
>>> my_list[0]
1
lines is a list which contains the lines of the file and search_data is a file object. It looks like you're missing some basic python concepts. Please do read the documentation I pasted in your other question you asked 10 minutes ago!