This is error is point towards this line of code:
s = str(input("Enter the String to be reversed:"))
def print_backward(string):
if len(string) == 0:
return string
else:
return print_backward(string[1:]) + string[0]
s = str(input("Enter the String to be reversed:"))
print(print_backward(s))
This appears to work perfectly. Maybe include something like this to make input work on Python 2 and 3.
try:
input = raw_input
except NameError:
pass
Related
For the get_letter_from_user function, while using the while loop for validation, it keeps repeating the invalid input; I want to make sure that it is a single letter and lower case, and I want to make sure that it doesn't equal the second parameter of the function. I'm not sure what I'm doing wrong, though. (and how to get gud at coding if u have tips)
def get_text_from_user(prompt):
return input(prompt).lower()
def get_letter_from_user(prompt, not_allowed):
not_allowed = ''
allowed = input(prompt).lower()
while not allowed == not_allowed or allowed.isalpha() or len(allowed) > 1:
allowed = str(input('Invalid letter, try again:'))
return allowed
def main():
text = get_text_from_user("Enter some text: ")
ltr1 = get_letter_from_user("Enter a letter: ", '')
ltr2 = get_letter_from_user("Enter another letter: ", ltr1)
new_text = text.replace(ltr1,ltr2)
print("The new text is", new_text)
if __name__ == "__main__":
main()
Suggestion for the function:
def get_letter_from_user(prompt, not_allowed):
allowed = input(prompt).lower()
while allowed == not_allowed or len(allowed) > 1:
print('not_allowed:',not_allowed)
allowed = str(input('Invalid letter, try again:'))
return allowed
ltr1 = get_letter_from_user("Enter a letter: ", '')
ltr2 = get_letter_from_user("Enter another letter: ", ltr1)
Sample output:
Enter a letter: d
Enter another letter: d
not_allowed: d
Invalid letter, try again:d
not_allowed: d
Invalid letter, try again:a
To replace a letter or sequence of letters in a string, you might want to take a look at the string.replace() function:
text = input('Enter some text: ')
find = input('Enter a letter to replace: ')
replace_with = input(f'Enter a letter to replace \'{find}\' with: ')
replaced = text.replace(find, reolace_with)
print('The new text is:', replaced)
To add another little detail because you asked how to get better at coding:
I would never make a function with a parameter that is immediately changed to an empty string. Like:
def get_letter_from_user(prompt, not_allowed):
not_allowed = ''
Rather use a default value like this:
def get_letter_from_user(prompt, not_allowed=''):
...
I am trying to solve an exercise in python3 and I can't get it to work.
I have this code:
def mask_string(string3):
"""Mask string"""
s = string3[-4:].rjust(len(string3), "#")
masking_string = ""
string3_length = len(s)
result = multiply_str(masking_string, string3_length) + s
return result
def multiply_str(string3, masking_string):
"""Mulitply string"""
new_multiply_str = string3 * int(masking_string)
return new_multiply_str
And I am running it like this:
elif choice == "10":
string3 = input("Enter a string that will replace all of the caracters with # exept the 4 last ones: ")
print(marvin.mask_string(string3))
masking_string = input("Enter number: ")
print(marvin.multiply_str(string3, masking_string))
And I get this error when I run it:
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Would really appreciate some help, and please dumb it down a lot when explaining because I am new to python and still do not understand a lot of how to do things.
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Therefore your masking_string was "" which is not a valid number (integer or not). You must have pressed enter without entering a number.
If you want to prevent this, wrap your input routine in a loop and only return when you have a number:
def get_int():
while True:
x = input("Number: ")
try:
return int(x)
except ValueError:
print(f"Invalid input {x}, try again...")
This program essentially encodes and decodes a message and code respectively. I only did the decoding part so far. However I keep getting an EOF error even though I made sure to end parentheses, checked my syntax and kept tampering with it. Unfortunately no luck. Anyone know why this error keeps popping up? I would greatly appreciate it. Also I copied both files that i'm using.
from LetterCodeLogic import LCL
def main():
print("Welcome to the LetterCode program")
choice = getChoice()
while choice !=0:
if choice == 1:
#Encode logic...
print()
elif choice == 2:
#Decode logic...
msg = input("Enter your numbers to decode (separate with commas): ")
#send msg to Decode function in LCL class (LetterCodeLogic.py file)
result = LCL.Decode(msg)
print("Your decoded message is: \n" + result)
else:
print("Unknown process...")
print()
choice = getChoice()
print("Thanks for using the Letter Code program")
def getChoice():
c = int(input("Choice? (1=Encode, 2=Decode, 0=Quit): "))
return c
if __name__ == "__main__":
main()
class LCL:
"""Encode/Decode Functions"""
#staticmethod
def Decode(msg):
#separate numbers from msg string (e.g., "1,2,3")
nums = msg.split(",") #produces list of separate items
result = ""
for x in nums:
try:
n = int(x.strip()) #remove leading/trailing spaces...
if n == 0:
c = " "
elif n < 0 or n > 26:
c = "?"
else:
#ASCII scheme has A=65, B=66, etc.
c = chr(n+64)
except ValueError:
c = "?"
result += c #same as: result = result + c
return result
#staticmethod
def Encode(msg):
the "#staticmethod" and "def Encode()" function was empty and that was the end of line parsing error. When I was coding this and ran it, it ran with no problems. So I removed it for the time being.
I have a try/except statement:
def get_file():
myfile = input("Enter the name of the file to read:\n")
try:
open_myfile = open(myfile, "r")
return open_myfile
except:
print('Could not open file.')
get_file()
And then a function if the code works to check the spelling:
def checktext(textfile):
sp = spellchecker(textfile)
lines_text = textfile.readlines()
true = 0
false = 0
for line in lines_text:
for word in line.split():
c_word = sp.check(word)
if c_word == True:
true =+ 1
else:
print("Possible Spelling Error on line", lines_text.index(line),":",c_word)
false = false + 1
percent = ((true)/(true+false))*100
print(false, "words that passed the spell checker.")
print(true, "words failed the spell checker.")
print(percent, "% of words passed.")
This works if I input a usuable file initially. If I put input anything other than a usable file, it will allow me to input another usable file, however, the code then will give me the attribute error:
'NoneType' object has no attribute 'readlines'. I am not sure why the code works when I just put in the correct file and then doesn't if get_file() passes though the except statement.
My code takes a regular paragraph file and switches it up to ROT13 characters.
I keep getting the error ("TypeError: write() argument must be str, not None") and have no idea why/what it's talking about.
My code works fine outputting everything correctly into the file, but this error is really bugging me.
Function
# Constants
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ROT13_ALPHABET = "NOPQRSTUVWXYZABCDEFGHIJKLM"
def code_ROT13(file_variable_input, file_variable_output):
line = file_variable_input.readline().strip()
alphabet_list = list(ALPHABET)
rot13_list = list(ROT13_ALPHABET)
while line != "":
for letter in line:
rot13_edit = False
for i in range(len(alphabet_list)):
if letter == alphabet_list[i] and not rot13_edit:
letter = rot13_list[i]
rot13_edit = True
elif letter == alphabet_list[i].lower() and not rot13_edit:
letter = rot13_list[i].lower()
rot13_edit = True
file_variable_output.write(letter)
line = file_variable_input.readline()
Main
# Imports
from cipher import code_ROT13
# Inputs
file_name_input = input("Enter input file name: ")
file_name_input = "code.txt"
file_variable_input = open(file_name_input, "r")
file_name_output = input("Enter output file name: ")
file_name_output = "code_ROT13.txt"
file_variable_output = open(file_name_output, "w")
# Outputs
editversion = code_ROT13(file_variable_input, file_variable_output)
file_variable_output.write(editversion)
file_name_input.close()
A function with no return, returns None. You've assigned that to editversion, which you then attempt to write to a file.
However, your method accepts the file as a parameter and is already writing to it.
Just call this. Remove the equals before it and the line after it
code_ROT13(file_variable_input, file_variable_output)