Codementor Events

small stuff about python3 print()

Published Feb 12, 2019

Hi there. I'm starting a series on random programming topics ranging from high-level constructs to ultra-pedantic details and everything in between because I am a freaking nerd and I love it.

Goal: to teach myself better python3 and to help others and make some money

1. print()

First of all, your basic print() function is used like the following:

print('hello world!')
print("hello world!")

Some people might argue with me over what should be taught or learned first. I say you need print() before everything else.

Sure, the interpreter allows you to basically 'get' the value of whatever you want to print out by just typing it on the command line, but what fun is that?

I come from an age or era when we did not have the luxury of an interpreter. Our programs had to be compiled before you could just get the value of an arbitrary variable or reference.

There are a lot of ways to use print(), but since you're cool and want to do things my way, I like to look at print() like how Java's IO works:

System.out.print();
System.out.println();

The two main print functions in Java are System.out.print() and System.out.println(). Notice the main difference is the print and println. One prints no newline at the end of whatever it prints, and the other does.

So, in Python3, to do that with print():

print('This will print a newline')
print('This will not print a newline', end='')

The second print() has a second, optional parameter at the end: end=''.


1.1 printf-style format codes

If you've ever written any C, you've used printf().

printf() is cool because it has a bunch of format codes for outputting.

They work similarly in Python3.

someNum = 15
print('This is a number: %d' % someNum)

aStr = 'hello world'
print('This is a string: %s' % aStr)

print('These are multiple values: %d %s' % (someNum, aStr))

import math
print('This is a double: %5.3f' % math.pi)

The key here is to remember that when passing multiple values in, you must pass them in a tuple.


1.2 new-style formatting

I learned the above first, but this isn't new apparently.

https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting

someNum = 15
print(f'This is a number: {someNum}')

aStr = 'hello world'
print(f'This is a string: {aStr}')

This seems to be the prefered way of doing things, so I will be making effort to integrate this style into my own programming.


That is all for now. If you have been liking my content, please do whatever equivalent of liking and subscribing exists on this platform, and check out my other locations online. Thank you and take it easy!
e...

Discover and read more posts from Mike Bell
get started
post commentsBe the first to share your opinion
Show more replies