This question already has answers here:
Making a string out of a string and an integer in Python [duplicate]
(5 answers)
Closed 8 years ago.
Here is a simplified snapshot of my code:
def getExamPoints(examPoints):
totalexamPoints = 0
return totalexamPoints
def getHomeworkPoints(hwPoints):
totalhwPoints = 0
return totalhwPoints
def getProjectPoints(projectPoints):
totalprojectPoints = 0
return avgtotalprojectPoints
def computeGrade(computeGrade):
computeGrade = 1
return computeGrade
def main ( ):
gradeReport = "\n\nStudent\t Score\tGrade\n=====================\n"
studentName = input ("Enter the next student's name, or 'quit' when done: ")
while studentName != "quit":
examPoints = getExamPoints(studentName)
hwPoints = getHomeworkPoints(studentName)
projectPoints = getProjectPoints(studentName)
studentScore = examPoints + hwPoints + projectPoints
studentGrade = computeGrade (studentScore)
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore + "\t" + studentGrade**
main ( ) # Start program
Getting an error on gradeReport assignment on last line which says "can't convert int object to str implicitly". Why is it so?
This is the line in question:
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore+"\t"+studentGrad
You should use string formatting instead of simply adding strings and ints together (which is an error). One way would be:
gradeReport = '%s\n%s\t%6.1f\t%s' % (gradeReport, studentName, studentScore, studentGrade
There are other ways, but since you were already using % formatting, I've continued that here
In Python, "5" + 5 is an error, because it's ambiguous. Should it return "55"? 10? Rather than make assumptions and be wrong half the time, Python requires you to be explicit about it.
Related
This question already has an answer here:
Why does the print function return None?
(1 answer)
Closed last year.
import random
class simulate_DNA:
def create_DNA(length):
sequence = ""
for i in range(length):
sequence = sequence + random.choice("ATGC")
return print(sequence)
def main():
length = 10
output_file = input("Enter output file path and name: ")
output_file = open(output_file, "w")
for i in range(10):
# simulate_DNA.create_DNA(length)
output_file.write(simulate_DNA.create_DNA(length))
output_file.readline()
output_file.close()
if __name__ == '__main__':
main()
I got this error after running the code above: TypeError: write() argument must be str, not None
Would anyone please tell me how to fix this error? Thank you so much!
The print function returns None, and you're trying to return the result of the print function => So it's None
Replace this:
return print(sequence)
By:
return sequence
studentList= list()
courseList = list()
class Student:
def StudentInfo():
NumberOfStudent = int(input("How many students in this class?"))
for i in range (NumberOfStudent):
print("student no "+ " ", i+1)
id = input ("id:")
name = input ("name:")
DoB = input ("Date of birth: ")
student = {
"id" : id ,
"name" : name,
"DoB" : DoB
}
studentList.append(student)
def ListStudent():
NumberOfStudent = len(studentList)
for i in range (NumberOfStudent):
print ("No" + i+1 +":" + studentList[i] )
return
StudentInfo()
ListStudent()
In the following line of code, you are trying to concatenate str ("No" and ":") with int (i+1).
print ("No" + i+1 +":" + studentList[i] )
You should convert the no-str datas to str like this:
print ("No" + str(i+1) +":" + str(studentList[i]))
Another solution is to use f-string like this (put f before your string and your variables between {.}):
print (f"No{i+1}:{studentList[i]}")
As the error says, you can't concatenate a string and an integer. You can resolve this by turning the integer into a string via int_as_str = str(i+1) and then using the variable int_as_str (with a better name).
A more general thing you should do here, though, is use f-strings for formatting strings like this. For example, you should use print(f"No {i+1}: {studentList[i]}". Putting the f at the beginning of the string allows you to call variables directly inside the {}.
I am making an online game using the sockets module and pygame in python.
def read_pos(str):
if str is not None:
string = str.split(",")
return int(string[0]), int(string[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
def redrawWindow(win,player, player2):
win.fill((255,255,255))
player.draw(win)
player2.draw(win)
pygame.display.update()
def main():
run = True
n = Network()
startPos = read_pos(n.getPos())
p = Player(startPos[0],startPos[1],100,100,(0,255,0))
p2 = Player(0,0,100,100,(255,0,0))
clock = pygame.time.Clock()
while run:
clock.tick(60)
p2Pos = read_pos(n.send(make_pos((p.x, p.y))))
p2.x = p2Pos[0]
p2.y = p2Pos[1]
p2.update()
This is the code I'm using in my client. in my server, the code is as follows
def convertPos(str):
if str is not None:
str = str.split(",")
return int(str[0]), int(str[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
pos = [(0,0),(100,100)]
def threaded_client(conn,player):
conn.send(str.encode(make_pos(pos[player])))
reply = " "
while True:
try:
data = conn.recv(2048).decode()
pos[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = (pos[0])
else:
reply = (pos[1])
print("Received: ", data)
print("Sending : ", reply)
conn.sendall(str.encode(make_pos(reply)))
except:
break
print("Lost connection")
conn.close()
I am getting the error of ValueError: invalid literal for int() with base 10: ' '.
Can someone tell me why this is happening? The value of str in the function of convertPos() is coming in as a tuple which I am converting into a string and after that into an integer.
As you have converted it to string, the format you have is (x,y), you need to remove the brackets. You need to rewrite your convertPos function as:
def convertPos(str):
if str is not None:
str=str.strip("()")
str = str.split(",")
return int(str[0]), int(str[1])
EDIT You are not using the else part, so you can remove it.
And as #Azat Ibrakov says, you should not convert the tuple to an string, but if you need to do it, you can use ast.literal_eval like this:
import ast
def convertPos(str):
return ast.literal_eval(str)
or use it directly in place of the convertPos function.
Obviously - as others have pointed out, the returned error is because you're trying to convert an empty string (or spaces) to an integer.
But the real issue is that the incoming co-ordinate is malformed. The code is not catching this error. You can write lots of code to determine what the error is, and report an accurate error. Or just plough-on as if everything is fine, but also catch any exception with a reasonable error message.
def convertPos(str):
coord = None
try:
parts = str.split( ',', 2 )
x = int( parts[0] )
y = int( parts[1] )
coord = ( x, y )
except:
raise ValueError( 'Malformed co-ordinate string [' + str.strip() + ']' )
return coord
I suspect the socket code is not buffering a full packet, and maybe what's being processed is something like 122,, whereas the socket buffering needs to keep reading until a full co-ordinate has arrived.
So you could space-pad your co-ordinates to say a block of 11 characters - that way you know you must have received 11 characters to have a valid co-ordinate string. Alternatively use and end-of-coord marker, like a |, and then the socket code keeps buffing the input co-ordinate until that | arrives.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to make a function to find names of python functions in a file
for a python class I have no idea why it's only returning one comma that I add in between the function names
def pythonanalysis(s):
pythonlen = str(s.count("\n"))
functionname = ''
funcdoc = s
counter = 0
while funcdoc.find("def") != -1:
function = funcdoc.find("def")
funcdoc = funcdoc[function + 4:funcdoc.find("(")]
functionname += funcdoc[:funcdoc.find("(")] + ", "
counter += 1
print(functionname)
forlen = str(s.count("for"))
iflen = str(s.count("if"))
whilelen = str(s.count("while"))
authnum = s.find('__author__ =')
author = s[authnum + 14:]
authname = author[:author.find('\'')]
return "There are " + pythonlen + " lines in this file \n\
There are "+ str(counter) + " functions in this document named: " + functionname + "\n\
There are " + forlen+" for loops and " + iflen + " if loops and " + whilelen + " while loops\n\
The author is " + authname
function = funcdoc.find("def")
funcdoc = funcdoc[function + 4:funcdoc.find("(")]
The "(" that you find could quite possibly be BEFORE the "def", which would result in an empty string here! Even if you did find the "(" that's just after the function name, you discard the entirety of the file after that point, so you could never find more than one function. Hint: the str.find() method takes an optional second parameter that specifies the starting point of the search.
This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()