Terminating raw_input based on the ascii value of the string - python-2.7

I am new to python.
My Issue- need to terminate the raw_input if no input is passed
I am basically asking user for number of key-value pairs to be added to dictionary. Then adding the key-value pairs in dictionary. Later querying the dictionary which should result value if key exist, else print Not found.
I searched the Stack Overflow and found solution in terms of timer but I am trying to use ord function to get ascii value of string and check it against null that is ascii value of 0. My code does not seem to terminate, please advice on necessary changes in code.
Please find the code that I am using in the program:
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input().rstrip())
phonebook = dict(raw_input().split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input()
temp=convert_to_ascii(choice)
print temp
if temp != '0':
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print 'Not found'

You should have the empty string '' instead of '0' as your check. This code worked for me. I also added some prints in the raw_inputs to help me look through your code, but the only change that matters is the '0' to '':
def convert_to_ascii(text):
return "".join(str(ord(char)) for char in text)
n=int(raw_input('How many entries in your phonebook?\n').rstrip())
phonebook = dict(raw_input('Please enter "[name] [number]" for entry '+str(i+1)+':\n').split() for i in range(n))
print phonebook
list1=[]
while True:
choice = raw_input('Who do you want to choose?\n')
temp=convert_to_ascii(choice)
if temp != '': #<-- changed to empty string from '0'
list1.append(choice)
else:
break
for word in list1:
if word in phonebook :
print '{0}={1}'.format(word,phonebook[word])
else:
print word,'was not found'

Related

Getting error "NameError: name 'letter' is not defined"

I'm fairly new to python and don't know much but i tried to make a program that sees how fast it can guess a string in this case a password. I tried to create an individual variable for each letter by making a loop that sets the variable. (I added the print letter1... at the end so i can see if it works).Then when i went to test it i got this error.
letter[x] = password[x - 1:-(len(password)-1)]
NameError: name 'letter' is not defined
print "Password guesser"
password = raw_input('Enter Password (1-30 carechters only): ')
passwordLength= len(password)
for x in range(0,passwordLength):
letter[x] = password[x - 1:-(len(password)-1)]
print letter1
print letter2
print letter3
Since you're assigning letters with dictionary syntax, you may want to declare the letter variable as a dictionary: letter = {}, then output it as a dictionary. This may get you in the direction you want to go:
letter = {}
for x in range(passwordLength):
letter[x] = password[x - 1:-(passwordLength-1)]
print letter[0]
print letter[1]
print letter[2]

Python: The code disobeys the conditional depending on the input

I'm making a hang man game. When I made the code with out a conditional and classes, it worked fine. Basically my issues with the code below are:
Only the letter "t" will match. I can't get any other letter to match.
If I enter "t" on the first try, then purposely get the next 4 letters wrong, it won't end until after 7 turns. Yet if I enter any other letter first, it will end after 4 wrong turns, like it should.
My questions....
How can I get it to match with the other letters that are in the self.word index?
Why is it not obeying the condition I set with the while loop in the main method if I enter "t" on my first try and get every other letter wrong thereafter?
class Hang():
def __init__(self):
self.turns = 0
self.word = ['t', 'h', 'i', 's']
self.empty = ["__", "__", "__", "__"]
self.wrong = []
def main(self):
while self.turns < 4:
for i in self.word:
choice = raw_input("Enter a letter a-z: ")
if choice == i:
index = self.word.index(i)
self.empty.pop(index)
self.empty.insert(index, i)
print self.empty
else:
print "Wrong"
self.wrong.append(choice)
print self.wrong
print self.empty
self.turns += 1
char1 = Hang()
char1.main()
In the game of hangman you can guess any character in the phrase in any order. But you're using a for loop to go through each character in order and it is only correct if the player correctly guesses the characters in order
Try this instead
while self.turns < 4:
choice = raw_input("Enter a letter a-z: ")
# optional, if user enters more than a single letter
if len(choice) > 1:
print "invalid choice"
continue # loop again from start
index = self.word.index(choice)
if index != -1:
# -1 indicates character in not int the string
# so this block is only executed if character is
# in the string
self.empty[index] = choice # no need to pop, you can simply change the value of the list at a given index
else:
print "wrong"
self.turns += 1
print self.empty

python 2.7 - trying to print a string and the (printed) output of function in the same line

I have the following function defined:
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print '' # print an empty line
Now, I want to print the following:
Current hand: a b c
To do this, I try to do:
print "Current hand: ", displayHand({'a':1, 'b':1, 'c':1})
And I get:
Current hand: a b c
None
I know that None is printed cause I am calling the print function on the displayHand(hand) function, which doesn't return anything.
Is there any way to get rid of that "None" without modifying displayHand(hand)?
if you want to use your function in a print statement, it should return a string and not print something itself (and return None) - as you would do in a __str__ method of a class. something like:
def displayHand(hand):
ret = ''
for letter in hand.keys():
for j in range(hand[letter]):
ret += '{} '.format(letter) # print all on the same line
# ret += '\n'
return ret
or even
def displayHand(hand):
return ''.join(n*'{} '.format(k) for k,n in hand.items() )
When you trail a print with a ,, the next print will appear on the same line, so you should just call the two things on separate lines, as in:
def printStuff():
print "Current hand: ",
displayHand({'a':1, 'b':1, 'c':1})
Of course you could just adapt this and create a method like:
def printCurrentHand(hand):
print "Current hand: ",
displayHand(hand)
The only way to do this (or I believe the only way to do this) is to use return instead of print in your displayhand() function. Sorry if I didn't answer your question.
Your function 'displayHand' does not have to print the output,
it has to return a string.
def displayHand(hand):
mystring=''
for letter in hand.keys():
for j in range(hand[letter]):
mystring+= letter # concatenate all on the same line
return mystring
BUT, you have to check the '.keys' command help as the order of the input (a/b/c) may not be respected

How to check if a value entered is an integer or string when using input

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.

Converting integers for loop in Python - Loop ignores function value?

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