Input, Output & Comments
✕Output Function
print()displays output on screen- We can print number, text, variables, expressions
print("Hello")# Hello, World!print(5 + 2)# 7name = "Rabindra"print(name)# Rabindraage = 30print("I am", age, "years old")# I am 30 years old
Examples:
f-strings formatting
- Used to format strings by embedding expressions inside string literals
- Note: Must use
fat the beginning of the string and use curly braces{}to enclose variables name = "Rabindra"age = 30print(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.
Examples:
Format Specifiers
- Used to customize the output using f-strings
- Syntax:
{variable:format_specifier}. Specifier is in form[fill][align][width][.precision]
| Specifier | Description |
|---|---|
| Fill | Character used for padding the output (default is space). Has to be single character |
| Align | Alignment of the output: < for left, > for right, ^ for center. Default: > for numbers and < for strings |
| Width | Minimum width of the output |
| Precision | Number of digits after decimal point for floating-point numbers |
Formatted Output Examples
- Format numbers with specific width and precision
num_1 = 3.14159print(f"{num_1:.2f}")# 3.14num_2 = 123print(f"{num_2:->10}")# -------123print(f"{num_2:-<10}")# 123-------print(f"{num_2:#^11}")# ####123####
Examples:
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.
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")
Examples:
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 - # This is a single line comment
- """This is a multi-line comment."""
Examples:
