This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 5 years ago.
I want to use a function as a String, i have this function:
def getCoins(user): ##Get the Coins from a user.##
try:
with open(pathToUser + user + ".txt") as f:
for line in f:
print(user + " has " + line +" coins!")
except:
print("Error!")
Now it just print the coins, but i want to use it in other codes like this:
client.send_msg(m.text.split(' ')[2] + "has" + coinapi.getCoins('User') + "coins")
How do it do that? So that i can use it like a string, the message in Twitchchat should be:
"USERXYZ has 100 coins"
Return a string
def getCoins(user): ##Get the Coins from a user.##
try:
with open(pathToUser + user + ".txt") as f:
return '\n'.join(user+" has "+line +" coins!" for line in f)
except:
return "Error!"
Also you should use format strings (assuming python 3.6)
def getCoins(user): ##Get the Coins from a user.##
try:
with open(f"{pathToUser}{user}.txt") as f:
return '\n'.join(f"{user} has {line} {coins}!" for line in f)
except:
return "Error!"
You should be able to just return the string you want in the output.
It looks like your code is iterating over f and printing the number of coins on each line, so you may need to return a list or generator of the coins amount, but the key answer to your question is just to return a string or something that can be turned into a string
Related
This question already has answers here:
Getting SyntaxError for print with keyword argument end=' '
(17 answers)
Closed 8 years ago.
This is the function for printing all values in a nested list (taken from Head first with Python).
def printall(the_list, level):
for x in the_list:
if isinstance(x, list):
printall(x, level=level + 1)
else:
for tab_stop in range(level):
print("\t", end='')
print(x)
The function is working properly.
The function basically prints the values in a list and if there is a nested list then it print it by a tab space.
Just for a better understanding, what does end=' ' do?
I am using Python 3.3.5
For 2.7
f = fi.input( files = 'test2.py', inplace = True, backup = '.bak')
for line in f:
if fi.lineno() == 4:
print line + '\n'
print 'extra line'
else:
print line + '\n'
as of 2.6 fileinput does not support with.
This code appends 3 more lines and prints the appended text on the 3rd new line. and then appends a further 16 empty lines.
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed
Eg: - print ("hello",end=" +") will print hello +
See the documentation for the print function: print()
The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.
when I run the program this has been popping up. could not convert string to float. I tried to look it up but I couldn't find anything.
here's the code:
f = open("ticket.txt",'r')
s=f.read()
lines=s.split("\n")
priceMax=0
priceMin=9999
total=0
for line in lines:
cols=line.split(" ")
price=(float)(cols[1])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
f.close()
f=open("output.txt",'w')
f.write("*******************************************\n")
f.write(" TICKET REPORT\n")
f.write("*******************************************\n\n")
f.write("There are " + str(len(lines)) + " tickets in the database.\n\n")
f.write("Maximum Ticket price is $" + str(priceMax) + "\n")
f.write("Minimum Ticket price is $" + str(priceMin) + "\n")
f.write("Average Ticket price is $" + str(total / len(lines)) + "\n\n")
f.write("Thank you for using our ticket system!\n\n")
f.write("*******************************************\n")
f.close()
print("File Created sucessfully")
Yeah, indentation is important in Python. You must be consistent.
This "cast" (float) evaluates to, basically, the float() function, and then you call it, so that's not the problem. More canonical is f = float("123.45"). Now, this will throw a ValueError exception if there's an invalid number passed, so, you might want to catch this, so you can find out where the problem is. Along the lines of:
s = "123.baboom"
try:
f = float(s)
except ValueError as e:
print("Oh, no, got an exception:", e)
print("The offending string was: ", s)
What's the error that's shown?
I think the issue is that you have started the list with cols[1] instead of cols[0].
Also the indentation is wrong here.
for line in lines:
cols=line.split(" ")
price=(float)(cols[0])
total=total+price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have one problem with print in Python, I am starting to learn Python, but when I want to print variables in print function, it looks like that after one variable it adds newline to the outcome:
print(game_name + " | " + rating)
I am making a game database with my own ratings on the games but if it prints the game and the rating there is like one empty line belpw the game_name and rating is written, how can I delete that empty newline? I am very new to this, so please don't be mean...
Welcome to Stack Overflow! The most likely culprit is that there is a newline at the end of the game_name variable. The easy fix for this is to strip it off like this:
print(game_name.strip() + " | " + rating)
Say we had two variables like this.
game_name = 'hello\n'
rating = 'there'
game_name has the newline. To get rid of that use strip().
print(game_name.strip() + " | " + rating)
output
hello | there
If you want to remove the line break after printing, you can define the optional end parameter to the print statement.
print('Hello World', end='') # No new line
If your variable has a new line added to it, and you want to remove it, use the .strip() method on the variable.
print('Hello World\n'.strip()) # No empty line
For your code, you could run it:
print(game_name + " | " + rating, end='')
Or
print(game_name + " | " + rating.strip())
If the error is that a new line is printed after game_name, you'll want to call the strip method on that instead.
print(game_name.strip() + " | " + rating)
rating or game_name most likely have a new line after the specified string.
You can fix it by doing this:
game_name = game_name.strip('\n')
rating = rating.strip('\n')
print(game_name + " | " + rating)
This question already has answers here:
TypeError: can only concatenate str (not "float") to str
(3 answers)
Closed 2 years ago.
import time
print("><><><><><><><><><><><><><")
print("> Reaction Time Tester <")
print("><><><><><><><><><><><><><")
name = input ("Please enter your first name: ")
time.sleep(1)
start=time.time()
text = input("Press enter on keyboard")
end = time.time()
duration = round(end-start,2)
print("Reaction Time: " + str(duration)+ "seconds.")
#Saving the results to a csv file
csv = (name + "," + duration + "/n")
win = open ("ClickTestResults.csv","a")
win.write(csv)
win.close()
time.sleep(60)
This is the error it shows when I run it:
Traceback (most recent call last):
File "C:\Users\theun\Desktop\click test.py", line 20, in
csv = (name + "," + duration + "/n")
TypeError: can only concatenate str (not "float") to str
csv = (name + "," + str(duration) + "/n")
or better
csv = f'{name},{duration}\n'
Edit: context added per comment advise from Carlo Zanocco
In the first example I kept the original format of the code, but the duration value is not a string and can not be concatenated with the other strings, so it is wrapped in the str function.
The second example is considered "better" because the formatting is easier to read and the duration is automatically converted to a string in the process.
This question already has answers here:
Turn a variable from string to integer in python [duplicate]
(3 answers)
Closed 4 years ago.
I wrote this program up a few hours ago:
while True:
print 'What would you like me to double?'
line = raw_input('> ')
if line == 'done':
break
else:
float(line) #doesn't seem to work. Why?
result = line*2
print type(line) #prints as string?
print type(result) #prints as string?
print " Entered value times two is ", result
print 'Done! Enter to close'
As far as I can tell, it should be working fine.The issue is that when I input a value, for example 6, I receive 66 instead of 12. It seems like this portion of code:
float(line)
is not working and is treating line as a string instead of a floating point number. I've only been doing python for a day, so its probably a rookie mistake. Thanks for your help!
float() returns a float, not converts it. Try:
line = float(line)
float(line) does not convert in-place. It returns the float value. You need to assign it back to a float variable.
float_line = float(line)
UPDATE: Actually a better way is to first check if the input is a digit or not. In case it is not a digit float(line) would crash. So this is better -
float_line = None
if line.isdigit():
float_line = float(line)
else:
print 'ERROR: Input needs to be a DIGIT or FLOAT.'
Note that you can also do this by catching ValueError exception by first forcefully converting line and in except handle it.
try:
float_line = float(line)
except ValueError:
float_line = None
Any of the above 2 methods would lead to a more robust program.
float(line) doesn't change line at all, so it is still a string. You'll want to use line = float(line) instead.