I am trying to validate input that is going into a list. The input needs to be an integer. How I have it works if I input an integer or a single letter. but if I enter something like 'qw' the program crashes. What can I do to better validate the input? Here is my code:
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = raw_input("Enter the number of pints donated: ")
check = isinstance(pints[counter], int)
while check == False:
print "Please enter an integer!"
pints[counter] = input("Enter the number of pints donated: ")
counter = counter + 1
As written, check will always evaluate to False, because raw_input() only returns a string, never an integer. Then you'll get stuck in an infinite while loop, because you don't update check in it.
Instead of isinstance, use the string isdigit() method.
check = pints[counter].isdigit()
You'll also need to re-evaluate check inside the loop. But really, you don't need check at all.
pints[counter] = raw_input("Enter the number of pints donated: ")
while not pints[counter].isdigit():
print "Please enter an integer!"
pints[counter] = raw_input("Enter the number of pints donated: ")
I suspect you also want to convert pints[counter] to an int once you have a suitable input.
You're using the LBYL method (Look Before You Leap). You can also use the EAFP (Easier to Ask Forgiveness than Permission) method by just trying to convert the input to an int and catching the exception if the input is bad:
while True:
try:
pints[counter] = int(raw_input("Enter the number of pints donated: "))
break
except ValueError:
print "Please enter an integer!"
Related
I'm creating a program that takes in the users grade(A-F), health(0-100) and economic output(0-100). I need a while loop for when the user inputs a value wrong e.g A for health. why does the loop keep repeating? how do I do this for the grade as well?
name = raw_input(' Enter your name: ')
grade = raw_input(' Enter your grade: ')
string_two = raw_input(' Enter your economic out put: ')
while string_two not in range (0,100):
print 'please enter a value between 0 and 100.'
string_two = raw_input(' Enter your economic out put: ')
string_one = raw_input(' Enter your health: ')
while string_one not in range (0,100):
print 'please enter a value between 0 and 100.'
string_one = raw_input(' Enter your health: ')
health == int(string_one)
economic_output == int(string_two)
if economic_output > 85:
print name + ' you are exceptional! Welcome aboard!'
elif grade == 'A':
print name + ' you are exceptional! Welcome aboard!'
elif economic_output > 60:
if health > 60:
if grade == 'B' or 'C':
print 'Congatulations ' + name +'!' + ' Come aboard!'
else:
print 'Sorry, ' + name + ' but you dont meet the criteria and cammot be permitted to board. '
The while loop keeps repeating because raw_input always returns a string object, regardless if you typed digits only or something else. string_two not in range (0,100) is always true because a string cannot be in any range of ints.
So what you can do. If I were you, I would define a function which would ask the user to enter something in a while loop until his input satisfies some pattern (just as you are trying to do in your code) and convert it to a specific type if necessary. There is a very useful tool to check a string for matching some pattern, it is called regular expressions (RE).
import re
def inputAndValidate(prompt, pattern, convertFunc=str):
result = raw_input(prompt)
while re.match(pattern, result) is None:
print 'Input pattern is "' + pattern + '". Please enter a string matching to it.'
result = raw_input(prompt)
return convertFunc(result)
Putting a piece of code being used several times to a function is a good practice. So here I defined a function called inputAndValidate with 2 mandatory parameters - a prompt to be displayed for user to let him understand what do you want from him, and the pattern to check his input. The third parameter is optional - it's a function which will be applied to the user input. By default, it's str, a function converting something to a string. User input is already a string, so this function will do nothing, but if we need an int, we'll pass int as the third parameter and get an int from the inputAndValidate function, and so on.
re.match(pattern, string) returns a match object if the string did match the pattern, and None if it didn't. See official re documentation for more information.
Usage of the function
name = inputAndValidate('Enter your name: ', r'.+')
# This pattern means any string except empty one. Thus we ensure user will not enter an empty name.
grade = inputAndValidate('Enter your grade (A-F): ', r'[A-F]')
# This pattern means a string containing only one symbol in the A-F range (in the ASCII table).
economic_output = inputAndValidate('Enter your economic output (0-100): ', r'\d{1,3}', int)
# This pattern means a string containing from one to three digits. `int` passed to the third parameter means the result will be an int.
health = inputAndValidate('Enter your health (0-100): ', r'\d{1,3}', int)
# Same as the previous one.
re module documentation also contains information about the regular expressions language, it can help you understand the patterns I used.
I am creating a python program which stores it in a list, then records in a text file called wrongpasswords.txt.
The program should ask the user for input by saying 'Please enter your password: '. The correct password will always be 'rusty' but the user can of course enter any String. And also, how do I add to my program that the number of characters the user inputs wrong is also stored for each incorrect password?
Please do mind me as I am a beginner in programming and python.
Please see my code below:
enteredPass = raw_input("Enter your password: ")
incorrectPass= file("wrongpasswords.txt","w")
counter = 0
for i in range(0, counter+1):
if enteredPass != "rusty":
counter = counter +1
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
enteredPass = raw_input("Enter your password: ")
else:
incorrectPassO = open("wrongpasswords.txt","w")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()
If I understood correctly you're trying to create a simple login program that counts the wrong login attempts? This should work:
counter = 0
correct_answer_entered = False
while not correct_answer_entered:
enteredPass = raw_input("Enter your password: ")
counter = counter + 1
if enteredPass != "rusty":
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Incorrect password" +str(counter)+": " + enteredPass + "\n")
incorrectPassO.close()
else:
incorrectPassO = open("wrongpasswords.txt","a")
incorrectPassO.write("Correct password entered on the " + str(counter)+"th entry")
incorrectPassO.close()
correct_answer_entered = True
The points I fixed in your code that you should notice:
I replaced the "w" with an "a" where you open the file, since "w" makes it write over what's already wroten in the file, while "a" appends after what's there.
I replaced the for loop with a while, what you did was a range from 0 to 1, so the loop would exit after the first round, I added a boolean value (correct_answer_entered), to indicate if the correct password was entered, and keeps going if it wasn't.
I moved the "counter = counter + 1" outside of the if statement, since the number of attempts is not related to wither the password is correct or not, the way you did it if the password was correct at the first attempt it'd say 0th attempt instead of 1th.
overrall your code is pretty nice and it's good to see new people getting into programming ^.^
I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")
This is the code in question:
#i/p from user
print "enter your number"
a=sys.stdin.readline()
if(a==6):
print('entered a 6!')
else:
print('you did not enter a 6')
If I enter 6, it is supposed to return entered a 6!,but it is returning you did not enter a 6.
Why is this happening?
You should use:
a = int(sys.stdin.readline())
or
a = int(raw_input())
Your code is reading the input as a string, and you are comparing it to an integer. You need to convert the input for a to an int before making the comparison.
I wrote a program where you guess a randomly generated number between 1 and 100:
from random import randint
play='y'
print 'Guess a number between 1 and 100'
while play=='y':
x = randint(1,100)
guess=1000
while guess != x:
guess=input('Guess: ')
if guess < x:
print 'Higher'
if guess > x:
print 'Lower'
print 'You got it! Good Job! The number was ' + str(x)
play=raw_input('Would you like to play again(y/n)?: ')
raw_input("Press <enter> to exit")
when the user enters a guess that is not an integer how do I print That is not a number, then allow them to continue guessing?
Use a while True loop to repeat the question until it breaks. Only way to break the loop is if try does not raise a ValueError. int() raises an error when it gets something like 'hello' or '1.2'.
Also, use raw_input instead of input (note: raw_input assigns a string to guess).
while True:
guess=raw_input('Guess: ')
try:
int(guess)
break
except ValueError:
print '\nNot an int, try again.'
More specifically, insert this after while guess != x: and before if guess < x.