Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 2 - Basic Python Syntax

2.4 Basic Input And Output

Your Python code interacts with users through input and output. Input allows your program to receive responses from users, while output presents results back to them.

Taking User Input:

To capture user input, you use the input() function. It retrieves user input as a string by default. For example:

num = input('Enter a number: ')

Providing Output:

Output in Python is displayed using the print() function. You can output variables or strings to the console. For instance:

print('You Entered:', num)

Combining input and output, you can create programs that interact with users:

num = input('Enter a number:')
print('\nYou Entered:', num)

The \n character in print('\nYou Entered:', num) adds a new line for better readability.

Example Program:

Let's create a program that takes two numbers from user input, performs mathematical operations, and prints the results:

str1 = input('Enter the first number: ')
str2 = input('Enter the second number: ')

# Concatenation example (string operation)
res_concat = str1 + str2
print("Concatenation Result:", res_concat)

# Conversion to integers for arithmetic operations
num1 = int(str1)
num2 = int(str2)

# Arithmetic operations
res_add = num1 + num2
res_sub = num1 - num2
res_mul = num1 * num2
res_div = num1 / num2  # Division results in a float

print("Addition Result:", res_add)
print("Subtraction Result:", res_sub)
print("Multiplication Result:", res_mul)
print("Division Result:", res_div)

In this program:

  • str1 and str2 store user input as strings.
  • num1 and num2 convert these strings into integers using the int() function.
  • Arithmetic operations (+, -, *, /) are performed on num1 and num2.
  • Results are printed using print() statements.

Remember, converting input to the appropriate type (int, float, etc.) ensures correct mathematical operations in Python.