Print Function in python
The print function in Python is a powerful tool for displaying information to the screen.
Syntax: -
print(object(s), sep=separator, end=end, file=file, flush=flush)
- object(s): Any Python object (e.g., string, list, tuple) that you want to print. It will be converted to a string before being displayed.
- sep: Optional. Specifies how to separate multiple objects if you’re printing more than one. The default separator is a space.
- end: Optional. Determines what to print at the end of the output. The default is a newline character (‘n’).
- file: Optional. An object with a write method where the output will be directed. The default is sys. stdout.
- flush: Optional. A Boolean value indicating whether the output should be flushed (True) or buffered (False). The default is False.
Print a single message:
print ("Hello, World!")
Print multiple objects:
print ("Hello", "how are you?")
Specify a custom separator:
print ("Hello", "how are you?", sep="---")
Input () Function
The input function in Python is a powerful way to interact with users and obtain input from them.
Syntax: –
user_input = input(prompt)
prompt (optional): A string that displays a message to the user before accepting input.
For Example, taking the user’s name and age as input:
name = input ("Please enter your name: ")
age = input ("Please enter your age: ")
print ("My name is “, Name)
print (“I am” ,age, “ year old ”)
While Processing information for numeric type, we need to tell the interpreter about it.
Example 1
age=int (Input (“Enter your age”))
Print(age)
Example 2
temperature=float (Input (“Enter the temperature”))
Print(temperature)
#Write a Python program to add two numbers
num1 = 4.7
num2 = 7.5
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print ('The sum of {0} and {1} is {2}’. format (num1, num2, sum))
#Write a Python program to add two numbers provided by user.
# Store input numbers
num1 = input ('Enter first number: ')
num2 = input ('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print ('The sum of {0} and {1} is {2}’. format (num1, num2, sum))
#Write a Python Program to Find the Square Root.
num = float (input ('Enter a number: '))
num_sqrt = num ** 0.5
print ('The square root of %0.3f is %0.3f'% (num, num_sqrt))
#Write a Python Program to Calculate the Area of a Triangle.
a = float (input ('Enter first side: '))
b = float (input ('Enter second side: '))
c = float (input ('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a) *(s-b) *(s-c)) ** 0.5
print ('The area of the triangle is %0.2f' %area)