Python Examples: Difference between revisions

From Lucca's Wiki
Jump to navigationJump to search
No edit summary
No edit summary
 
(16 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<hr>
 




Calculate the average of three numbers
Calculate the average of three numbers
  avg = float((num1+num2+num3)/3)
  avg = (num1+num2+num3)/3
 
Display a variable inside an f string and round it to only have 2 decimals, like with money. (the end result looks like this: <code>1000.00</code>)
monthly_payment = 1000.0000
print(f'The monthly payment is {monthly_payment:.2f}.')
 
Display a large number and add commas in-between every 3 digits. (the end result looks like this: <code>1,000,000,000</code>)
large_number = 1000000000
print(f'{large_number:,}')
 
Display a value using a minimum field width. This is useful for spacing in a cli or gui. (the end result looks like this: <code>The number is ________99</code>)
number = 99
print(f"The number is {number:10}")
 
Align the text when a field width is specified. The <code><</code> can be substituted for a <code>></code> or <code>^</code> to align right or center respectively.
number = 40
print(f"{number:<10}")

Latest revision as of 10:58, 29 August 2025


Calculate the average of three numbers

avg = (num1+num2+num3)/3

Display a variable inside an f string and round it to only have 2 decimals, like with money. (the end result looks like this: 1000.00)

monthly_payment = 1000.0000
print(f'The monthly payment is {monthly_payment:.2f}.')

Display a large number and add commas in-between every 3 digits. (the end result looks like this: 1,000,000,000)

large_number = 1000000000
print(f'{large_number:,}')

Display a value using a minimum field width. This is useful for spacing in a cli or gui. (the end result looks like this: The number is ________99)

number = 99
print(f"The number is {number:10}")

Align the text when a field width is specified. The < can be substituted for a > or ^ to align right or center respectively.

number = 40
print(f"{number:<10}")