Chapter 4

Input and Output of Python

input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution.

https://www.geeksforgeeks.org/python/input-and-output-in-python/

input in Python

Python's input() function is used to take user input. By default, it returns the user input in form of a string.


name = input("Enter your name: ")
print("Hello,", name, "! Welcome!") 

The code prompts the user to input their name, stores it in the variable "name" and then prints a greeting message addressing the user by their entered name.

Demonstration of input in python by code above in python editor and run scrip files

Output using print() in Python

At its core, printing output in Python is straightforward, thanks to the print() function. This function allows us to display text, variables and expressions on the console. Let's begin with the basic usage of the print() function: In this example, "Hello, World!" is a string literal enclosed within double quotes. When executed, this statement will output the text to the console.


    print("Hello, World!")

Printing Variables

We can use the print() function to print single and multiple variables. We can print multiple variables by separating them with commas. Example:


# Single variable
s = "Test"
print(s)

# Multiple Variables
s = "Sunya"
age = 35
city = "Songkhla"
print(s, age, city)

Output

How to Change the Type of Input in Python

By default input() function helps in taking user input as string. If any user wants to take input as int or float, we just need to typecast it.


# Typecasting to int
n = int(input("Please Enter Number 1:"))
m = int(input("Please Enter Number 2:"))
T = n+m
print("Sum of Number1+Number2 =",T)

Output

Float/Decimal Number in Python

The code prompts the user to input the price of each rose as a floating-point number, converts the input to a float using typecasting and then prints the price.


# Typecasting to float
n = float(input("Please Enter Number 1:"))
m = float(input("Please Enter Number 2:"))
T = n+m
print("Sum of Number1+Number2 =",T)


Output

Assigment

Write a program that takes input in degrees Celsius and converts it to degrees Fahrenheit.

หัวข้อ