Python- Input and Output


# 1. Using the input() function to take user input
# The input function always returns data as a string.

name = input("Enter your name: ")
age = int(input("Enter your age: "))  # Convert input to integer

print(f"Hello, {name}! You are {age} years old.")
# You can combine user input with formatted output like this.


# 2. Using the print() function and formatting with f-strings (introduced in Python 3.6+)

# a) Simple f-string example
greeting = "Hello"
name = "Alice"
print(f"{greeting}, {name}!")  # Output: Hello, Alice!

# b) Formatting numbers
pi = 3.14159265358979
print(f"Value of Pi rounded to 2 decimals: {pi:.2f}")  # Output: 3.14

# c) Padding numbers with spaces and zeros
number = 42
print(f"Right aligned (width 5): {number:5d}")   # Output: "   42" (3 spaces before 42)
print(f"Left aligned (width 5): {number:<5d}")   # Output: "42   " (3 spaces after 42)
print(f"Zero-padded (width 5): {number:05d}")    # Output: "00042" (zeros added before)

# d) Thousands separator and large number formatting
large_num = 1234567.89
print(f"Formatted with comma separator: {large_num:,.2f}")  # Output: 1,234,567.89


# 3. Using str.format() method for formatting (Older style, but still useful)

# a) Basic string formatting
name = "John"
age = 30
print("Hello, {}. You are {} years old.".format(name, age))  # Output: Hello, John. You are 30 years old.

# b) Formatting numbers with str.format()
pi = 3.14159265358979
print("Pi rounded to 3 decimals: {:.3f}".format(pi))  # Output: 3.142

# c) Padding numbers with spaces or zeros
number = 42
print("Right aligned (width 5): {:5d}".format(number))  # Output: "   42"
print("Left aligned (width 5): {:<5d}".format(number))  # Output: "42   "
print("Zero-padded (width 5): {:05d}".format(number))   # Output: "00042"

# d) Large number with commas
large_num = 1234567.89
print("Formatted with comma separator: {:,.2f}".format(large_num))  # Output: 1,234,567.89


# 4. Using % Operator (Old-style formatting, similar to C's printf)

# a) Basic string formatting
name = "Alice"
age = 25
print("Hello, %s. You are %d years old." % (name, age))  # Output: Hello, Alice. You are 25 years old.

# b) Formatting floats
pi = 3.14159265358979
print("Pi rounded to 2 decimals: %.2f" % pi)  # Output: Pi rounded to 2 decimals: 3.14

# c) Padding numbers
number = 42
print("Right aligned (width 5): %5d" % number)   # Output: "   42" (3 spaces before 42)
print("Zero-padded (width 5): %05d" % number)    # Output: "00042" (zeros added before)

#

More formatting

# 1. Integer Formatting

# a) Decimal integer
number = 123
print(f"Decimal: {number:d}")       # Output: 123
print("Decimal: {:d}".format(number))  # Output: 123
print("Decimal: %d" % number)         # Output: 123

# b) Binary representation
number = 10
print(f"Binary: {number:b}")         # Output: 1010
print("Binary: {:b}".format(number))   # Output: 1010
print("Binary: %b" % number)          # Output: 1010

# c) Octal representation
number = 8
print(f"Octal: {number:o}")          # Output: 10
print("Octal: {:o}".format(number))    # Output: 10
print("Octal: %o" % number)          # Output: 10

# d) Hexadecimal representation (lowercase)
number = 255
print(f"Hexadecimal: {number:x}")    # Output: ff
print("Hexadecimal: {:x}".format(number))  # Output: ff
print("Hexadecimal: %x" % number)     # Output: ff

# e) Hexadecimal representation (uppercase)
number = 255
print(f"Hexadecimal: {number:X}")    # Output: FF
print("Hexadecimal: {:X}".format(number))  # Output: FF
print("Hexadecimal: %X" % number)     # Output: FF


# 2. Floating-Point Formatting

# a) Fixed-point notation
pi = 3.14159265358979
print(f"Fixed-point: {pi:f}")        # Output: 3.141593
print("Fixed-point: {:.2f}".format(pi))  # Output: 3.14
print("Fixed-point: %f" % pi)        # Output: 3.141593

# b) Exponential notation (lowercase)
pi = 3.14159265358979
print(f"Exponential: {pi:e}")        # Output: 3.141593e+00
print("Exponential: {:.2e}".format(pi))  # Output: 3.14e+00
print("Exponential: %e" % pi)        # Output: 3.141593e+00

# c) Exponential notation (uppercase)
pi = 3.14159265358979
print(f"Exponential: {pi:E}")        # Output: 3.141593E+00
print("Exponential: {:.2E}".format(pi))  # Output: 3.14E+00
print("Exponential: %E" % pi)        # Output: 3.141593E+00

# d) General format (fixed-point or exponential depending on value)
pi = 3.14159265358979
print(f"General: {pi:g}")            # Output: 3.14159
print("General: {:.2g}".format(pi))    # Output: 3.1
print("General: %g" % pi)            # Output: 3.14159

# e) General format (uppercase)
pi = 3.14159265358979
print(f"General: {pi:G}")            # Output: 3.14159
print("General: {:.2G}".format(pi))    # Output: 3.1
print("General: %G" % pi)            # Output: 3.14159


# 3. String Formatting

# a) String
text = "Hello"
print(f"String: {text:s}")            # Output: Hello
print("String: {}".format(text))      # Output: Hello
print("String: %s" % text)            # Output: Hello


# 4. Other Formatting Options

# a) Percentage
ratio = 0.85
print(f"Percentage: {ratio:%}")       # Output: 85%
print("Percentage: {:.2%}".format(ratio))  # Output: 85.00%
print("Percentage: %%" % (ratio * 100))  # Output: 85%

# b) Number (locale-dependent, used with the `format` method)
from locale import setlocale, LC_NUMERIC, localeconv
setlocale(LC_NUMERIC, '')
number = 1234567.89
print(f"Number: {number:n}")         # Locale-dependent formatting


# 5. Formatting Specifications

# a) Width and Alignment
number = 42
print(f"Right aligned (width 10): {number:10d}")  # Output: "        42"
print(f"Left aligned (width 10): {number:<10d}")   # Output: "42        "
print(f"Center aligned (width 10): {number:^10d}")  # Output: "    42    "
print(f"Zero-padded (width 5): {number:05d}")      # Output: "00042"
print(f"Signed number: {number:+d}")               # Output: "+42"


# 6. Aligning Text

# a) Center alignment
text = "Python"
print(f"Center aligned (width 20): {text:^20}")   # Output: "       Python       "

# b) Right alignment
print(f"Right aligned (width 20): {text:>20}")    # Output: "              Python"

# c) Left alignment
print(f"Left aligned (width 20): {text:<20}")     # Output: "Python              "


# 7. Nested Expressions in f-strings

# Using a calculation within f-string
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}.")  # Output: The sum of 10 and 20 is 30.


# 8. Special Characters in f-strings

# Escaping curly braces
print(f"Curly braces: {{ and }}")  # Output: Curly braces: { and }



Questions 

# Problem 1: Basic String Formatting
name = "Alice"
# Print: Hello, Alice!
print(f"Hello, {name}!")  # Output: Hello, Alice!


# Problem 2: Right Alignment
number = 123
# Print: [right-aligned 123 in a field of width 10]
print(f"{number:>10}")   # Output: "        123"


# Problem 3: Left Alignment
text = "Python"
# Print: [Python left-aligned in a field of width 20]
print(f"{text:<20}")    # Output: "Python              "


# Problem 4: Zero Padding
number = 42
# Print: [42 padded with zeros to width 5]
print(f"{number:05}")   # Output: "00042"


# Problem 5: Floating-Point Precision
pi = 3.14159265358979
# Print: [pi rounded to 2 decimal places]
print(f"{pi:.2f}")     # Output: "3.14"


# Problem 6: Exponential Notation
value = 12345.6789
# Print: [value in exponential notation with 3 decimal places]
print(f"{value:.3e}")  # Output: "1.235e+04"


# Problem 7: Hexadecimal Representation
number = 255
# Print: [255 in uppercase hexadecimal format]
print(f"{number:X}")   # Output: "FF"


# Problem 8: Percentage Format
ratio = 0.876
# Print: [ratio as a percentage with 1 decimal place]
print(f"{ratio:.1%}")  # Output: "87.6%"


# Problem 9: Center Alignment
text = "Centered"
# Print: [text centered in a field of width 30]
print(f"{text:^30}")   # Output: "            Centered            "


# Problem 10: Thousand Separator
large_number = 1234567890
# Print: [large_number with comma as thousand separator]
print(f"{large_number:,}")  # Output: "1,234,567,890"




Contact us for software training, education or development










 

Post a Comment

0 Comments

Me