Here's my code:
import random
ch1=input("Please enter the name of your first character ")
strch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch1+" is:")
print (strch1)
print("and the skill value of "+ch1+" is:")
print (sklch1)
ch2=input("Please enter the name of your second character ")
strch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch2+" is:")
print (strch2)
print("and the skill value of "+ch2+" is:")
print (sklch2)
myFile = open("CharacterSkillAttributes.txt", "wt")
myFile.write("The attributes of "+ch1+" are: /n")
myFile.write("Strength: "+strch1+"/n")
myFile.write("Skill: "+sklch1+"/n")
myFile.write("The attributes of "+ch2+" are: /n")
myFile.write("Strength: "+strch2+"/n")
myFile.write("Skill: "+sklch2+"/n")
myFile.close()
Here's the error:
Traceback (most recent call last):
File "E:\Computing Science\Computing science A453\Task 2\task 2 mostly working (needs 'save to file').py", line 22, in <module>
myFile.write("Strength: "+strch1+"/n")
TypeError: Can't convert 'int' object to str implicitly
I don't want to change the code too much (unless I really have to), just need this problem solved.
Use string formatting to get rid of the error:
file.write('Strength: {0}\n'.format(sklch1))
Obviously you will have to do the same when you write to the file with sklch2.
You should just make a string from your integer variable:
myFile.write("Strength: " + str(strch1) + "/n")
or as suggested Alex use str.format().
The error message tells you exactly that, strch1 is an int and you cannot concatenate it with string directly.
You can do
file.write('Strength: %s\n' % (sklch1))
Related
As the user inputs a different word the length of words will change so I am trying to store the .len() answer in a variable which is not working.
This is what I tried:
letter=input("TYPE A WORD--> ")
letter.upper()
NO=letter.len()
print (NO)
Though there is an error message saying:
Traceback (most recent call last):
File "main.py", line 3, in \<module\>
NO=letter.len()
AttributeError: 'str' object has no attribute 'len'
There is no string.len() function in python.
If you want to find the length of a string, you should use len(string) function.
For example
NO = len(letter)
give letter as argument to len()
NO = len(letter)
Updated code for you
letter=input("TYPE A WORD--> ")
letter=letter.upper()
NO=len(letter)
print (NO)
I have following python script which wants to intake the first argument as a string, reverse it and then print it out
import sys
input = sys.argv[1:]
input_reversed = input[::-1]
print("The input_reversed is: " + input_reversed)
Running it with a call like python test.py abcdef gets me the following error which says:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print("The input_reversed is: " + input_reversed)
TypeError: cannot concatenate 'str' and 'list' objects
What am I dong wrong? sys.argv[1:] does not return a string?
I just want to call python test.py abcdef and get the output as fedcba which is a reverse of abcdef.
If you want the content of each argument to be reversed, in addition to reversing the order of the arguments themselves, join all your arguments together into a string and then reverse that string:
print("The reversed input is: " + ' '.join(sys.argv[1:])[::-1])
Notice the order of operations here. It could be written with more intermediate steps as:
args_list = sys.argv[1:]
args_string = ' '.join(args_list)
reversed_args_string = args_string[::-1]
print("The reversed input is: " + reversed_args_string)
No, it returns a list. You can join a list together using join(). Try this:
print("The input_reversed is: " + ', '.join(input_reversed))
im creating a dice game in python 3.7.2 , i need to write the results to a text file but in the current format im getting errors
Ive tried just casting to a string but that just causes more issues
file = open("dicegamescores.txt","w")
x = str('on round',x,username1 ,'has',player1_score , '\n',username2'has', player2_score)
file.write(x)
file.close
i expected ('on round', x, username1 , 'has', player1_score , '\n' , username2 , 'has', player2_score ) to be written to the file with the correct variable values based on the iteration
but got this:
WHEN NOT CAST TO STR:
Traceback (most recent call last):
File "C:\Users\joelb\AppData\Local\Programs\Python\Python37\dicegame.py", line 45, in <module>
file.write(x)
TypeError: write() argument must be str, not tuple
OR WHEN I CAST TO STR:
Traceback (most recent call last):
File "C:\Users\joelb\AppData\Local\Programs\Python\Python37\dicegame.py", line 44, in <module>
x = str('on round', x, username1 , 'has', player1_score , '\n' , username2 , 'has', player2_score )
TypeError: str() takes at most 3 arguments (9 given)
Hey, you need to make the x variable in a string format.
You can use this code :
file = open("dicegamescores.txt","w")
x = ('on round',2,username1 ,'has',player1_score , '\n',username2,'has', player2_score)
xx = ("%s%s%s%s%s%s%s%s%s")%(x)
file.write(xx)
file.close
For every string in the variable you should add %s.
It should be something like this:
x = 'on round {round} {user1} has {user1score} \n {user2} has {user2score}'.format(
round = x, user1 = username1, user1score = player1_score, user2= username2, user2score = player2_score)
with the .format() method you can insert values into placeholders i.e.round.
When you try to write something to a file the way you do it has to be a string, so that is why the first one fails.
The second one fails, because (as the error says) you try to create a string out of the ungrouped elements. To make this work, the elements should be one array/list so Python can make a proper string out of it:
x = str(['on round',x,username1 ,'has',player1_score , '\n',username2'has', player2_score]) #See the square brackets
However the more pythonic way to do this would be:
x = "on round %s %s has %d \n %s has %d" % (x, username1, player1_score, username2, player2score)
%s inserts a String, %d an integer, %f a float. See Learn Python for an explanation on this.
Im writing a program for Uni to find all the palindromic primes, i have written out the program already but when i run it, my first input gets an error while trying to assign values to the variable.
please could someone tell me why this is the case!
start =input("Enter the start point N:")
starteval= eval(start)
endval = eval(input("Enter the end point M:"))
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse=eval(reverse)
if evalreverse==starteval:
if starteval==2 or starteval==3:
print(starteval)
elif starteval%2==0 or starteval%3==0:
pass
i=5
w=2
a=0
while i<=starteval:
if starteval%i==0:
break
else:
a=True
i+=2
if a==True:
print (starteval)
else:
pass
x+=x+1
the ouput i recieve is
"Enter the start point N:200
Enter the end point M:800
Traceback (most recent call last):
File "", line 1, in <module>
start =input("Enter the start point N:")
Syntax Error: 002: <string>, line 1, pos 3"
please and thank you!
Try instead of the first 3 lines to use:
starteval = int(raw_input("Enter the start point N:"))
endval = int(raw_input("Enter the end point M:"))
In Python 3 integer literals cannot begin with a zero:
>>> i = 002
File "<stdin>", line 1
i = 002
^
SyntaxError: invalid token
Because you are applying the eval function to your string input, Python attempts to parse your input as a valid Python expression, whcih is why you see the error you see.
It would make more sense to use int(input(...)) to get the integer (though you would still have to handle any exceptions raised when the user types a non-integer into your code). This has the advantage that it will accept the input that is causing you trouble in eval.
You could write a small intParsing function, that handles simple input parsing for you, then basically replace every "eval()" function of your code with intParsing().
Here is your edited code:
def intParsing(input_str):
str = ""
# Delete all chars, that are no digits (you could use a regex for that too)
for char in input_str.strip():
if char.isdigit():
str += char
# Now you only got digits in your string, cast your string to int now
r = int( str )
print "result of parsing input_str '", input_str, "': ", r
return r
start =raw_input("Enter the start point N:")
starteval= intParsing(start) # I edited this line
end = raw_input("Enter the end point M:") # I edited this line
endval =intParsing(end) # I edited this line
reverse=""
x=starteval+1
while x<endval:
reverse+=start[::-1]
evalreverse= intParsing(reverse) # I edited this line
I need the contents of a file made by some function be able to be read by other functions. The closest I've come is to import a function within another function. The following code is what is what I'm using. According to the tutorials I've read python will either open a file if it exists or create one if not.What's happening is in "def space" the file "loader.py" is duplicated with no content.
def load(): # all this is input with a couple of filters
first = input("1st lot#: ") #
last = input("last lot#: ") #
for a in range(first,last+1): #
x = raw_input("?:")
while x==(""):
print " Error",
x=raw_input("?")
while int(x)> 35:
print"Error",
x=raw_input("?")
num= x #python thinks this is a tuple
num= str(num)
f=open("loader.py","a") #this is the file I want to share
f.write(num)
f.close()
f=open("loader.py","r") #just shows that the file is being
print f.read() #appened
f.close()
print "Finished loading"
def spacer():
count=0
f=open("loader.py","r") #this is what I thought would open the
#file but just opens a new 1 with the
#same name
length=len(f.read())
print type(f.read(count))
print f.read(count)
print f.read(count+1)
for a in range(1,length+1):
print f.read(count)
vector1= int(f.read(count))
vector2 = int(f.read(count+1))
if vector1==vector2:
space= 0
if vector1< vector2:
space= vector2-vector1
else:
space= (35-vector1)+vector2
count=+1
b= open ("store_space.py","w")
b.write(space)
b.close()
load()
spacer()
this what I get
1st lot#: 1
last lot#: 1
?:2
25342423555619333523452624356232184517181933235991010111348287989469658293435253195472514148238543246547722232633834632
Finished loading # This is the end of "def load" it shows the file is being appended
<type 'str'> # this is from "def spacer" I realized python was creating another
# file named "loader.py with nothing in it. You can see this in the
#error msgs below
Traceback (most recent call last):
File "C:/Python27/ex1", line 56, in <module>
spacer()
File "C:/Python27/ex1", line 41, in spacer
vector1= int(f.read(count))
ValueError: invalid literal for int() with base 10: ''tion within another function but this only causes the imported function to run.
The file probably has content, but you're not reading it properly. You have:
count=0
#...
vector1= int(f.read(count))
You told Python to read 0 bytes, so it returns an empty string. Then it tries to convert the empty string to an int, and this fails as the error says, because an empty string is not a valid representation of an integer value.