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.
Related
I am making some homework drill and am trying to check whether a number is a positive integer using Try. somewhere along the way it returns the value of my input, but it returns the negative value, even after I eventually type in a valid value.
lets say- first i typed in -10, it tells me to type again, then I type 2, but the return is still -10.
def takes_desicion(name):
print "Ok %s, now lets make a desicion what to do with your text.\n" %name
print "you can either- 1.leave it, 2.reverse it, or 3.make a new input."
while True:
try: #takes an input with exception- in this case, only integer.
desicion = int(raw_input("Hit your number to decide."))
print desicion
except ValueError:
print "Sorry, thats not a number."
continue
else: #if int is negetive, goes back to the function again, recursively
if desicion < 1:
print "That number is illegal."
takes_desicion(name)
break
return desicion
if i first input -10, and the second input is 2, i would expect the output (return) to be 2. but its -10. That's the value that returns from the function.
You call the takes_desicion function again on third last line, but you don't do anything with the value from that function. You need to store the newly returned value: desicion = takes_desicion(name)
Although you should just use continue instead t jump to the first like of the while loop, there's no need to call the function again:
def takes_desicion(name):
print "Ok %s, now lets make a desicion what to do with your text.\n" %name
print "you can either- 1.leave it, 2.reverse it, or 3.make a new input."
while True:
try: #takes an input with exception- in this case, only integer.
desicion = int(raw_input("Hit your number to decide."))
print desicion
except ValueError:
print "Sorry, thats not a number."
continue
else: #if int is negetive, goes back to the function again, recursively
if desicion < 1:
print "That number is illegal."
continue
break
return desicion
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 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!"
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.
I'm working on a number guessing game and can't seem to get my loop to work while utilizing a function. I was manually typing out conversion under each if/elif in the block, but that was tedious and only checking for integers - string inputs couldn't read and broke the system.
I tried creating a conversion function to check the values and determine if it was an integer or string and change the variable type accordingly. However this results in an infinite loop fo line 18.
Can someone point out what I'm doing wrong here?
Heads up, I do have the random.py script from Python.org and am importing it so the game plays differently each time.
from random import randint
print 'Hello, my name is Skynet. What\'s yours?'
myName = raw_input()
print 'Good to meet you, ' + myName + '! Let\'s play a game.'
print 'I\'m thinking of a number between between 1 and 20, can you guess it?'
pcNum = randint(1,20)
myNum = raw_input()
def checkNum(myNum):
try:
int(myNum)
except ValueError:
returnVAL = 'That\'s not a number I know, try again.'
else:
returnVAL = int(myNum)
return returnVAL
while myNum != pcNum:
if myNum > pcNum:
print 'That\'s too high! Try again.'
myNum = raw_input()
checkNum(myNum)
else:
print 'That\'s too low! Try again.'
myNum = raw_input()
checkNum(myNum)
if myNum == pcNum:
print 'Good job, my number was ' + str(pcNum) + ' too! Good job, ' + myName
Any input is appreciated. I did some browsing here and got some a better idea of how to pull this off, or so I thought, and now here I am asking. First post!
print "I'm thinking of a number between between 1 and 20, can you guess it?"
while True:
guess = raw_input("What's your guess? ")
try:
guess = int(guess, 10)
except ValueError:
print "That's not a number I know, try again."
continue
if guess == pcNum:
...
break
elif guess > pcNum:
...
else:
...
Don't mix responsibilities. It is wrong to have myNum be both a number and an error message.
Also, think what you want to do when a user enters a non-number. In your case, the user's guess is "That's not a number I know, try again.", and it's being compared to pcNum; this makes no sense. If it was me, I would want the user to enter the number again. So rather than checkNum, I want input_valid_integer:
def input_valid_integer():
result = None
while result is None:
text = raw_input()
try:
result = int(text)
except ValueError:
print 'That\'s not a number I know, try again.'
return result