When asked for raw_input, and I hit enter, python closes - python

I am completely new to python so please excuse me. I try to learn python on a website called Codecademy. It all works fine, however I wanted to see what would happen if I insert a script from the website into python on my PC. I have currently installed the second version of python (2.7.13).
The script is the following:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word [0]
new_word = word + first + pyg
# All the different variables are now in one
new_word = new_word[1:len(new_word)]
# The first two letters are removed
print new_word
else:
print 'empty'
# If there is no input or any input containing non-letter characters
When I open this script via python, I am able to enter the first question, but as soon as I hit enter, the program closes and I can not get to my second question. I tried loading it via cmd directly, but it didn´t work either.

Just add this line after your output:
raw_input('Enter any key to exit: ")
This will keep it open until you hit a key and click enter.

There is no "second question" -- you have only one input statement in your control flow. If you want the program to repeat, you need to code that. A simple version:
while True:
# Get user input
original = raw_input('Enter a word:')
# Convert to Pig Latin
... continue with your original code
# Print result
Granted, this will loop forever. You can set a check in the loop for a "quit" input, if you like. I leave that as a further exercise for the student.

The complete solution of your query:
Note(You said the first two letter is removed but in your code you wrote [1:]-- that means it removed only first letter)
pyg = 'ay'
want_continue = True
while want_continue:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word [0]
new_word = word + first + pyg
# All the different variables are now in one
new_word = new_word[2:len(new_word)]
# The first two letters are removed
print new_word
else:
print 'empty'
# If there is no input or any input containing non-letter characters
user_input = raw_input('Want to Contiue:(Y)')
if user_input.lower() != 'y':
want_continue = False

Related

After changing a variable, the next input that's supposed to use the updated variable uses the old one

I'm very new to python and Stack overflow so sorry if my question is lacking information, but I hope you can solve it.
To give some background, I am making a game that generates a random alphabet with some words in there (kind of like a word search) and I am unable to remove a specific letter (to make it easier for the user to guess) until after the response has been given. Valid words are the words that are in the alphabet, and random_az_word is a string of a random alphabet.
Here is the code:
while not user_win:
user_input = input(input_question)
if user_input in valid_words:
user_win = True
while not user_input.isalpha():
user_valid = False
input_question = 'Please put in a valid word '
user_input = input(input_question)
if user_input not in valid_words:
while not remove:
remove_num = random.randint(1,int(len(random_az_word)-1))
if random_az_word[remove_num] not in ''.join(valid_words):
remove = True
random_az_word = random_az_word.replace(random_az_word[remove_num],'')
input_question = f'Incorrect, please try again, after removing the letter {random_az_word[remove_num]} alphabet is {random_az_word} '
After wards, the input question ends up with the old alphabet (without the removed letter), until after you put in a response.
PS. I'm very tired right now so I could just be missing a very noticeable mistake, I apologize if that's the case.

Take word by word input and output a sentence

I am trying to write a program that inputs a sentence from the keyboard, word by word, into a list. The program should output the following.
The complete sentence, with the first word capitalized if it wasnt already, spaces between each word, and a period at the end.
The count of the number of words in the sentence.
For instance, if the input is:
the
cat
ran
home
quickly
Your program should output:
The cat ran home quickly.
There are 5 words in the sentence.
listMessage = []
message = input('Enter first word of your message: ')
while message != 'done!':
listMessage.append(message)
message = input('Please enter the next word of your message or type done! when complete ')
return listMessage
Given that you already have listMessage, you can simply:
' '.join(listMessage).capitalize() + '.'
def function():
listMessage = []
message = input('Enter first word of your message: ').strip()
while message != 'done!':
listMessage.append(message)
message = input('Please enter the next word of your message or type done! when complete ')
text = ' '.join(listMessage).capitalize()+'.'
return text
You've got a couple things you might want to check here, according to your problem description.
If you want spaces between each word, you'll likely want to check to make sure that the words themselves, when entered, don't have leading or trailing spaces already. Use .strip() on your input to ensure this is the case.
If you want to capitalize the first letter of your sentence, you can check to see if listMessage[0][0].isupper() == True. This checks the first letter of the first word for capitalization.
If you'd like to add spaces to each string when you concatenate it, you can try a ranged for loop:
finalStr = ""
for str in listMessage:
finalStr += (str + " ")
(This will leave a space at the end, remember to .strip() it.)
Put it all together, and you've got your code. Try a working solution here!
You can try this:
word = ""
sentence = ""
while True:
word = input("Enter a word: ")
if word == 'done!':
break
sentence = sentence + word + " "
print(sentence)

How can I delete a letter from a string in a list?

I have to solve the following problem:
-Write a program that takes a text as an entry and prints the same text without the letter 'r' in it.The teacher said that we have to use a list to put all the words in it and then remove the letter "r" from them. Here is how I started:
text = input("Enter some text: ")
l=text.split(" ")
for i in range(len(l)): #I want to use for to run the elements of the list
I don't know what to do next and what method I should use, I thought maybe the method remove() can be useful,but I don't know how to use it in each item of the list.
Welcome to SO, 👋
Here is my version.
statement = input("Enter some text: ")
listOfWords = statement.split(" ")
for i, word in enumerate(listOfWords):
if("r" in word.lower()):
print("found an instance of letter r in the word ({0})".format(word))
listOfWords[i]=word.replace("r", "")
sentence = " ".join(listOfWords)
print(sentence)
First - it grabs all the words from the input text as a list.
Then it iterates over all the words and if there is a "r" , it removes it from the word and updates the list as well. At the every end it generates the sentense back from the list.
Please note - this is ultra verbose code. It does not use Python features like List Comprehension, but it is much easier to understand. I purposefully added debug statements.
Please let me know if this works for you.
Thanks
For the list: str.split() will give a list of each item surrounded with whitespace (You can specify any delimiter you like)
Let's start with an individual list item... We will go with "Rollercoaster".
We can use the in keyword to check if a substring included in a larger string.
text = input("Enter some text: ")
result = ""
for ch in text.lower():
if ch == 'r':
continue
else:
result += ch
print(result)
Returns
Enter some text: rollercoster
ollecoste
Process finished with exit code 0

Python guessing word game

I trying to convert my code using function. As this coding is not done yet but i manage to get the code running well. The only thing is every time i guess a letter, it reset my previous record. How to i store my previous guess result and continue add if the letter is guessed correctly?
import random
def chooseAword(wordList):
correct_word = random.choice(wordList)
return correct_word
#def spelltheword(word)
def guessAletter(guessedletter):
word = guessedletter
guess = input('Guess a letter: ')
letter = ''.join(x if x in guess else '-' for x in word)
if guess in word:
print("So far you have: ", letter)
else:
print("So far you have: ", letter)
return letter
def playAgame(wordList):
word = chooseAword(wordList)
for n in range(5):
guessletter = guessAletter(word)
def main():
wordList = ('python', 'csharp','java','oracle')
playAgame(wordList)
main()
No, it doesn't reset your previous record: you have no previous record. Every call to guessAletter very specifically puts a hyphen in any position that is not the currently guessed letter.
Yes, you return the word (which you named letter, for some reason) of hyphens and correct letters, but the calling program playAgame puts this into a local variable guessletter (another misleading name), and then never uses it again.
I have several suggestions:
Practice incremental programming. Write a few lines of code to perform a trivial part of your program. Debug them. Do not continue until you know they do what you want, through testing several possibilities. Then write a few more lines; repeat this process until your program works.
Use meaningful variable names. word doesn't tell us much; we don't know whether this is the word we're supposed to guess, the current game progress you show the user, or something else. At the worst, you use guessedLetter for something that is not a single letter, and is not a guess.
With the incremental programming, follow the status of your game state: this should be one value passed back and forth with your guess-and-check function. You update it in that function, and print it in the guess-a-letter loop.

Defining the same variable twice / help understanding

I made this simple Pyglatin translator in a Codeacademy learning exercise. Code is working fine, but need help understanding why.
The variable new_word is defined twice in the if statement. How does the code know to print the second definition of new_word instead of the first. Seems like it would make more sense for the final two lines of the if statement to read like-
final_word = new_word[1:len(new_word)]
print final_word
Full working code below-
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
print 'empty'
Can you keep redefining the same variable and it will always take the last definition given?
That's how imperative programming works. It says set the value of new_word to X. Then set the value of new_word to Y. Each statement does a particular thing, and the statements are followed one by one, modifying the program's state one by one.
You can contrast that with something like declarative programming in which you only define everything once, and the computer figures out in which order it needs to execute what in order to arrive at the result you described.
In this line you assign the concatenation of word, first and pyg to new_word:
new_word = word + first + pyg
After that, in this line, you chop off the first char:
new_word = new_word[1:len(new_word)]
You indeed use the same var new_word twice,
and the newest value (first char chopped off) overwrites the first one (first char still present).
B.T.W. the second line is needlessly complicated, it could also have been:
new_word = new_word[1:]
Maybe it helps to realize that a program variable isn't a mathematical variable, and the = in your program isn't a mathematical =.
a = 3 isn't a proposition meaning that a is equal to 3.
It is an action that puts the number 3 into a memory location labeled a.
So you can always put something else there.
Early languages used := (becomes) instead of = (is), and some languages still use <- to denote this assignment action.

Categories