?print-pdf
' Created for
escape character | result |
---|---|
\' | Single Quote |
\" | Double Quote |
\n | New Line |
\t | Tab |
\\ | Backslash |
print('line1\nline2')
#line1
#line2
print('abc\t123')
#abc 123
print('John\'s pub')
#John's pub
# above, we can do without escape, but changing quotes
print("John's pub")
#John's pub
print()
function is used for outputting data to the console.
print(*objects, sep=' ', end='\n',file=sys.stdout, flush=False)
### basic usage
print("Hello")
print("World")
#Hello
#World
### Print multiple values. Note that default separator is space
print(1,2,3)
# 1 2 3
# Change separator to '-'
print(1,2,3,sep="-")
# 1-2-3
# Change default EOL symbol ("\n") to none. So, there will be no new line after print
print("Hello",end="")
print("World",end="")
print("!")
# HelloWorld!
input()
function is used to get user input as string.
variable = input("prompt message, to be displayed to the user: ")
name = input("Enter your name: ")
print("Hello,", name)
value = input("Enter a number: ")
print("The type of the entered value is:", type(value)) # Always <class 'str'>
int()
or float()
value = input("Enter a number: ")
# Convert to integer
integer_value = int(value)
print("Integer value:", integer_value)
print("Type of integer_value:", type(integer_value))
# Convert to float
float_value = float(value)
print("Float value:", float_value)
print("Type of float_value:", type(float_value))
user_name = 'Ada'
user_surname = 'Byron'
print('Hello ' + user_name + ' ' + user_surname + '!')
# Hello Ada Byron!
f-strings
, the code is more readable and easy to write (like using "template strings" in JavaScript):
user_name = 'Ada'
user_surname = 'Byron'
print(f'Hello {user_name} {user_surname}!')
# Hello Ada Byron!
f-strings
?
f"some text {expression} more text"
{}
(curly braces) to embed any Python expression.
# single line f-string:
x = 1
y = 2
print(f'x + y = {x+y}')
#x + y = 3
# multiline f-strings
print(f"""
x=1
y=2
x+y = {x+y}
""")
#x=1
#y=2
#x+y = 3
f-strings
f-strings
in Python allow for various format specifiers to control how the values are displayed.
# ------------------- Precision for Floating Point Numbers ------------------- #
PI = 3.14159265
# rounded to 2 decimal places:
print(f"{PI:.2f}")
# 3.14
# ---------------------- Comma as a thousands separator ---------------------- #
budget = 1234567890
print(f'budget={budget:,}')
# budget=1,234,567,890
# ---------------------- Format a number as a percentage --------------------- #
accuracy = 0.95678
print(f"Accuracy: {accuracy:.2%}")
# Accuracy: 95.68%
f-strings
- more examples
<!-- --------------------------- Width and Align --------------------------- -->
x = 123
# Right-align x within a 10-character wide field:
print(f"--->{x:>10}<---")
# ---> 123<---
# Center-align x within a 10-character wide field:
print(f"--->{x:^10}<---")
# ---> 123 <---
# Center-align x within a 10-character wide field, padding with '*':
print(f'--->{x:*^10}<---')
# --->***123****<---
# Pad an integer with zeros.
day = 5
print(f"Day of the month: {day:02d}")
# Day of the month: 05
# ---------------------------- Dynamic Formatting ---------------------------- #
value = 12.34567
precision = 3
# Use variables to determine the format.
print(f"Value: {value:.{precision}f}")
# Value: 12.346
|==========|==========|
| 1|1 |
| 23|23 |
| 456|456 |
|==========|==========|
print(f"|{'='*10}|{'='*10}|")
print(f"|{1:>10}|{1:<10}|")
print(f"|{23:>10}|{23:<10}|")
print(f"|{456:>10}|{456:<10}|")
print(f"|{'='*10}|{'='*10}|")
str.format()
and Old-Style Percent Syntax
"format_string" % (values_tuple)
>>> "%s died in %d year" % ("Ada Byron", 1852)
'Ada Byron died in 1852 year'
print("| %10s | %10s |" % ("=" * 10, "=" * 10))
print("| %10d | %10d |" % (1,2) )
print("| %10d | %10d |" % (34,12) )
print("| %10d | %10d |" % (243,126) )
print("| %10s | %10s |" % ("=" * 10, "=" * 10))
| ========== | ========== |
| 1 | 2 |
| 34 | 12 |
| 243 | 126 |
| ========== | ========== |
x = 1.2345678
y = 123
print("x = %d, y = %d" % (x,y))
print("x = %02d, y = %02d" % (x,y))
print("x = %f, y = %f" % (x, y))
print("x = %.2f, y = %.2f" % (x, y))
str.format()
method
"string_with_placeholders".format(values_to_be_substituted)
>>> "{} died in {} year".format("Ada Byron", 1852)
'Ada Byron died in 1852 year'
{}
>>> "{1} died in {0} year".format("Ada Byron", 1852)
'1852 died in Ada Byron year'
{}
and with :
used instead of %
. For example, '%10d
' can be translated to '{:10d}
' and so on.
print("| {:10s} | {:10s} |".format("=" * 10, "=" * 10))
print("| {:10d} | {:10d} |".format(1, 2))
print("| {:10d} | {:10d} |".format(34, 12))
print("| {:10d} | {:10d} |".format(243, 126))
print("| {:10s} | {:10s} |".format("=" * 10, "=" * 10))
These slides are based on
customised version of
framework