1. Print Function

The print() function in Python is used to output data to the console. It accepts zero or more expressions as arguments and prints their values as text.

Basic Usage

  print("Hello, World!")
  

Output:

  Hello, World!
  

Printing Variables

You can print the values of variables by passing them as arguments to print():

  name = "Alice"
age = 30
print("Name:", name, "Age:", age)
  

Output:

  Name: Alice Age: 30
  

Printing Multiple Items

You can print multiple items by separating them with commas in the print() function:

  print("Python", "Programming", "is", "fun!")
  

Output:

  Python Programming is fun!
  

Printing with Formatting

Use formatted strings (f-strings) for more complex output:

  x = 10
y = 5
print(f"The sum of {x} and {y} is {x + y}.")
  

Output:

  The sum of 10 and 5 is 15.
  
  1. Escape Characters

Escape characters in Python are special characters preceded by a backslash (’'’). They are used to represent characters that are difficult or impossible to type directly into the code or to perform certain actions within strings.

Common Escape Characters

\n: Newline - Inserts a newline character. \t: Tab - Inserts a tab character. \': Single Quote - Inserts a single quote character. \": Double Quote - Inserts a double quote character. \\: Backslash - Inserts a backslash character.

Examples

Example \n

  print("Hello\nWorld!")
  

Output:

  Hello
World!
  

Example \t

  print("Python\tProgramming")
  

Output:

  Python  Programming
  

Example \"

  print("He said, \"Python is awesome!\"")
  

Output:

  He said, "Python is awesome!"
  

Raw Strings

Use raw strings (prefixing with r) to ignore escape characters:

  print(r"Path: C:\Users\Username\Documents")
  

Output:

  Path: C:\Users\Username\Documents
  

Escape characters are crucial for formatting text output and handling special characters within strings in Python. Mastering their usage enhances the readability and functionality of your code.