Learn Python
Lesson 1 - Introduction To Python
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
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.
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: ')
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.
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.+
, -
, *
, /
) are performed on num1
and num2
.print()
statements.Remember, converting input to the appropriate type (int
, float
, etc.) ensures correct mathematical operations in Python.