So I have to write a code while assuming that the grader defines the following variables
a to be some int
b to be some float
s to be some string
and then I have to write a program that prints out exactly the following, where the values in < .... > are replaced by the actual value inside the variables. However, you can only use ONE print statement.
// The variable 'a' has value of <a>. //
\\ While the variable 'b' has value of <b>. \\
// Lastly, the variable 's' has value of "<s>". //
Example, if a=1, b=1.5 and s='hi', then the expected output is:
// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.5. \\
// Lastly, the variable 's' has value of "hi". //
Here is what I have so far, which clearly doesn't work...
a = int
b = folat
s = str
print(f"// The variable 'a' has value of <{a}> . //\n \\ While the variable 'b' has value of <{b}> . \\ \\n// Lastly, the variable 's' has value of <{s}>. //")
What changes should I make??
CodePudding user response:
You can just convert the int and float to a string and concatenate them all in the print
statement. You also need to double the \
character, because it is the escape character, and acts as a single character with the proceeding character:
a = 1
b = 1.0
s = "a"
print("// The variable 'a' has value of " str(a) ". //\n\\\\ While the variable 'b' has value of " str(b) ". \\\\ \n// Lastly, the variable 's' has value of " s ". //")
Output:
// The variable 'a' has value of 1. //
\\ While the variable 'b' has value of 1.0. \\
// Lastly, the variable 's' has value of a. //
CodePudding user response:
Consider using the multiline priniting feature in python. Also you need to escape the \
because it itself is an escape character for example \n
is newline instead of literally printing \n
. And by doing \\
it means just \
a = 1
b = 1.5
s = "hi"
print(
f"""// The variable 'a' has value of {a}. //
\\\\ While the variable 'b' has value of {b}. \\\\
// Lastly, the variable 's' has value of "{s}". //"""
)
Personally i think this is the easiest to read and clean because it looks more like the desired output.