Amazing Python 3
68 subscribers
Learning Python 3 from scratch
Download Telegram
Channel created
How to print "Hello World" in Python.

print('Hello, World!')

This program prints the welcome phrase. The print function is a built-in func- tion that outputs things to the console. In this case, we want to output a text string.

Save the code in the file named helloworld.py. To run the program, type the following in your terminal (the dollar sign is a part of shell’s prompt, so you don’t type it):

$ python3 helloworld.py

If there are no typos in the code, you will see the desired output:

Hello, World!
Let's compare formatted output in Python. Here's a test program:

name = 'John'
print('Hello, ' + name + '!')


# Using string formatting


# Old style
print('Hello, %s!' % name)

# New style
print('Hello, {}!'.format(name))


Simple string formatting using the old style with the % formatters and the new style with the call of format method.

$ python3 formatted-output.py Hello, John!
Hello, John!
Hello, John!
String formatting and interpolation

What if you need to print two names?

name1, name2 = 'John', 'Karla'

# Old style
print('Hello, %s and %s!' % (name1, name2))

# New style
print('Hello, {} and {}!'.format(name1, name2))

Simple string formatting using the old style with the % formatters and the new style with the call of format method. Notice how easily you can use more than one variable.

$ python3 format2.py
Hello, John and Karla!
Hello, John and Karla!
What are F-strings

The so-called f-strings are available in Python 3.6+. You can use them to inter- polate variables in strings.

name = 'John' print(f'Hello, {name}!')

Prefix a string with f and use curly braces to enclose the variable name inside the string.

$ python3 f-strings.py
Hello, John!
More on f-strings

Here is an example of when the new style of string formatting can be very handy.

a, b = 10, 20
print('a + b = b + a')

print('{0} + {1} = {1} + {0}'.format(a, b))
# {0} is replaced with a
# {1} is replaced with b
# but you only mention them once

You can use indices inside {} to indicate which argument of the format method to substitute at this place. In the list of variables, we have two variables only, but they both are used twice in the string.

$ python3 more-formatting.py
a + b = b + a
10 + 20 = 20 + 10
Formatted strings with named arguments

Here is an example of using the format method with named arguments.

first_name = 'James'
last_name = 'Bond'
greeting = 'My name is {last}. {first} {last}.'.format(
first = first_name,
last = last_name
)
print(greeting)


You can pass named arguments when calling the format method on a string. Give the temporary names to your placeholders and use them directly in curly braces.

$ python3 named-formatted.py
My name is Bond. James Bond.
A simple "echo" program

This program prints everything that it receives as input.

while True:
s = input()

print(s)

Run the program and type something. You should see that the program copies your input and prints it.

$ python3 echo.py

To stop the program, press Ctrl+C.
Another "echo"

This program is a modification of the previous one, but it does not print any error messages when you terminate it by pressing Ctrl+C.

while True:
try:
s = input()
print(s)
except:
break
# Now the program simply stops after
# the end of input

The try block catches the exception that happens after pressing Ctrl+C and breaks the loop.

$ python3 echo-try.py
Using pprint to make the output of data structures more readable.

The pprint module gives you a ‘Pretty Printer,’ which is a handy tool if you
want to print a big data structure and have it readable in the output.

import pprint
data = {'France': 'Paris', 'Germany': 'Berlin', 'Italy': 'Rome'}

# Make the printer
p = pprint.PrettyPrinter(width=1)

p.pprint(data)

In this program, the printer is configured to have the maximum output width of 1, which forces a given dictionary to be printed line by line.

$ python3 pprint.py
{'France': 'Paris', 'Germany': 'Berlin', 'Italy': 'Rome'}
Difference between Python 2 and Python 3 in printing

You have a variable keeping some text message:

message = 'Hello, World!'

In Python 2, you can print it like this:

print message

This code works in Python 2 but does not work in Python 3, where you need to have parentheses:

print(message)

One of the most noticeable difference between the two versions of Python, Py- thon 2 and Python 3, is the requirement to use parentheses to call print. In Python 2, you can say: print message, while in Python 3, print is a proper function and you need to call it as you do with other functions: print(message).

$ python3 print-2vs3.py
Hello, World!
Setting precision when printing numbers using f-strings

If you print a floating-point number using f-strings, you can easily apply a for- matting requirement, for example, to print two digits after the decimal point.

import math

print(math.pi) # Default

print(f'{math.pi}') # Again, default
print(f'{math.pi:.2f}') # Two digits after the "."
print(f'{math.pi:.3f}')
print(f'{math.pi:.4f}')

In the given example, the value of π is printed a few times, first, without any additional truncation (well, it is still truncated to some default length), and then with two, three, and four digits after the decimal point.

$ python3 format-prec.py
3.141592653589793
3.141592653589793
3.14
3.142

3.1416

Also notice that the printed value is correctly rounded (i. e., 3.1416 is printed, not 3.1415).