Don't understand why print(char + int) causes an error [duplicate] - python

This question already has answers here:
Why does Python not perform type conversion when concatenating strings?
(8 answers)
Closed 7 months ago.
fname3 = input("Enter the Blue print name: ")
import re
with open (fname3) as file:
fileText=file.read()
q1,q2,q3 = [ int(n) for n in re.findall(": (\d+)",fileText) ]
p1,p2,p3 = re.findall("(.*):",fileText)
qb=q1+q2
qc=q1+q2+q3
print("This BLUEPRINT CONTAINS--------------|")
print(p1+" Questions: "+q1)
This code above is giving an error of line: print(p1+" Questions: "+q1)
but print(p1+" Questions: "+p1) is giving correct output abd also print("q1")
but combining them is outputting an error
but gives error print("questions: "+q1)
This code opens a txt file which contains the following:
Part A: 12 10*2 = 20
Part B: 6 4*5 = 20
Part C: 5 3*10 = 30

Another way to do this is with something called f-strings (available in Python 3.6+, but the latest version is 3.7):
print (f"{p1} Questions: {q1}")
Notice how there is an f before the quotes (applies to all types of quotes), and any variable you want has to be in {}

You need to convert to a string with str:
print(p1 + " Questions: " + str(q1))
Alternatively, simply use multiple arguments when calling print:
print(p1, "Questions:", q1)
Note that the spaces are added automatically with this method.

The problem is in the types of your variables.
Questions:, p1, p2 and p3 are all of type str.
Conversely, q1, q2 and q3 are of type int.
The print calls work separately because print can convert its arguments to str. However, you are first trying to add two strings (p1 and Questions:) to an int (q2), which is what fails.
Rather than naive addition/concatenation, you should prefer str.format calls:
print('{p} Questions: {q}'.format(p=p1, q=q1))
These make it easier to understand what the string will look like and automatically perform conversion of your arguments.

Python is strongly typed language. In most cases, it does not do any implicit type conversion. Consider, should "5"+7 be 12 or "57"? How about 7+"5"?
On ambiguous cases like this, Python will simply raise error rather than trying to guess what you meant.
You need to do the type conversion explicitly:
print(p1+" Questions: "+str(q1))
or with Python 3 f-string:
print(f"{p1} Questions: {q1}")
or print function accepts multiple arguments, that will, by default, be separated by space:
print(p1, "Questions:", q1)

Related

I'm struggling to concatenate a string to a function

This is my code. Solution #1:
def age():
input('Age: ')
def friends():
print("John" + age)
Expected outcome:
John13
Actual outcome #1:
TypeError: can only concatenate str (not "function") to str
Solution #2:
def age():
input('Age: ')
def friend():
print("John" + age())
Solution outcome #2:
TypeError: can only concatenate str (not "NoneType") to str
How can I concatenate my function age (age is an input() function declaration) to a string or strings? The age function is an input() and I want to add it to the appropriate name or string.
You need to add a return statement to your function age, for example:
def age():
agein = input(...)
return agein
age() doesn't do anything with the input, it just throws it away immediately. You need to actually return the value.
Also, there's little point in creating a method that does nothing but call another method. Why not just call input(...) "directly"?
Also, your first solution does not concatenate the string returned by age - without the (), you try to append the age() method itself to the string, which doesn't make sense.
As you know, the variable age as you've defined it is a function, not a string.
So your question boils down to:
How can we extract the actual data we want -- in this case, a string representing an age -- from
our function?
In other words,
How can we make our function "return" the data we want?
Simple! There is a construct in Python (and just about every other programming language) that does exactly this!
It is called a return statement. It "returns" a value -- any value you want -- from a function, which simply means that your code outside the function may use that value.
For example:
def age():
age = input('Age: ')
return age // We can now use this value outside the function!
You can use it like so:
def friends():
johns_age = age() // calling the age function and assigning its returned value
print("John is " + johns_age)
If you found this answer helpful, I suggest you read a beginner-friendly Python book (such as the free Automate the Boring Stuff with Python), as you'll learn much faster that way than asking questions on this rather strict and unfriendly site.

Can i use PRINT function instead of RETURN at the end of every function i create? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 3 years ago.
i just can not understand the importance of return at the end of functions.with return u have to type print(function()) anyways so why cant we just type print(value) at the and of the function and when we need to use that function just call it like function()?
def example():
value = 5+5
print(value)
example()
print and return are not doing the same thing. The former is displaying information to the user, while the latter is giving a raw value out of a function. Consider the following:
>>> def print_10():
... print(10)
...
>>> def return_10():
... return 10
...
>>> print(return_10() + return_10())
20
>>> print(print_10() + print_10())
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
return_10 gives back the number 10, while print_10 prints the value 10 to the console and returns None (since you don't specify a return value). Trying to use that value elsewhere is possible (None is a valid result), but it probably doesn't do what you want it to do.
Thinking of this in explicit typing makes this very clear:
def print_10() -> None:
print(10)
def return_10() -> int:
return 10
the print statement only prints what is inside the Parenthesis to the console to be seen and can't be stored in variables or do any operations on it as it is a NoneType
i will show you with an example:
def example():
a = 5
b = 6
print(a + b)
x = example() + 5
print(x)
the above code will return a TypeError.
but if you change it to this:
def example():
a = 5
b = 6
return(a + b)
x = example() + 5
print(x)
you get 16
if you want to display info and not use it again use print else use return
There's a principle called separation of concerns that proposes that each unit of code (function, class, module, etc.) should be responsible for doing just one thing (where the definition of "one thing" is flexible to account for the size of the unit of code being discussed). The benefit is that code that follows this principle is easier to test, debug, combine, and reuse.
If you write a function that prints its result, it is harder to reuse that code in situations where you don't want to print the result, but rather use it in some other way. The function is doing two things: calculating its result, and printing it. If you don't want it to do the second thing, or want it to do the second thing in a slightly different way, you are S.O.L. On the other hand, if the function just calculates its result, doing just one thing, the caller can easily print it if that's what they want.
That said, if you often find yourself printing a result, then it might make sense to provide a second function that calls the first and prints the result, especially if printing it is complicated. But having the first function available is a win for future code reuse.
Some development methodologies advise you to write the simplest thing that works. But I think preserving separation of concerns is an obvious and logical reason to ignore this advice in many cases.

Python specifying function as input [duplicate]

This question already has answers here:
how to define a function from a string using python
(4 answers)
Closed 4 years ago.
import math
def g(x):
return x**2+3
def Integrate(f, a , b, n):
h=(b-a)/n
result=0
for k in range(n):
x=k*h+h/2
result+=f(x)*h
return result
F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))
Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?
error:
line 14, in Integrate
result+=f(x)*h
TypeError: 'str' object is not callable
You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:
F = eval(input("f:"))
On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:
lambda x: 2 * x + 1
as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.
I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:
function_to_call = getattr(math, f)
result += function_to_call(x) * h
When doing this you should surround with try except block to check if given function name exit in math module.

python s=input().count What does input().count function do in python?

I saw this code on the internet:
s=input().count
print( max( (s('6')+s('9')+1)//2, max([s(i) for i in "01234578"])))
but I don't get what this line does :
s=input().count
I thought this function was to count how many letters are in the word. So I tried to print the s, but I got this error:
<built-in method count of str object at 0x7f4f8b859148>
what does input().count function do and what situation will it be used?
s=input().count is a function which you can call.
You could write
input().count('6')
to count how many times you get 6 in the input.
Or,
s('6')
is now a shorthand for this.
s = input().count
Basically you are binding the count method to s so when you call s like s(i), it converts the code to input().count(i) internally.
Let me give you a simple example:
p = print
p("hello world")
# hello world

Why doesn't join() turn my list into a string? [duplicate]

This question already has an answer here:
Why is the join built-in having no influence on my code?
(1 answer)
Closed 8 years ago.
Hey I was just wondering why in this piece of code:
def change_letter(line, what_letter_to_replace, what_to_replace_with):
"""
This function takes 3 parameters: a string, the letter that is going to be
replaced,
and what it is going to be replaced with.
"""
lst_line = list(line)
for letter in lst_line:
if letter == str(what_letter_to_replace):
lst_line[lst_line.index(letter)] = str(what_to_replace_with)
x = ''.join(lst_line)
y= x.split()
return y
The function works as intended and returns a list of the words that are in the new updated line whereas in this piece of code:
def change_letter(line, what_letter_to_replace, what_to_replace_with):
"""
This function takes 3 parameters: a string, the letter that is going to be
replaced,
and what it is going to be replaced with.
"""
lst_line = list(line)
for letter in lst_line:
if letter == str(what_letter_to_replace):
lst_line[lst_line.index(letter)] = str(what_to_replace_with)
''.join(lst_line)
lst_line.split()
return lst_line
The function has a run-time AttributeError that says that 'list' object has no attribute 'split', but wouldn't the code have already made the lst_line into a string already due to the previous line?
''.join(lst_line) does not affect lst_line. It returns a new string. If you want that new string to be called lst_line, you need to assign it back to that variable:
lst_line = ''.join(lst_line)
Notice that this is what the first example does (it just calls it x instead of lst_line).

Categories

Resources