creating decorated plaque for text - python

The output should be as follows:
Input:
Give the text: hippo
Give the character: x
Output:
xxxxxxx
xhippox
xxxxxxx
Input 2:
Give the text: sausage
Give the character: **
Output 2:
Invalid input! Type only one character!
The code im using:
text = input("Give the text: ")
plaque = input("Give the character: ")
def make_plaque(string):
decorated = 'plaque' * (len(string) + 2) + "\n" #top row
decorated = decorated + 'plaque' + string + "*\n" #middle row
decorated = decorated + 'plaque' * (len(string) + 2) + "\n" #bottom row
return decorated
plaque = make_plaque(text)
print(plaque)
Trying to make it work but still unsuccessful

You should really state your issue better. I assume the issue is that you don't have any error checking for your expected single character input. I would use a loop.
not_valid = True
plaque_char = ""
while not_valid:
plaque_char = input("Give the character: ")
if len(plaque_char) != 1:
print("Please enter one character.")
else:
not_valid = False
Using this code to manage the input of your plaque character should give you the desired error checking. However you can play with it to get it to detect multiple character or no characters if you want. I think; my syntax is good, but I've been using a lot of C++ lately, so if it is off sorry.

text = input("Give the text: ")
char_check=False
while char_check is False:
plaque = input("Give the character: ")
if len(plaque)>1:
print("Invalid input! Type only one character!")
else:
char_check=True
def make_plaque(string):
decorated = plaque * (len(string) + 2) + "\n" #top row
decorated = decorated + plaque + string + "{}\n".format(plaque) #middle row
decorated = decorated + plaque * (len(string) + 2) + "\n"#bottom row
return decorated
plaque = make_plaque(text)
print(plaque)
this code will do!

Related

Issue checking input type in Pyton 2.7 vs Python 3

I need to re-use a script I wrote in Python 3.10 using Python 2.7; when I change the interpreter to 2.7, script below errors with following message: TypeError: unbound method CheckInput() must be called with Elem instance as first argument (got int instance instead)
Trying to resolve this for hours but I'm a beginner and am definitely missing something. Aim of the program is to add a few values as user input and later on print them out. Code below:
class Elem():
Elem_count = 0
def CheckInput(input):
try:
# Convert it into integer
val = int(input)
except ValueError:
try:
# Convert it into float
val = float(input)
except ValueError:
print("You have entered a string, please use numbers!")
def Add_Elem(self):
if Elem.Elem_count == 0:
print('Enter first Elem info:')
self.width = input('width: ')
Elem.CheckInput(self.width)
self.height = input('Height: ')
Elem.CheckInput(self.height)
self.depth = input('depth: ')
Elem.CheckInput(self.depth)
else:
print('Enter second Elem info:')
self.width = input('width: ')
Elem.CheckInput(self.width)
self.height = input('Height: ')
Elem.CheckInput(self.height)
self.depth = input('depth: ')
Elem.CheckInput(self.depth)
Elem.Elem_count += 1
if Elem.Elem_count > 2:
exit
def Display_Elem(self):
print('\n')
if Elem.Elem_count == 0:
print('Element ')
print('width: ' + self.width)
print('Height: ' + self.height)
print('Depth: ' + self.depth)
else:
print('Element ')
print('width: ' + self.width)
print('Height: ' + self.height)
print('Depth: ' + self.depth)
def main():
First_Elem = Elem()
Second_Elem = Elem()
First_Elem.Add_Elem()
Second_Elem.Add_Elem()
print ("Elements added:")
First_Elem.Display_Elem()
Second_Elem.Display_Elem()
if __name__ == "__main__":
main()
Your issue is here:
def CheckInput(input):
For a normal class method, you'll have a definition like this:
def my_method(self, some_parameter):
The self here refers to the class. While you can pass in some other class, the behavior quickly becomes undefined. Your TypeError points to this, though: CheckInput() must be called with Elem instance as first argument (got int instance instead).
This means an int was passed - which is likely the parameter you meant. All you need is this:
def CheckInput(self, candidate_input):
try:
val = int(candidate_input)
except ValueError:
try:
val = float(candidate_input)
except ValueError:
print(f"Could not convert '{candidate_input}' to a number!")
return val
Note the change of input to candidate_input to avoid builtin name collision, and the use of the candidate input in the output string to allow the user to understand what was happening with bad input.
Also, it's likely that you want to return the value that you have - though it's not great design to have a function that returns one of two types of numbers.
To me the easiest fix would be to remove the checkinput method from your elem class ; it is useless for it to be in the class because it doesn't use the attributes of the class.
Also, you shouldn't name a variable "input" as it is the name of a builtin in both Python 2 and Python 3.
def CheckInput(data):
try:
# Convert it into integer
val = int(data)
except ValueError:
try:
# Convert it into float
val = float(data)
except ValueError:
print("You have entered a string, please use numbers!")
class Elem():
Elem_count = 0
def Add_Elem(self):
if Elem.Elem_count == 0:
print('Enter first Elem info:')
self.width = input('width: ')
CheckInput(self.width)
self.height = input('Height: ')
CheckInput(self.height)
self.depth = input('depth: ')
CheckInput(self.depth)
else:
print('Enter second Elem info:')
self.width = input('width: ')
CheckInput(self.width)
self.height = input('Height: ')
CheckInput(self.height)
self.depth = input('depth: ')
CheckInput(self.depth)
Elem.Elem_count += 1
if Elem.Elem_count > 2:
exit
def Display_Elem(self):
print('\n')
if Elem.Elem_count == 0:
print('Element ')
print('width: ' + self.width)
print('Height: ' + self.height)
print('Depth: ' + self.depth)
else:
print('Element ')
print('width: ' + self.width)
print('Height: ' + self.height)
print('Depth: ' + self.depth)

too many positional arguments in python

Explanation
I am currently writing a code that simulates a game of hangman, but cheats by attempting to evade the player's guesses by changing the word. The class and methods are defined in hangman.py, while play_hangman.py calls the instance of Hangman and the play method (cannot be changed per the instructions of the assignment).
Problem
In the play method, I received the following error: "
TypeError: askForWordLength() takes 1 positional argument but 2 were given "
I know that this means I am giving too many arguments into the call of the method, but I am unsure of how to change it. I have tried rewriting the 5th line of the following code multiple times to fix this error, but it does not cease:
Specific Section of Code*
def play(self):
MODE = 1
openSession = 1
while(openSession == 1):
word_length = self.askForWordLength(self.words)
num_guesses = self.askForNumOfGuesses()
wordStatus = self.wordStatus(word_length)
letters_already_guessed = []
print()
gameOver = 0
while (gameOver == 0):
if (MODE == 1):
self.printCountOfRemainingWords(self.remainingWords)
self.printGameStats(self.remainingWords. letters_already_guessed,
self.num_guesses, self.wordStatus)
guess = self.askPlayerForGuess(letters_already_guessed)
letters_already_guessed.append(guess)
num_guesses -= 1
remainingWords = self.retrieveRemainingWords(guess, self.remainingWords,
num_guesses, word_length)
wordStatus = self.wordStatus(remainingWords[0], letters_already_guessed)
print()
if (guess in wordStatus):
num_guesses += 1
if ('-' not in wordStatus):
game_over = 1
print('Congratulations! You won!')
print('Your word was: ' + wordStatus)
if (num_guesses == 0 and game_over == 0):
game_over = 1
print('Haha! You Lose')
print('Your word was: ' + remainingWords[0])
print('Thanks for playing Hangman!')
ENTIRE CODE
hangman.py
import re
class Hangman:
# hangman self method
def hangman(self):
self.hangman = Hangman() # object of the Hangman class
def words(self):
with open('dictionary.txt') as file: # opens dictionary text file
file_lines = file.read().splitlines() # reads and splits each line
all_words = [] # empty list to contain all words
valid_words = [] # empty list to contain all valid words
for word in file_lines: # traverses all words in the file lines
if len(word) >= 3: # accepts word if it has at least 3 letters
all_words.append(word) # appends accepted word to list
# list of all invalid characters in python
CHARACTERS = ["~", "`", "!", "#", "#", "$", "%", "^", "&", "*", "(",
")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
"", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]
for i in CHARACTERS: # traverse list of invalids
for word in all_words:
if i not in word: # if invalid character is not in word
valid_words.append(word) # accept and append to list
return valid_words # return list of valid words
def askForWordLength(self, valid_words):
word_lengths = [] # empty list for possible word lengths
for word in valid_words: # traverse list of valid words
length = word.__len__() # record length of current word
if (length not in word_lengths):
word_lengths.append(length) # accept and append to list
word_lengths.sort()
# inform user of possible word lengths
print('The available word lengths are: ' + str(word_lengths[0]) + '-'
+ str(word_lengths[-1]))
print()
# have user choose from possible word lengths
while(1):
try:
length = int(input('Please enter the word length you want: '))
if (length in word_lengths):
return length
except ValueError:
print('Your input is invalid!. Please use a valid input!')
print()
def askForNumberOfGuesses(self):
while(1):
try:
num_guesses = int(input('Enter number of guesses you want: '))
if (num_guesses >= 3):
return num_guesses
except ValueError:
print('Your input is invalid!. Please use a valid input!')
print()
def wordStatus(self, length):
status = '-'
for i in range(0, length):
status += '-'
return
def remainingWords(self, file_lines, length):
words = []
for word in file_lines:
if (word.__len__() == length):
words.append(word)
return words
def printGameStats(self, letters_guessed, status, num_guesses):
print('Game Status: ' + str(status))
print()
print('Attempted Guesses' + str(letters_guessed))
print('Remaining Guesses' + str(num_guesses))
def askPlayerForGuess(self, letters_guessed):
letter = str(input('Guess a letter: ')).lower()
pattern = re.compile("^[a-z]{1}$")
invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None
if (invalid_guess):
while (1):
print()
if (re.match(pattern, letter) == None):
print('Invalid guess. Please enter a correct character!')
if (letter in letters_guessed):
print('\nYou already guessed that letter' + letter)
letter = str(input('Please guess a letter: '))
valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None
if (valid_guess):
return letter
return letter
def retrieveWordStatus(self, word_family, letters_already_guessed):
status = ''
for letter in word_family:
if (letter in letters_already_guessed):
status += letter
else:
status += '-'
return status
def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
wordStatus, guesses_num, word_length,
createWordFamiliesDict,
findHighestCountWordFamily,
generateListOfWords):
word_families = createWordFamiliesDict(remaining_words, guess)
family_return = wordStatus(word_length)
avoid_guess = num_guesses == 0 and family_return in word_families
if (avoid_guess):
family_return = wordStatus(word_length)
else:
family_return = findHighestCountWordFamily(word_families)
words = generateListOfWords(remaining_words, guess, family_return)
return words
def createWordFamiliesDict(self, remainingWords, guess):
wordFamilies = dict()
for word in remainingWords:
status = ''
for letter in word:
if (letter == guess):
status += guess
else:
status += '-'
if (status not in wordFamilies):
wordFamilies[status] = 1
else:
wordFamilies[status] = wordFamilies[status] + 1
return wordFamilies
def generateListOfWords(self, remainingWords, guess, familyToReturn):
words = []
for word in remainingWords:
word_family = ''
for letter in word:
if (letter == guess):
word_family += guess
else:
word_family += '-'
if (word_family == familyToReturn):
words.append(word)
return words
def findHighestCountWordFamily(self, wordFamilies):
familyToReturn = ''
maxCount = 0
for word_family in wordFamilies:
if wordFamilies[word_family] > maxCount:
maxCount = wordFamilies[word_family]
familyToReturn = word_family
return familyToReturn
def printCountOfRemainingWords(self, remainingWords):
show_remain_words = str(input('Want to view the remaining words?: '))
if (show_remain_words == 'yes'):
print('Remaining words: ' + str(len(remainingWords)))
else:
print()
def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
words, wordStatus, printCountOfRemainingWords, printGameStats,
askPlayerForGuess, retrieveRemainingWords):
MODE = 1
openSession = 1
while (openSession == 1):
word_length = askForWordLength(words)
num_guesses = askForNumberOfGuesses()
wordStatus = wordStatus(word_length)
letters_already_guessed = []
print()
game_over = 0
while (game_over == 0):
if (MODE == 1):
printCountOfRemainingWords(remainingWords)
printGameStats(remainingWords, letters_already_guessed,
num_guesses, wordStatus)
guess = askPlayerForGuess(letters_already_guessed)
letters_already_guessed.append(guess)
num_guesses -= 1
remainingWords = retrieveRemainingWords(guess, remainingWords,
num_guesses, word_length)
wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
print()
if (guess in wordStatus):
num_guesses += 1
if ('-' not in wordStatus):
game_over = 1
print('Congratulations! You won!')
print('Your word was: ' + wordStatus)
if (num_guesses == 0 and game_over == 0):
game_over = 1
print('Haha! You Lose')
print('Your word was: ' + remainingWords[0])
print('Thanks for playing Hangman!')```
It looks like you don't understand how classes work or there is a piece of code not shown here. When you define a method in a class, the first argument always refers to the object on which the method operates, which is conventionally called self. Any subsequent arguments are defined how you want. Usually, you don't need to pass the first self argument because it is passed according to the object you use. Any remaining arguments are your responsibility though.
For example:
class Student:
def __init__(self, name, age):
# Initializer (Commonly called Constructor in other languages)
# This is the first method that will run when you create an object and
# it runs automatically (You don't need to call it).
# This is where you'd initialize the state of the object, for example:
# Create a student with name and age.
# name and age are regular parameters of the __init__ method. We'd like
# to save them as attributes of our student object which is represented
# by self.
self.name = name
self.age = age
# Maybe we'd like to save a list of grades too
self.grades = []
def add_grade(self, grade):
# self is our object, and grade is the parameter
self.grades.append(grade)
def get_average(self):
# If we don't need additional parameters, we don't have to, but self is
# mandatory
return sum(self.grades) / len(self.grades)
def print_status(self):
# Note I am calling get_average() and I don't specify self. It's determined automatically.
print("Name:", self.name)
print("Age:", self.age)
print("Average:", self.get_average())
# We created the class, but we need to create some objects to use it.
s1 = Student("Dan", 15)
s2 = Student("Maya", 14)
# Note we only pass the custom parameters we specified which are `grade`
# self is determined by the object we are using (s1 or s2)
s1.add_grade(81)
s1.add_grade(86)
s2.add_grade(89)
s2.add_grade(93)
s1.print_status()
s2.print_status()
I hope this example helps you understand how methods work. In your code, I don't understand why you pass the methods as arguments of the play method and I don't see where you call this method or where you even create a Hangman object, so I can't help further.

input is not changing in iteration

In the code below, I am trying to input the number (e.g. 2 3 4). Suppose if the length of the input is not equal to mat_dim_col, I want to input again. However, the function is retaining the previous input and not returning the latest one.
Matrix row entry function.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
mat_row(mat_dim_col,r)
When you recurse, you need to return the value it provides, otherwise, you might end up getting a correct response after a few attempts but it won't be returned through the stack correctly.
def mat_row(mat_dim_col,r):
inp = input("Enter " +
str(mat_dim_col) +
" values, all space seperated for row " +
str(r) + " : " ).split()
print(inp)
if len(inp) == mat_dim_col:
print(inp)
row_ent = [int(x) for x in inp]
return row_ent
else:
print("Invalid entry, try again!")
""" RETURN mat_row response """
return mat_row(mat_dim_col,r)

CS50 mario python less comfortable .rstrip function

I'm taking the CS50 course and right now I'm on pset6, python Mario code.
For the rstrip() function, it's supposed to remove the new line at the end of the code. I don't know whats going on and its really bugging me (i think its a syntax error but I'm not sure).
Please if any f you could help that would be great!
Note: I am using "+" symbol to represent " " just for personal understanding.
My code:
def input_number(message):
while True:
try:
user_input = int(input(message))
except ValueError:
continue
else:
return user_input
height = input_number("Height: ")
while height < 1 or height > 8:
height = int(input("Height: "))
i = 0
while i < height:
print("\n")
x = height-1
a = 0
while x>=i:
print("+".rstrip("\n"))
x-=1
while a<=i:
print("#".rstrip("\n"))
a+=1
i+=1
#print("\n")
whats getting printed:
Height: 5
+
+
+
+
+
#
+
+
+
+
#
#
+
+
+
#
#
#
+
+
#
#
#
#
+
#
#
#
#
#
expected output:
#
##
###
####
#####
Thanks!
Use end="" in print method rather than using rstrip method.
def input_number(message):
while True:
try:
user_input = int(input(message))
except ValueError:
continue
else:
return user_input
height = input_number("Height: ")
while height < 1 or height > 8:
height = int(input("Height: "))
i = 0
while i < height:
x = height-1
a = 0
while x>=i:
print(" ", end="")
x-=1
while a<=i:
print("#", end="")
a+=1
print("")
i+=1
Output:
Height: 5
#
##
###
####
#####
Explanation:
rstrip is used to remove white spaces from end of a string. For example, when we want to remove unwanted white spaces from user inputted string, we can use rstrip to do so. Another use case of rstrip is to omit white spaces from lines while reading a file.
On the other hand, to format a output string in a desired format we manipulate print method. By default, print method outputs the values in a separate line.
For example,
print("some string")
print("another string")
It will show:
some string
another string
According to print method documentation, we can use string in end argument to overwrite the default end='\n'.
For example,
print("some string", end="......")
print("another string", end="!!!!!!")
It will show:
some string......another string!!!!!!
Reference:
Manual string formatting python documentation
rstrip documentation
print method documentation
It appears that you'd like to remove the \n at the end of the line.
Instead of rstrip use
print("whatever you want to output in here like # or +", end = "").
The reason why rstrip won't work in this usecase is that it strips the string you passed to it which is "#" or "+". There is no \n there, that is added as the end character of print.
def input_number(message):
while True:
try:
user_input = int(input(message))
except ValueError:
continue
else:
return user_input
height = input_number("Height: ")
while height < 1 or height > 8:
height = int(input("Height: "))
i = 0
while i < height:
print("")
x = height-1
a = 0
# while x>=i:
# print("+", end = "")
# x-=1
while a<=i:
print("#", end = "")
a+=1
i+=1
Output:
#
##
###
####
#####
# TODO
while True:
n = int(input("Height: "))
if n > 0 and n < 9:
break
for i in range(0, n, 1):
for j in range(0, n, 1):
if (i+j < n-1):
print(" ", end="")
else:
print("#", end="")
print()
here thats my answer to your question.
the Output is the same :
#
##
###

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories