Python Format Flashcards
Boolean Expression
if 7<0 and 8>1:
print(“true”)
elif False or (0<100):
print(“False”)
False
(why?: becus there is an or statement and (0<100) is true, thus it iterates to the next line
Formatting Syntax?
format(value, format spec)
{[index], width.precision[type]
print(“I {} like games”).format(“darren”))
Result : I darren like games
print(“—”, format(1.23456, 10.2%))
converts 1.23456 to percentage -> 123.456%
rounds to .2 float -> 123.45
pads 4 additional space as it requires a minimum of 10 digits. (decimal included)
result : —, 123.45%
print(‘{2} {1} {0}’.format(‘directions’, ‘the’, ‘Read’))
Result : Read the directions
print(‘The first {p} was alright, but the {q} {p} was tough.’.format(p = ‘second’, q= ‘last’))
Result:
The first second was alright, but the last second was tough.
print(“{0} ate {1:.1%} of the cake ! “.format(“tom”, (2/3)))
tom ate 66.7% of the cake
print(“{0} ate {1:.1%} of the cake ! “.format(“tom”, (2/3)*100))
tom ate 6666.7% of the cake !
Because its already converted to percentage in the bracket, hence multiplying by 100 is redundant.
num = 3.14159 print(f”The valueof pi is: {num:{1}.{5}}”)
The value of pi is 3.1415
basically round off to 5 sig fig
name= “Tom”
money = 6.17
print(f”{name} has {money*money:9.2%}”)
Tom has 3806.89%