How to capture the enter key in Python without Tkinter - python

I need to make my program start over in Python if the enter key is pressed. I found this question and solution: how to check if the enter key is pressed python. However when I googled event.keysym, it seemed to have something to do with Tkinter which I don't think I have.
When I try using the solution I get an error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if event.keysym == 'Return':
NameError: name 'event' is not defined
I am a complete newbie having just completed a course with Dr. Severance on Coursera.
Here is the program I wrote to play pigs and bulls at work. Everything works as I want. The only problem is to exit the program if any key other than the "enter" button is pushed.
while True:
while True:
word= raw_input("Enter a four letter English word with no repeating letters: ")
print
if len(word) <> 4:
print "What part of 'four letter word' did you not understand? Try again."
print
continue
else: break
guesses = 0
while True:
correct = 0
position = 0
cnt = 0
result = 0
guess= raw_input("Enter a guess: ")
guesses = guesses+1
#print "guessses", guesses
for w in guess:
cnt = cnt+1
#print "cnt", cnt
position=0
for g in word:
position=position+1
#print "position", position
if g == w:
correct = correct+1
if position == cnt:
result = result+1
#print "result", result
print
print "Number correct:", correct
print "Number in the right position:", result
print
if correct<>4 and result<>4:
print "Give me another guess"
print
continue
elif correct == 4 and result == 4:
print
print "YOU WIN"
print
print "It took you", guesses, " guesses to get it right"
print
break
answer= raw_input("press ""enter"" to play again")
if event.keysym == 'Return':
continue
else:
exit
print
print
Then I thought, maybe I have replace "event" with my string variable "answer" but then I got this error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if answer.keysym == 'Return':
AttributeError: 'str' object has no attribute 'keysym'
Also, If I press any other key, it simply prints in Idle and the program does not exit.
By the way, I know there has to be a better way to program this using lists or dictionaries, but this is all I know how to do.

pressing enter would result in a zero-length word. make that your first check.
however, if you want to catch a single keyhit, like getch() in C, it's a lot more complicated, e.g. https://stackoverflow.com/a/6599441/493161
another alternative would be to trap ^C (control-C):
try:
answer = raw_input('Control-C to exit, <ENTER> to play again: ')
if len(answer) > 0:
raise(ValueError('Unexpected input'))
else:
continue
except (KeyboardInterrupt, ValueError):
sys.exit(0)

Related

How to do the program will terminate if your user input's first letter of a word is not capitalize?

How do I make this program accepts only a user input that's been typed while following a proper capitalization. Like it won't accept "robin hood" unless it's "Robin Hood". When I run it, it says...
Traceback (most recent call last):
File "C:\Users\AMD-Ryzen\Documents\PY CODEX\3.1.py", line 20, in <module>
if x.isupper() == false:
AttributeError: 'list' object has no attribute 'isupper'
Here's my code:
#List of the movies
lst = ['Spidey', 'Castaway', 'Avengers', 'GI. JOE', 'Shallow']
#The data stored in this list will come from input("Name of movie") using .append
x=[]
print("Enter at least 5 of your favorite movies"+"\n")
#Loop to repeat the same question 5 times
for i in range(5):
x.append(input("Name of movie:"))
#I used the set.intersection method to find the common elements between the two list
lst_as_set = set(lst)
intersection = lst_as_set.intersection(x)
intersection_as_lst = list(intersection)
if x.isupper() == false:
print("It will never work out. Nice meeting you!")
elif len(intersection_as_lst) == 3:
Ques = input("\n"+"Do you love some of his movies?:")
if Ques == "yes":
print("\n"+"You have", len(intersection_as_lst), "common fave movies and they are:")
print(intersection_as_lst)
elif Ques == "no":
print("It will never work out. I dont like")
s = set(x) - set(lst)
print(s)
elif len(intersection_as_lst) == 0:
Ques = input("Do you love some of his movies?:")
if Ques == "yes":
print("It will never work out. Nice meeting you!")
else:
print("It will never work out. Nice meeting you!")
The error occurs because you are trying to apply a string method isupper() to a list. You must use a loop with the parameter:
for c in x:
if not c[0].isupper():
print("It will never work out. Nice meeting you!")
break
First in python it is False and not false.
and as you want to stop the program you can raise an exception
x = list()
print("Enter at least 5 of your favorite movies\n")
for i in range(5):
m_name = input("Name of movie: ")
if m_name[0].islower():
raise 'must start with an uppercase letter'
x.append(m_name)
You are checking if list is isupper .
You'll need to do
output = []
for word in x:
if word[0].isupper() == False:
output.append(word)
print("It will never work out. Nice meeting you!")
def ìs_properly_capitalized(word: str) -> bool:
if not word:
return False
return word[0].isupper() and not any([c.isupper() for c in word[1:]])
results = [ìs_properly_capitalized(word) for word in lst]
if False in results:
print("One or more words not properly capitalized")
sys.exit(1)

TypeError: object of type 'builtin_function_or_method' has no len(), in 2 parts of the code

I'm working on a hangman game, and I keep running into the same error, and I've been trying to debug it for a couple hours with no progress.
This is the error message:
Traceback (most recent call last):
File "hangman.py", line 128, in <module>
guess = guessletter(miss + correct)
File "hangman.py", line 103, in guessletter
if len(guess) != 1:
TypeError: object of type 'builtin_function_or_method' has no len()
Here are the relevant parts of my code:
Line 98 - 110
`def guessletter(previousguess): #this function lets the player guess a letter, and see if the guess is acceptable
while True:
print ('Guess a Letter')
guess = input()
guess = guess.lower
if len(guess) != 1:
print ('Enter single letter please.')
elif guess in previousguess:
print ('That letter was already guessed. Choose another')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print ('Please put a letter')
else:
return guess`
Line 125~141
while True:
board(hangmanpictures, miss, correct, unknownword) #i define a board function at the top
guess = guessletter(miss + correct) #i use the function defined above, but it seems to make an error here..
if guess in unknownword:
correct = correct + guess
foundallletters = True #check if player has won
for k in range(len(unknownword)):
if unknownword[k] not in correct:
foundallletters = False
break
if foundallletters:
print ('The secret word is "' + unknownword + '"! You won!')
gamefinish = True
The problem is with this line:
guess = guess.lower
You forgot to call the str.lower method so guess is being assigned to the method object itself.
To fix the problem, call the method by placing () after its name:
guess = guess.lower()
# ^^
Below is a demonstration:
>>> guess = 'ABCDE'
>>> guess = guess.lower
>>> guess
<built-in method lower of str object at 0x014FA740>
>>>
>>> guess = 'ABCDE'
>>> guess = guess.lower()
>>> guess
'abcde'
>>>

How to make the user only enter one character at a time

OK so what I need to do is make my code only allow the user to enter one letter and then one symbol at a time. The example below shows what I want in a better view.
At the moment my code allows the user to enter more than one character at a time which I don't want.
What letter would you like to add? hello
What symbol would you like to pair with hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello']
What I want is a message to be displayed like this and the pairing not to be added to the list.
What letter would you like to add? hello
What symbol would you like to pair with hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
So far my code for this section is as follows...
It would also be great for when the user enters a number in the letter section, an error message to be printed.
def add_pairing(clues):
addClue = False
letter=input("What letter would you like to add? ").upper()
symbol=input("\nWhat symbol would you like to pair with ")
userInput= letter + symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
elif len(userInput) ==1:
print("You can only enter one character")
else:
newClue = letter + symbol
addClue = True
if addClue == True:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
The easiest way to ensure user input is with a loop:
while True:
something = raw_input(prompt)
if condition: break
Something set up like this will continue to ask prompt until condition is met. You can make condition anything you want to test for, so for you, it would be len(something) != 1
Your method can be simplified to the following if you let the user enter a letter and symbol pair:
def add_pairing(clues):
pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
clues = pairing.upper().split()
print('Your pairings are: {}'.format(clues))
return clues
Not exactly sure what you want to return but this will check all the entries:
def add_pairing(clues):
addClue = False
while True:
inp = input("Enter a letter followed by a symbol, separated by a space? ").upper().split()
if len(inp) != 2: # make sure we only have two entries
print ("Incorrect amount of characters")
continue
if not inp[0].isalpha() or len(inp[0]) > 1: # must be a letter and have a length of 1
print ("Invalid letter input")
continue
if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
print ("Invalid character input")
continue
userInput = inp[0] + inp[1] # all good add letter to symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
else:
newClue = userInput
addClue = True
if addClue:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
I am fan of raising and catching exceptions in similar cases. Might be shocking for people with 'C-ish' background (sloooow), but it is perfectly pythonic and quite readable and flexibile in my opinion.
Also, you should add check for characters outside of set you are expecting:
import string
def read_paring():
letters = string.ascii_uppercase
symbols = '*##$%^&*' # whatever you want to allow
letter = input("What letter would you like to add? ").upper()
if (len(letter) != 1) or (letter not in letters):
raise ValueError("Only a single letter is allowed")
msg = "What symbol would you like to pair with '{}'? ".format(letter)
symbol = input(msg).upper()
if (len(symbol) != 1) or (symbol not in symbols):
raise ValueError("Only one of '{}' is allowed".format(symbols))
return (letter, symbol)
def add_pairing(clues):
while True:
try:
letter, symbol = read_paring()
new_clue = letter + symbol
if new_clue in clues:
raise ValueError("This pairing already exists")
break # everything is ok
except ValueError as err:
print(err.message)
print("Try again:")
continue
# do whatever you want with letter and symbol
clues.append(new_clue)
print(new_clue)
return clues

Nothing happens for either input

I have a feeling I've made a silly mistake somewhere but at nearly 2am I just can't see it...
Here's the code in question. It is part of a function:
running = True
while (running):
playerName = input("Please enter your first name \n").title()
print ("You have entered '%s' as your name. Is this correct?"%playerName)
playerNameChoice = input("Enter 'Y' for Yes or 'N' for No.\n").upper()
if(playerNameChoice == "Y"):
break
#The following randomly selects Card 1 for the computer
randomComputerCard = random.choice(availableCards)
if randomComputerCard in (Queen,King,Jack,Ace):
randomComputerCard = 10
else:
randomComputerCard = randomComputerCard
randomComputerCard2 = random.choice(availableCards)
if randomComputerCard2 in (Queen,King,Jack,Ace):
randomComputerCard2 = 10
else:
randomComputerCard2 = randomComputerCard2
print ("%i"%randomComputerCard)
print ("%i"%randomComputerCard2)
print ("TEST OVER")
elif(playerNameChoice == "N"):
continue
During testing when I enter Y when prompted to enter either Y or N nothing happens, it just continues the loop when it should actually break. However when I enter N it does exactly what it's meant to and continues the loop. Sorry if this is a waste of a question, but I actually have no idea what I've done incorrectly.
Thanks in advance as always! :)
EDIT: The variable availableCards has already been defined.
You need to remove the 'break' at line 7. That's causing your code to exit prematurely.

Running code through iPython or command window by double clicking

When coding with Python, I've been using Spyder (as it came part of the package that I needed for work)
It comes with an editor, and of course a console, so I write my code and then run it there also.
It looks like this for those who are unfamiliar:
Here I can run my code no problem and get no errors.
Of course, I also save this code to a file, and I would like to get that code running by just double-clicking on the file name. Is that possible?
I can do it now and get a command prompt, but when I do it now I get this error:
(I'm using the same code that's in the images, can anyone tell me what I am doing wrong?
Here is my clear() code in case that matters:
def clear():
os.system(['clear','cls'][os.name =='nt'])
Edit:
Here's the last portion of the code, since the pictures are hard to read.
player = raw_input("What is your name? ")
The game itself
def hangman(player):
clear()
print "Hello! \nWelcome to Hangman, %s" % player
if init_play() == "quit":
print "Ok. Goodbye"
return
word = word_gen("text")
word_hidden = ["-" for x in range(0,len(word))]
av_letters = [chr(x) for x in range(97,123)]
guessed = []
turn = 1
print ("I am thinking of a word that is %d letters long\n" % len(word))
print "Here is the board\n"
print_board(word_hidden)
print "\nHere are your available letters:\n"
show_letters(av_letters)
while turn <= 5:
if word_hidden.count("-") == 0:
print "\nYou won!"
play_again()
print "\nGuess %d out of %d\n" % (turn, 5)
turner = word_hidden.count("-")
guess = raw_input("Guess a letter! ")
als = av_letters.count(guess)
guess_check(guess, guessed, word, word_hidden, turn, av_letters)
if als == 0:
pass
elif word_hidden.count(guess) == 0:
turn+=1
print ("You lose.\nThe word was %s\n" % word)
print ""
play_again()
clear()
hangman(player)
To use os.system, you need to import the os module first. The code is missing the import statement.
Put the following line at the beginning of the code:
import os

Categories

Resources