Uploaded by dtessias

print function notes

advertisement
Welcome to this set of notes regarding the formating of print() function.
In [1]: #This one is simple enough and it is the old way we used to print variables in text before python 3.6
course="Python for everybody"
print("The course you are in is {}".format(course))
The course you are in is Python for everybody
In [9]: #Now an easier alternative is
course="Python for everybody"
print("The course you are in is ",course)
The course you are in is
Python for everybody
In [5]: #The format method can be used to print variables in more than one place inside the text
course="Python for everybody"
name="Dimitris"
print("Hallo {} the course you are in is {}".format(name,course))
Hallo Dimitris the course you are in is Python for everybody
In [6]: #Or we can skip the name variable and insert the name in the format
course="Python for everybody"
print("Hallo {} the course you are in is {}".format("Dimitrios",course))
Hallo Dimitrios the course you are in is Python for everybody
In [8]: #From python 3.6 and above we can use this method
course="Python for everybody"
name="Dimitris"
print("Hallo",name,"the course you are in is",course)
Hallo Dimitris the course you are in is Python for everybody
So the methods are similar in operation,the .format() method is better when i have a very large combination of text and variables to print
But lets take it a step further and introduce the f-string and lets see how easy it is to print multiple thing in any order without all these commas and quotation marks
In [9]: course="Python for everybody"
name="Dimitris"
fees=200
enrollment=100
f"Hallo {name} welcome to {course} the total cost for attending is {fees+enrollment}"
Out[9]:
'Hallo Dimitris welcome to Python for everybody the total cost for attending is 300'
In [10]: #Or this way
course="Python for everybody"
name="Dimitris"
f"Hallo {name} welcome to {course} the total cost for attending is {200+100}"
Out[10]:
'Hallo Dimitris welcome to Python for everybody the total cost for attending is 300'
In [11]: #We can even use operations inside the {}
course="Python for everybody"
name="Dimitris"
f"Hallo {name.upper()} welcome to {course.lower()} the total cost for attending is {200+100}"
Out[11]:
'Hallo DIMITRIS welcome to python for everybody the total cost for attending is 300'
In [13]: # EXAMPLE
user_name=input("Hallo what is your name? ")
print(f"Hallo {user_name.capitalize()},welcome to the class Python for everybody")
Hallo Dimitris,welcome to the class Python for everybody
The idea of looking more into the print function started when we came across the following piece of code for the creation of the multiplication matrix
In [1]: X = 1
Y = 1
print ('{:>4}'.format(' '), end= ' ')
for X in range(1, 11):
print('{:>4}'.format(X), end=' ')
print()
for X in range(1,11):
print('{:>4}'.format(X), end=' ')
while Y <= 10:
print('{:>4}'.format(X * Y), end=' ')
Y+=1
print()
Y=1
1
2
3
4
5
6
7
8
9
10
1
1
2
3
4
5
6
7
8
9
10
2
2
4
6
8
10
12
14
16
18
20
3
3
6
9
12
15
18
21
24
27
30
4
4
8
12
16
20
24
28
32
36
40
5
5
10
15
20
25
30
35
40
45
50
6
6
12
18
24
30
36
42
48
54
60
7
7
14
21
28
35
42
49
56
63
70
8
8
16
24
32
40
48
56
64
72
80
9
9
18
27
36
45
54
63
72
81
90
10
10
20
30
40
50
60
70
80
90
100
Now lets start by understading the (end=' ') argument.The end parameter specifies the string(multiple characters) or character to which the printed value ends. By default, it is a line break.As you may know, calling multiple print() functions adds a new line automatically. This is because, by default, each print() function call adds a
newline character ‘\n’ to the end of the row.Lets test this out.
In [2]: print("Hello")
print("world")
Hello
world
In [3]: print("Hello \n")
print("world \n")
Hello
world
In [4]: print("\n Hello \n")
print("\n world \n")
Hello
world
So we understand that changing line for the next resaults to appear is the default method that the print function uses.The end argument lets us interfere and change the tha defaul method.
In [6]: print("Hello", end=" ")
print("world")
Hello world
In [8]: #but we can always check the default method
print("Hello", end="\n")
print("world")
Hello
world
So imagine that if the core code programer had not included the default method if we wanted the print to function the way it does now we would have to include the end="\n" each time we called the function except from the last since in case we wouldnt print anything else from tha point forward. Remember the default mode is to
change the line in the end of what we print so the next thing will appear on the next line.
This is a useful link with some basic things about print() https://www.codingem.com/python-print-function-parameters/#Further_Reading
'{:>4}'.format(' ') This is the one we will try to understand now!lets start with some basics to set the logic. Lets create a string with 4 spaces
In [10]: mystring="
" #this thing is actually a string with 4 elements inside that are all blank
This kind of format works the following way
In [11]: #To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
#Use ">" to right-align the value, we could use "<" to left-align the item:
txt = "We have {:>8} chickens."
print(txt.format(49))
We have
49 chickens.
In [14]: txt = "We have {} chickens."
print(txt.format(49))
We have 49 chickens.
Many thoughts may passing your mind, like what if i just put spaces inside {}. Won't work the brackets have a default behaviour. What if I put the spaces in the format brackets.
In [22]: txt = "We have {} chickens."
print(txt.format("
49"))
We have
49 chickens.
Thats maybe clever but what happens if we use the print in a loop and we want it to change
In [23]: txt = "We have {} chickens."
nmb = input("How many chickens we have?")
print(txt.format(f"
{nmb}"))
We have
49 chickens.
So we fount it we actully found the alternative to skip the need of knowing the formating features of strings.So lets show the examples again to memorize the resaults.
In [24]: txt = "We have {:>8} chickens."
nmb = input("How many chickens we have?")
print(txt.format(nmb))
We have
50 chickens.
In [27]: #with the f-string method
txt = "We have {} chickens."
nmb = input("How many chickens we have?")
print(txt.format(f"
{nmb}"))
#We used 6 spaces since we know the variable will take the 2 more at the end , a total of 8
We have
50 chickens.
In [28]: #what if we want to left-align
txt = "We have {:<8} chickens."
nmb = input("How many chickens we have?")
print(txt.format(nmb))
We have 50
chickens.
In [29]: #with the f-string method
txt = "We have {} chickens."
nmb = input("How many chickens we have?")
print(txt.format(f"{nmb}
"))
#We used 6 spaces since we know the variable will take the 2 more at the start , a total of 8
We have 50
chickens.
Conclution: The formating method is the only one reliable enought because even if we use the f-string as a clever trick we are limited to the specific number of spacies we enter. If the variable becomes a 3 digit number the alligment we try to create in examples like the multiplication matrix gets destoyed.
Here is a site with more details into formating a string https://www.w3schools.com/python/ref_string_format.asp
In [ ]:
Download