Input, Output & Comments

Output Function

  • print() displays output on screen
  • We can print number, text, variables, expressions
  • Examples:
    1. print("Hello") # Hello, World! print(5 + 2) # 7 name = "Rabindra" print(name) # Rabindra age = 30 print("I am", age, "years old") # I am 30 years old

f-strings formatting

  • Used to format strings by embedding expressions inside string literals
  • Note: Must use f at the beginning of the string and use curly braces {} to enclose variables
  • Examples:
    1. name = "Rabindra" age = 30 print(f"My name is {name}. I am {age} years.") # My name is Rabindra. I am 30 years. print(f"Next year, I will be {age + 1} years old.") # Next year, I will be 31 years old.

Format Specifiers

  • Used to customize the output using f-strings
  • Syntax: {variable:format_specifier}. Specifier is in form [fill][align][width][.precision]
SpecifierDescription
FillCharacter used for padding the output (default is space). Has to be single character
AlignAlignment of the output: < for left, > for right, ^ for center. Default: > for numbers and < for strings
WidthMinimum width of the output
PrecisionNumber of digits after decimal point for floating-point numbers

Formatted Output Examples

  • Format numbers with specific width and precision
  • Examples:
    1. num_1 = 3.14159 print(f"{num_1:.2f}") # 3.14 num_2 = 123 print(f"{num_2:->10}") # -------123 print(f"{num_2:-<10}") # 123------- print(f"{num_2:#^11}") # ####123####

User Input

  • input() is used to take input from user. It always returns a string
  • Type conversion is required to convert input to other data types like int, float, etc.
  • Examples:
    1. name = input("Enter your name: ") print(f"Hello, {name}!") # Hello, Rabindra! length_in_cm = int(input("Enter length in cm: ")) length_in_m = length_in_cm / 100 print(f"Length = {length_in_m:.2f} m")

Comments

  • Text in code that is not executed by program
  • Used to explain code and improve readability
  • Single line comments start with #
  • Multi-line comments use triple quotes
  • Can use ctrl + / to comment/uncomment in VS Code
  • Examples:
    1. # This is a single line comment
    2. """This is a multi-line comment."""