Python Print
BASIC
print ONE thing
print(oneThing)
1 int, float, string, boolean
print ONE thing
print("Hello")
print(x)
print(sum/total)
print(type(myVar))
Hello
Hello
93.7
True
6.27
<class 'int'>
sum = 78.7
total = 84
print(str(sum) + "/" + str(total) + "=" + str(sum/total))
+ concatenates multiple strings into ONE string
Note: no spaces anywhere in output
print ONE thing (a string)
78.7/84=0.9369047
print MULTIPLE things
print(thing1, thing2, thing3)
1 int, float, string, boolean
sum = 78.7
total = 84
things separated by commans print separated by a space
print MULTIPLE things
print(sum, "/",total, "=", sum/total)
78.7 / 84 = 93.7
By default once a print has printed all the specified thing(s) it will print a newline string. However, a different string can be specified using the end parameter
print("At the end", end = "") # print nothing instead of newline
print("At the end", end = " ") # print space instead of newline
print("Hello", "World", end="")
print("Hello", "LASA")
Hello WorldHello LASA
print "choose the end"
Python f-string
firstName = 'Grace'
lastName = 'Hopper'
fullName = f'{firstName} {lastName} LASA{{CS}}'
print(fullName)
Grace Hopper LASA{CS}
item = 'bananas'
price = 0.27
quantity = 6
print(f'{quantity} {item} cost ${price * quantity}')
6 bananas cost $1.62
for more see
The magic of f-strings is that you can embed Python expressions directly inside them. Any portion of an f-string that’s enclosed in curly braces { } is treated as an expression that is evaluated and converted to a string representation.
sum = 78.7
total = 84
print(f'{sum} / {total} = {sum/total}')
print(f'{sum}/{total}={sum/total}')
78.7 / 84 = 93.7
78.7/84=93.7
f-string example
advanced f-string
will not be on a quiz or test
Python f-strings
print(f'Price per item is ${price/quantity}')
Price per item is $0.28966666667
print(f'{price = }') # Python 3.8 introduced this self-documenting expression with the = character
price = 1.74
quantity = 6
item = 'bananas'
price = 0.27
print(f'{quantity:3d} {item} cost ${price*quantity:.1f}') # rounds too
6 bananas cost $1.6 rounds to 1 digit after decimal pt
print(f'Price per item is ${price*quantity:5.2f}') # rounds too
Price per item is $ 1.62 5 spaces, rounds to 2 digits after decimal pt
Python f-strings
Inside of { } put an
expression or variable optionally followed by
:[fill][alignment][width],.[decimals][type]
f-string examples
program is in speaker notes
f-string examples
program is in speaker notes
For more information