callig str when using functions - python

im writing some code to print a triangle with so many rows but when i try it it says,
how many rows in the triangle 5
Traceback (most recent call last):
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 6, in <module>
triangle(5)
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 5, in triangle
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
TypeError: 'str' object is not callable
anybodyknow whats going on here
the code i am using is
inttrow=int(input("how many rows in the triangle "))
def triangle(row):
for i in range(1,row):
x=int(inttrow)-int(i)
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
triangle(5)

The problem is the punctuation in your print statement. You're printing three strings in succession, but you forgot to put any concatenation operation between them. Try this:
print ((x*(str(" "))) + (int(i)*(str("*"))) + ((int(row)-int(i))*(str(" "))))
Further, why are you doing all these type coercions -- all of those variables already have the proper types. Cut it down to this:
print (x*" " + i*"*" + (row-i)*" ")

You are trying to contatenate strings by placing them near each other in the code like this:
("hello")(" ")("world")
Try that on the command line and see what happens. It is not the syntax of the language you are using. Then try using the plus sign.
"hello" + " " + "world"

Related

why doesn't this work? how do i refer to a list... inside a list

I am trying to make a randomly generated fantasy story, and it is not letting me refer to a list inside a list.
line 36 is the bottom line of the code shown.
I've looked it up and did what it said, but it isn't working! maybe because it was for printing text and a list, not making a list with a list inside it, and I don't understand the error message...
itemA = ["letter ", "scroll ", "message "]
specialPlace = ["waterfall.'", "rock pile.'"]
events = [f"a {mysticalCreature[randint(0,8)]} comes up to you and gives you a {itemA[randint(0,2)]} saying, 'come to the " + specialPlace + ", so you thank them and walk away."]```
Traceback (most recent call last):
File "main.py", line 36, in <module>
events = [f"a {mysticalCreature[randint(0,8)]} comes up to you and gives you a {itemA[randint(0,2)]} saying, 'come to the " + specialPlace + ", so you thank them and walk away."]
TypeError: can only concatenate str (not "list") to str
specialMessage is a list, and you're trying to use + to concatenate it with strings. If you want to choose a random value from it to put there, replace it with random.choice(specialMessage). Otherwise, you need to determine which string in that list you want to use in some other way.
You should probably be using random.choice in the other cases too; as written, if you change the length of any list you have to manually adjust the associated randint calls, while random.choice(mysticalCreature) gets the same result without hard-coding in any magic numbers.
import random
mysticalCreature = ["Fairy ", "Unicorn ", "Vampire (a fairy one) ", "Sasquatch ", "Dragon ", "Pheonix ", "Griffin ", "Satyr ", "Centaur " ]
itemA = ["letter ", "scroll ", "message "]
specialPlace = ["waterfall.'", "rock pile.'"]
events = [f"a {mysticalCreature[random.randint(0,8)]} comes up to you and gives you a {itemA[random.randint(0,2)]} saying, 'come to the " + specialPlace[random.randint(0,1)] + ", so you thank them and walk away."]
print(events)

Wordnet synset - strange list index out of range Error

I started working with nltk and I am attempting to generate a function that would allow me to pass in an adjective, extract the first synset from wordnet and print it alongside its antonym. Her is my code:
def placementOperator(wordItem):
wordnet_lemmatizer = WordNetLemmatizer()
placementItem = wordnet_lemmatizer.lemmatize(wordItem,'a')
print("The placementItem is: " + placementItem)
iterationSet = wn.synsets(placementItem, 'a')
if iterationSet[0]:
print(" This is the SS NAME : " + iterationSet[0].name())
for j in iterationSet[0].lemmas():
print(" This is the LEMMAAAA: " + j.name())
if j.antonyms():
print(" This is the RElATIONSHIP " + j.name(), j.antonyms()[0].name())
else: print(" _______> NO ANTONYM!")
else: pass
I am almost there, except that my interpreter throws a 'list out of range' exception. I know that I can't call a list position that doesn't exist and I know that this error occurs when one tries to do so. But since I am explicitly testing for this with if iterationSet[0] I am not sure how I am ending up with the error anyways.
Any advice would be highly appreciated.
Her is the error:
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 57, in <module> preProcessor(0)
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 54, in preProcessor placementOperator(each_element[0])
File "C:/Users/Admin/PycharmProjects/momely/associate/associate.py", line 31, in placementOperator if iterationSet[0]:
IndexError: list index out of range
Most likely, wn.synsets(placementItem, 'a') returned you an empty list. This can happen if placementItem isn't in wordnet.
Therefore, when you did iterationSet[0], it throws an out of range exception. Instead, you can change your check to be :
if iterationSet:
print( ....
....
instead of
if iterationSet[0]:
print(...

Data Organizing in Python 3.4 3

In Python I am using this file Criteria.txt and it looks like this
Homework,5,10,10
Quiz,3,20,20
Midterm,1,50,30
Final,1,100,40
I typed in this code to open and manipulate the Criteria.txt file
criteria=open('Criteria.txt','r')
criteria_line=criteria.readline()
for criteria_line in criteria:
print (criteria_line),
criteria_myline = criteria_line.strip().split(',')
print ("Assignment Type: "+criteria_myline[0])
print ("Number: "+ criteria_myline [1])
print ("Points: "+ criteria_myline [2])
print ("Weight: "+ criteria_myline [3])
print ()
The result was this
(None,)
Assignment Type: Quiz
Number: 3
Points: 20
Weight: 20
Midterm,1,50,30
(None,)
Assignment Type: Midterm
Number: 1
Points: 50
Weight: 30
Final,1,100,40
(None,)
Assignment Type: Final
Number: 1
Points: 100
Weight: 40
This was all correct except Homework didn't show up. You can see in the Criteria.txt file that Homework was the first assignment type in the list. What is wrong with this code? Why did it leave Homework out?
This happens because you read the first line of the file before your for loop starts. This causes the cursor in the file object to move to the next line, so when you iterate through for criteria_line in criteria, you're excluding the very first line (the one that includes Homework). If you remove the line
criteria_line = criteria.readline()
it should work.
This all works because a file object is an iterable and python will iterate over the lines in the file by default.
The line
criteria_line=criteria.readline()
reads the first line, the one containing Homework. In the following for loop, you immediately discard this first result.
When you criteria_line=criteria.readline(), you've already consumed one line from your file object criteria which is Homework,5,10,10, a fix is to read whenever you need the data in the for loop and as side note use with context opening file for better & safer coding:
with open('Criteria.txt') as criteria
for criteria_line in criteria:
#print (criteria_line) #for debugging
criteria_myline = criteria_line.strip().split(',')
print ("Assignment Type: "+criteria_myline[0])
print ("Number: "+ criteria_myline [1])
print ("Points: "+ criteria_myline [2])
print ("Weight: "+ criteria_myline [3])
print ()

How to define a variable inside the print function?

I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some input from the user.
The following works fine:
>>> print (" Hello " + input("tellmeyourname: "))
tellmeyourname: dfsdf
Hello dfsdf
However if I want to assign user's input to a variable, I can't:
>>> print (" Hello ", name = input("tellmeyourname: "))
tellmeyourname: mike
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
print (" Hello ", name = input("tellmeyourname: "))
TypeError: 'name' is an invalid keyword argument for this function
I have researched inside here and other python documentation, tried with %s etc. to solve, without result. I don't want to use it in two lines (first assigning the variable name= input("tellmeyourname:") and then printing).
Is this possible?
Starting from Python 3.8, this will become possible using an assignment expression:
print("Your name is: " + (name := input("Tell me your name: ")))
print("Your name is still: " + name)
Though 'possible' is not the same as 'advisable'...
But in Python <3.8: you can't. Instead, separate your code into two statements:
name = input("Tell me your name: ")
print("Your name is: " + name)
If you often find yourself wanting to use two lines like this, you could make it into a function:
def input_and_print(question):
s = input("{} ".format(question))
print("You entered: {}".format(s))
input_and_print("What is your name?")
Additionally you could have the function return the input s.
no this is not possible. well except something like
x=input("tell me:");print("blah %s"%(x,));
but thats not really one line ... it just looks like it

Python - Reading binary file with offsets and structs

I've recently gotten back into programming and decided as a project to get me going and motivated I was going to write a character editor for fallout 2. The issue I'm having is after the first few strings I can't seem to pull the data I need using the file offsets or structs.
This is what I am doing.
The file I Am working with is www.retro-gaming-world.com/SAVE.DAT
import struct
savefile = open('SAVE.DAT', 'rb')
try:
test = savefile.read()
finally:
savefile.close()
print 'Header: ' + test[0x00:0x18] # returns the save files header description "'FALLOUT SAVE FILE '"
print "Character Name: " + test[0x1D:0x20+4] Returns the characters name "f1nk"
print "Save game name: " + test[0x3D:0x1E+4] # isn't returning the save name "church" like expected
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0]) # is expected to return the current experience but gives the follosing error
output :
Header: FALLOUT SAVE FILE
Character Name: f1nk
Save game name:
Traceback (most recent call last):
File "test", line 11, in <module>
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0])
struct.error: unpack requires a string argument of length 2
I've confirmed the offsets but it just isn't returning anything as it is expected.
test[0x08:0x04] is an empty string because the end index is smaller than the starting index.
For example, test[0x08:0x0A] would give you two bytes as required by the h code.
The syntax for string slicing is s[start:end] or s[start:end:step]. Link to docs

Categories