Day 2 — Printing and Input in Python: A Comprehensive Guide 😃

Akshay Gawande
Data Shastra
Published in
6 min readAug 21, 2023
Photo by Joshua Fuller on Unsplash

Introduction 🚀

Greetings, fellow Python enthusiasts! 🐍 Ever wondered how your Python programs communicate with you through the console? This guide is your ticket to understanding how Python displays output and receives input. Whether you’re a rookie coder or a seasoned pro, these skills are your passport to more interactive and user-friendly programming experiences. Let’s dive in! 🤓

Table of Contents 📚

  1. Hello World: Your First Steps
  2. Customizing Print Output
    - Separator
    - Mark End
    - Write to File
    - File Flush
  3. Formatted Printing
  4. Taking User Input
  5. Conclusion

Hello World: Your First Steps 👶

Let’s kick things off with a classic “Hello, World!” 🌎 moment. In Python, the print() function is your buddy for putting stuff on the console. Simply put your text within quotes and watch the magic happen. ✨

Use the print() function/method to print the output on the Python console. You can use single quotes ('__'), double quotes ("__"), or triple quotes ('''__''') to encapsulate your statements.

Syntax:

print('Some Statements here in a single quote.')
print("Some Statement here in Double quotes.")
print('''Some Statement here in Tripple quotes.''')

Example:

Customizing Print Output 🎨

There are multiple optional keyword arguments provided by Python to process the statement and print the customized output. We will look into keyword arguments later. But some of these keywords that are frequently used can be listed as follows:

1. Separator:

The separator separates the two different strings with a given separator. It can be a string that you would like to insert between two string values or any special characters you need to add, by default space is used as a separator (print('some values', sep='separator')).

The print() function usually separates values with spaces, but what if you want to jazz it up? Enter the sep parameter! 💃

let’s see an example with a default separator and a user-defined separator.

Syntax:

print(‘val1’,’val2’,’val3’, . . . . . ,’valn’, sep=’pattern’)

Example:

2. Mark End

By default, the print statement ends with a new line i.e.(\n). The end keyword allows the user to end a statement with his choice of characters or string. You can end the print statement with any special character or string of your choice with the use of the end parameter by assigning some values.

By default, print() drops a new line at the end. But hey, you're the boss! Use the end parameter to say where the buck stops. 🛑

Syntax:

print(‘statement1’,‘statement1’, . . . . . ,‘statement N’, end=’pattern’)

Example:

3. Write to File 📝

print() function in Python3 also supports a ‘file‘ argument, which specifies the file to which the function should write a given object(s)/outputs. If not specified explicitly, it is by default.

With the file keyword, you can mention the file in which you would like to write/append the output of the print function.

Your program’s got something to say, and you want it in writing? Meet the file parameter! 🖊️

Syntax:

#write a code to open a file in write/append mode.
#edit modes : w= write mode, a = append mode
file_name = open (filePathUrl, edit_mode)
#print statement to write data to file.
print(data, file=’file_name’)

Example:

Before Run:

After Run: You can see the file starks.txt is created with data.

4. File Flush:

The flush() method in Python file handling clears the internal buffer of the file. In Python, by default, the flush() is set to False, we can set it to True as it is a Boolean expression. If the flush() is set to True, the stream is forcibly flushed.

What does forcibly flushed mean and why do we need Flush?
There are a couple of things to understand here. One is the difference between buffered I/O and unbuffered I/O.
The concept is fairly simple:

  • for buffered I/O, there is an internal buffer that is kept, only when that buffer is full, the output is “flushed”.
  • With unbuffered I/O, whenever a call is made to output something, it will do this, 1 character at a time.
  • Most I/O functions fall into the buffered category, mainly for performance reasons: it’s a lot faster to write chunks at a time.
  • flush() lets you manually choose when you want this internal buffer to be written — a call to flush will write any characters in the buffer. Generally, this isn’t needed, because the stream will handle this itself. However, there may be situations when you want to make sure something is output before you continue — this is where you’d use a call to flush().
  • Buffering is great, but sometimes you need results NOW. The flush() method clears the path for immediate satisfaction. 🚀

Syntax:

#write a code to open a file in write/append mode.
#w= write mode, a = append mode
file_name = open (filePathUrl, edit_mode)
#print statement to write data to file.
print(data, file=’file_name’, flush=True)

Formatted Printing:

By using format() the argument, you can pass as many variables as you want to print. When you pass the variables in the format() function you need to specify the index numbers (order in which they are placed inside the format argument) in a predefined string.

The format() method turns you into a style guru! Fancy dynamic content formatting? Say no more! 💃

Syntax:

print (‘predefined string with {indexes}‘.format(val1,val2,….))
print('My name is {name} and I am {age} years old.'.format(name='John', age=30))

Example:

Similar to a format argument where your print function acts as a template you can use it to print the values of variables.
1. %d: is used as a placeholder for numeric or decimal values.
2. %s: is used as a placeholder for the string.
3. %f: Floating point numbers
4. %.<number of digits>f: Floating point numbers with a fixed number of digits to the right of the dot.
5. %x/%X: Integers in hex representation (lowercase/uppercase).
6. Dynamic type casting is supported here, so even if you use %s python will typecast int to str while printing output. However, the opposite is not true. It will fail to convert a string to an integer and it will result in a Type Error.

Taking User Input

Time to let users join the conversation! The input() function gets the crowd talking. 💬

The input() function in Python is like having a chat with your program. When you use input(), your program listens to what you type and waits for you to press Enter.

Imagine you’re telling your program something like this:

User: "Hello, program! My age is 25."
Program: "Nice to meet you, 'Hello, program! My age is 25.'! Wait, you're 25, right?"

And if you try to be sneaky and just type numbers:

User: "100"
Program: "Cool, you said '100'! But wait, is this your shopping list?"vb

Syntax:

#this will prompt you to a dialogue/input box
val1 = input('Some String:')
print(val1)

Example:

Here’s the trick: no matter what you type, Python treats it as words, like it’s reading a book. It doesn’t care if you’re giving it numbers, words, or even secret codes. Everything you say becomes a string, like a bunch of letters tied together.

Conclusion 🎉

Congratulations! 🎈 You’ve unlocked the secrets of Python’s communication skills. From sprucing up your outputs to engaging in lively dialogues with your users, you’re now armed with the essentials. 🛡️ Keep experimenting, coding superheroes! 🦸‍♂️

Python has made it very simple to read and write data/output to its console and there are different built-in functions for it. The input() and print() are widely used for standard input and output operations.

--

--