write a file after create some random strings [duplicate] - python

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

Related

Why an extra none type str is returning?

Here is my code in Python for returning a string in capitalized :
import math
import os
import random
import re
import sys
def solve(s):
name = list(s.split())
for i in range(len(name)):
nparts = name[i].capitalize()
return print (nparts, end = " ")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
When I run only the function then the result is ok, but when I try to write the result in a file then I get the error below :
fptr.write(result + '\n')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
By manually checking I found that when I am storing the result into the result variable it also gets an extra value "None". I have no idea why this is going on. Please help.
Your def solve(s): function doesn't return anything so by default it returns None
Fix it to:
def solve(s):
name = list(s.split())
return name
To capitalize each word a sentence :
split it
loop on it to capitalize each word
join them by space
import os
def solve(sentence):
return " ".join(word.capitalize() for word in sentence.split())
if __name__ == '__main__':
s = input("Give a sentence: ")
result = solve(s)
with open(os.environ['OUTPUT_PATH'], 'w') as fptr:
fptr.write(result + '\n')
When the programmer does not define functions to return anything, Python function by default return None. This is the thing that is happening in your program.
The function solve does not return anything and so returns None which gets stored in the variable result when the function is called
A change that you can make in your program is to return the name.
def solve(s):
name = list(s.split())
return name
Also, in your program, a return statement cannot be used within a for block.
Moreover, name is not defined in your main program. A tip to fix it would be to change the variable name from name to result in your for loop and place the for block after calling the function:
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
name = solve(s)
for i in range(len(name)):
nparts = name[i].capitalize()
print (nparts, end = " ")
fptr.write(name[0] + '\n')
fptr.close()

Assistance with TypeError:write() argument must be str, not None

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)

Difficulties with an unruly program

I have been working on this code for a couple of hours now, and I am rather unsure what the problem is.
import random#imports random
import os#Imports os
print("Welcome to the maths quiz") # Welcomes user to quiz
score = (0)
def details():
plr_name = input ("Please Input Name:") # Asks user for name
plr_class = input("Input class number: ") # Asks the user for class numer
return (plr_name, plr_class)
def Q():
while qno < 10: # loops while qno is under 10
ran_num1 = random.randint(1,99) # Generates the first random number
ran_num2 = random.randint(1,99) # Generates the second random number
ran_fun = random.choice("X-+") # Picks a random function
print(ran_num1,ran_fun,ran_num2,"=") # Prints the Sum for the user
if ran_fun == "X":
sum_ans = ran_num1 * ran_num2 # Does the sum if it is a multiplication
if ran_fun == "+":
sum_ans = ran_num1 + ran_num2 # Does the sum if it is a addition
if ran_fun == "-":
sum_ans = ran_num1 - ran_num2 # Does the sum if it is a subtraction
plr_ans = int(input()) # Gets the user's answer
if plr_ans == sum_ans:
print("Correct!") # Prints correct
score = score + 1 # Adds 1 to score
else:
print("Incorrect!")
qno = qno + 1 # Adds 1 to qno
def plr_list_make(lines, listoreder):
index = 0
plr_names =[]
plr_scores =[]
for line in lines:
if listorder == 1:
column =0
rev = False
else:
column = 1
rev = True
return sorted(zip(plr_names, plr_scores),key = lambda x:(x[column]),reverse = rev)
def fileUP(plr_name, score, line ):
found = False
index = 0
for line in lines:
if line.startswith(plr_name):
line = line.strip("\n") + ","+str(score+"\n")
lines[index] = line
found = True
index = index + 1
if not found:
lines.append(plr_name+"|" +str(score)+"\n")
return lines
def save (plr_name, plr_class, score):
filename = "QuizScore_"+plr_class+".txt"
try:
fileI = open(filename)
except IOError:
fileI = open(filename, "w+")
fileI = open(filename)
lines = fileI.readlines()
fileI.close
lines = FileUP(plr_name, score, lines)
fileO = open(filename, "w")
fileO.writelines(lines)
fileO.close
def disp_list(): ## intialise_list
student_list=[]
filename = "QuizScore_"+plr_class+".txt"
try:
## open file read into list "lines"
input_file = open(filename)
lines = input_file.readlines() ## read file into list "lines"
input_file.close
student_list = create_student_list(lines, listorder) ### update "lines" with student list as requested by user
## output sorted list
for counter in range(len(student_list)):
print ("Name and Score: ", student_list[counter][0], student_list[counter][1])
except IOError:
print ("no class file!!!")
def menu():
print ("1 Test")
print ("2 Alphabetical")
print ("3 Highscore")
print ("4 Avg Score")
def Run():
selection = 0
while selection != 5:
menu()
option = int(input("Please select option: "))
if option == 1:
name, plr_class = details()
save(name, plr_class, Q())
else:
plr_class = input("input class ")
disp_list(plr_class, option-1)
Run()
Errors:
Traceback (most recent call last):
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 117, in
Run()
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 113, in Run
save(name, plr_class, Q())
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 74, in save
lines = FileUP(plr_name, score, lines)
NameError: global name 'FileUP' is not defined
Line 110:
name, plr_class = details()
But the details function does not return anything - so Python tries to assign the default return value None to the tuple name, plr_class. It can't do this, because None is not an iterable (you can't assign two things to it). To fix it, add the following line to your details function:
return (plr_name, plr_class)
(I haven't tested this.)
I like your game but it's buggy as a mofo :P
score and qno aren't properly defined. Define them in the functions that need them, define them globally or pass them to the relevant functions as arguments.
details() doesn't return anything but you still attempt to use its output to define two other variables. Add return (plr_name, plr_class) to details()
Every time you cast user input to int without checking its value, your program will crash if an int can't be cast. This applies here:
option = int(input("Please select option: "))
here
plr_ans = int(input())#Gets the user's answer
and elsewhere.
Since your program is input-heavy you could make a a function to which you pass the expected datatype and an optional string to display to the user. This way you wouldn't have to write try/except 10 times and your program wouldn't crash on unexpected input.
In def fileUP(plr_name, score, line ): you have for line in lines: but lines isn't defined. Thus, the save() function that calls FileUP() also fails. Also, FileUP and fileUP are not the same thing. You call the function with a capital "f" but the defintion of the function calls it fileUP with a lower case "f".
While we're at it, the file handling in def save (plr_name, plr_class, score):looks weird. The standard way of opening files for simple reading and writing in Python is via with open().
disp_list() should take one or two arguments but it doesn't at the moment so this error is raised:
TypeError: disp_list() takes 0 positional arguments but 2 were given
These 2 positional arguments were given here:
disp_list(plr_class, option-1)

sort() won't work? Keep getting NoneType back [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 5 months ago.
So I've been working on a program that can read a file that with multiple names in it and I just need to make it so it sorts the names now.
Something like this:
Bob
Bill
Tim
Tom
Rich
Into a list like above but sorted! PrList.sort() is where I need help and it's in the main function.
def readfile(filename):
infile = open(filename, "r")
filetext = infile.read().splitlines()
infile.close()
return filetext
def printlist(list):
for i, item in enumerate(list):
print(i, ': ', item, sep="")
def linear_search(search, value):
for i in range(len(search)):
if search[i] == value:
return i
def main():
filename = input('File name: ')
print()
read = readfile(file)
PrList = printlist(read)
print()
PrList.sort()
while True:
name = input('Enter the name a name: ')
if name == 'quit':
sys.exit()
else:
ls = linear_search(read, name)
print('The position of', name, 'is: \nLinear search: ', ls)
print()
main()
Error message:
Traceback (most recent call last):
File "C:\Python34\lab10c.py", line 47, in <module>
main()
File "C:\Python34\lab10c.py", line 36, in main
PrList.sort()
AttributeError: 'function' object has no attribute 'sort'
PrList = printlist(read)
function printlist() return None as default,you just print out the list,instead ,you should return it.

Python Printing the String Result

import operator
def mkEntry(file1):
results = []
for line in file1:
lst = line.rstrip().split(",")
lst[2] = int(lst[2])
results.append(lst)
return print(sorted(results, key=operator.itemgetter(1,2)))
def main():
openFile = 'names/' + 'yob' + input("Enter the Year: ") + '.txt'
file1 = open(openFile)
mkEntry(file1)
main()
File:
Emily,F,25021
Emma,F,21595
Madison,F,20612
Olivia,F,16100
Joaquin,M,711
Maurice,M,711
Kade,M,701
Rodrigo,M,700
Tate,M,699
How do I print out the result looks like this:
1. Name (Gender): Numbers
Instead of ['name', 'gender', numbers]
I have trouble doing the string thing. It won't give me the good output. Any help?
Thanks
return print(sorted(results, key=operator.itemgetter(1,2))) isn't doing what you'd expect it to.
Because print() returns None, your function will return None. Get rid of the print statement (if you want to print the line, just put it before the return)
Then you can do in your main() function:
for person in mkEntry(file1):
print("1. {0} ({1}): {2}".format(*person))

Categories