(Python 3) Program closes upon input - python-3.x

I created a Pig Latin translator. I run the program, it opens, I enter a word, and as soon as I hit 'enter' the program closes. Why is this?
userWord = input('Enter any word:')
pig = "ay"
if len(userWord) > 0 and userWord.isalpha():
word = userWord.lower()
first = word[0]
new = word[1:] + first + pig
print(new)
else:
print("INPUT INVALID")

Python does not interpret what you typed in as a string. You will need to put "" to denote it is a string.
For example:
Enter any word: blah
Traceback (most recent call last):
File "test.py", line 4, in <module>
userWord = input('Enter any word: ')
File "<string>", line 1, in <module>
NameError: name 'blah' is not defined
But if you put ""
Enter any word:"blah"
lahbay

Related

I'm trying to open file, but I have faced this type of errror FileNotFoundError: [Errno 2] No such file or directory:

how to open file wit python code
#user = ["abcdefghijklmnabcdefghijklww"]
user = open("notes.txt", "r")
print(user.read())
for i in user:
print("The no of occurrences of W is ",i.count("i"))
print("The no of occurrences of i is",i.count("n"))
print("The no of occurrences of s is",i.count("d"))
print("The no of occurrences of e is",i.count("i"))
print("The no of occurrences of n is",i.count("a"))
#print(len(user))
break;
```I'm just trying to open file
```I have tried this methods too
# user = open(r'd:\python\notes.txt')
# print(user)
the error was appered:
Traceback (most recent call last):
File "C:\Users\Pradeep\PycharmProjects\pythonProject\test1.py", line 98, in <module>
user = open("notes.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
It is possible that you will be able to obtain the desired result by using this piece of code. Check it out. It works for me.
with open('text.txt', 'r') as user_f:
# Read the contents of the file
text = user_f.read()
# Count the occurrence of each letter
W_count = text.count('W')
n_count = text.count('n')
d_count = text.count('d')
i_count = text.count('i')
a_count = text.count('a')
# Print the count for each letter
print(f"The no of occurrences of W is : {W_count}")
print(f"The no of occurrences of n is : {n_count}")
print(f"The no of occurrences of d is : {d_count}")
print(f"The no of occurrences of i is : {i_count}")
print(f"The no of occurrences of a is : {a_count}")

error:'builtin_function_or_method' object is not iterable

In some other tutorial the following python code for finding words from a json file which worked for them. but, not for me.
would you please help me to get rid of this error.
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(word):
word = word.lower
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys())) > 0:
yn=input ("did you mean %s instead? Enter Y if yes and N if no" % get_close_matches(word, data.keys())[0])
if yn == "Y":
return data[get_close_matches(word, data.keys())[0]]
elif yn == "N":
return("the word doesn't exist")
else:
print("we don't understand your entry")
else:
return("the word does't exist please crosscheck it")
word = input("enter a word: ")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
This is the error I got:
Traceback (most recent call last):
File "pracjson.py", line 23, in <module>
output = translate(word)
File "pracjson.py", line 10, in translate
elif len(get_close_matches(word, data.keys())) > 0:
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 723, in get_close_matches
s.set_seq2(word)
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 279, in set_seq2
self.__chain_b()
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 311, in __chain_b
for i, elt in enumerate(b):
TypeError: 'builtin_function_or_method' object is not iterable
Your error is in this line:
word = word.lower
.lower is a method, so it should be:
word = word.lower()
https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower
I'm not familiar with get_close_matches. But according to the docs: https://docs.python.org/2/library/difflib.html, it seems like it needs a list (iterable object).
data.keys() returns a dictionary. Try converting that to a list first.
elif len(get_close_matches(word, list(data.keys()))) > 0:

random.choice displays an error

I am new to stack overflow and I was wondering if anyone could help me with the following question. If you know a similar question that was answered, please point me towards it. thanks:)
This is my code to create a function load_words() that creates a list of 6 letter words from the file "words.txt". I want the random.choice() to pick a random word from the list and save it into word. However, I get the error below.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
for line in file:
word = line.strip()
if len(word)== length:
words.append(word)
return words
word = random.choice(words)
print (word)
the error I get is:
Traceback (most recent call last):
File "C:\Users\mssuk\Desktop\University\Software Engineering\Assignment\assignment 1 - word guessing game\compute_score.py", line 14, in <module>
word = random.choice(words)
NameError: name 'words' is not defined
It's an indentation error. Indent your return statement by 4 spaces and the code will work.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
#Assuming there is only one word in a line
for line in file:
word = line.strip().lower()
if len(word) == length:
words.add(word)
file.close()
return words
word = random.choice(load_words(your_filename, your_length)
print(word)

I/O operation closed on file in python

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

Python 3 Caesar cipher, help please

hi im trying to create a Caesar cipher using Python 3, the question is in the text, chapter 5 question 7, I have this so far but i keep getting this error message when i try to run the program and cant figure out why.
program:
def main():
print("This program executes a Caesar cipher for a string")
word = input("Please enter word: ")
key = input("Please enter the number of positions in the alphabet you wish to apply: ")
message=""
for ch in word:
word= chr(ord(ch)+key)
newWord =(message + word)
print (newWord)
main()
Error:
Traceback (most recent call last):
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 14, in <module>
main()
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 10, in main
word= chr(ord(ch)+key)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
word= chr(ord(ch)+key)
ord(ch) gives the integer value for that chr. Adding it with a string gives a TypeError, since the + operator is used differently for integers and strings. If you want key to be an int, you must do:
key = int(input("....")
Then, you can add them together.

Resources