1.
Input in Python
Definition:
Input means taking information from the user during program execution.
In Python, this is done using the input() function.
It always returns the data as a string, even if the user enters a number.
Syntax:
variable_name = input("Message for user")
Example:
name = input("Enter your name: ")
print("Hello", name)
Output:
Enter your name: xyz
Hello xyz
Note:
If you want a numeric input, convert it using int() or float():
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
2. Output in Python
Definition:
Output means displaying information or results to the user.
In Python, this is done using the print() function.
Syntax:
print(value1, value2, ...)
Example:
print("Welcome to Python programming!")
You can print multiple values:
name = "xyz"
marks = 95
print("Name:", name, "Marks:", marks)
You can also use formatted output:
print(f"{name} scored {marks} marks.")
Output:
xyz scored 95 marks.
Here’s a simple comparison table of input() vs print() in Python:
Feature input() print()
Purpose Used to take input from the user Used to display output on the screen
Function Type Input function Output function
Syntax variable = input("message") print(value1, value2, …)
Data Type
Always returns data as a string Does not return anything (only displays)
Returned
Example name = input("Enter your name: ") print("Hello", name)
age = int(input("Enter your age: print("Next year you will be", age
Usage Example ")) + 1)
Quick summary:
Use input() when you want to get data from the user.
Use print() when you want to show results or messages to the user.
Take Multiple Input in Python
We are taking multiple input from the user in a single line, splitting the values entered by the user into separate
variables for each value using the split() method. Then, it prints the values with corresponding labels, either two or
three, based on the number of inputs provided by the user.
Eg. # taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
Variable in Python
Definition:
A variable is a name used to store a value in a program.
It acts like a container that holds data which can be changed or used later in the program.
Example:
name = "xyz"
age = 200
marks = 85.5
print("Name:", name)
print("Age:", age)
print("Marks:", marks)
Output:
Name: xyz
Age: 200
Marks: 85.5
Rules for Naming Variables:
1. Must start with a letter or underscore (_).
Example: _name, student1
2. Cannot start with a number.
1name → invalid
3. Cannot contain spaces or special symbols.
student name, age@ → invalid
4. Variable names are case-sensitive.
Example: Age and age are different.
5. Avoid using Python keywords
(e.g., if, else, for) as variable names.
Types of Variables:
Based on the data stored:
x = 10 # integer
y = 3.14 # float
z = "Python" # string
Changing Variable Value:
You can assign a new value anytime.
x = 5
print(x)
x = 10
print(x)
Output:
5
10
Why Variables are Important:
They store information temporarily while a program runs.
Help make programs flexible and readable.
Would you like me to add a small table showing variable name examples (valid and invalid)?
Variable Name Valid / Invalid Reason
name ✅ Valid Starts with a letter
age1 ✅ Valid Letters and numbers allowed
_total ✅ Valid Can start with an underscore
Name ✅ Valid Case-sensitive (different from name)
1age ❌ Invalid Cannot start with a number
student name ❌ Invalid Spaces not allowed
marks% ❌ Invalid Special symbol % not allowed
class ❌ Invalid It’s a Python keyword
total_marks ✅ Valid Underscore used instead of space
@score ❌ Invalid Cannot start with @ or any symbol
Operators in Python
Definition:
Operators are special symbols used to perform operations on variables and values.
Example: +, -, *, /
1. Arithmetic Operators
Used for basic mathematical operations.
Operator Meaning Example Output
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 2 * 3 6
/ Division 10 / 2 5.0
// Floor Division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponent (power) 2 ** 3 8
eg
# Variables
a = 15
b = 4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)
output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
2. Comparison (Relational) Operators
Used to compare two values.
They return True or False.
Operator Meaning Example Output
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7 > 3 True
< Less than 4 < 2 False
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 6 <= 8 True
Eg
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
output
False
True
False
True
False
True
3. Assignment Operators
Used to assign values to variables.
Operator Meaning Example Same As
= Assign x = 5 —
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 4 x = x * 4
/= Divide and assign x /= 2 x = x / 2
%= Modulus and assign x %= 3 x = x % 3
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
4. Logical Operators
Used for logical decisions (True/False).
Operator Meaning Example Output
and
True if both conditions are (5 > 2 and 6 > 3)
True
true
or
True if any one condition is (5 > 2 or 6 < 3)
True
true
not Reverses the result not(5 > 2) False
a = True
b = False
print(a and b)
print(a or b)
print(not a)
output
False
True
False
Keywords in Python
Definition:
Keywords are special reserved words in Python that have predefined meanings.
They are part of the Python language syntax and cannot be used as variable names.
Examples of Keywords:
Category Keywords Meaning / Use
Logical / Boolean True, False, None Represent truth values and null
Control Flow if, else, elif Used for decision making
Loops for, while, break, continue, pass Used to repeat code blocks
Functions def, return, lambda Define and return from functions
Class / Object class, self, del Used for object-oriented programming
Import / Module import, from, as Used to include external modules
Exception Handling try, except, finally, raise, assert Handle and raise errors
Variable Scope global, nonlocal Define variable scope
Others and, or, not, in, is, with, yield Logical, membership, and other operations
Total Keywords:
Python has around 35 keywords (number may vary with versions).
import keyword
print([Link])
What Happens if We Use Keywords as Variable Names ?
If we attempt to use a keyword as a variable, Python will raise a SyntaxError.
Ex
for = 10
print(for)
Output
Hangup (SIGHUP)
File "/home/guest/sandbox/[Link]", line 1
for = 10
^
SyntaxError: invalid syntax
Variables vs Keywords
Variables Keywords
Reserved words with predefined
Used to store data.
meanings in Python.
Can be created, modified, and deleted by the Cannot be modified or used as
programmer. variable names.
Examples: x, age, name Examples: if, while, for
Hold values that are manipulated in the Used to define the structure of
program. Python code.
Variable names must follow naming rules but Fixed by Python language and cannot
are otherwise flexible. be altered.
Data Types in Python
Definition:
A data type defines the kind of value stored in a variable and what operations can be done on it.
For example, numbers are used for calculations, and strings are used for text.
1. Numeric Data Types
Type Example Description
int x = 10 Whole numbers (no decimals)
float y = 3.14 Decimal numbers
complex z = 2 + 3j Numbers with real and imaginary parts
2. String Data Type
Type Example Description
str name = "Srini" Sequence of characters enclosed in quotes
Example:
name = "Srini"
print("Hello", name)
3. Boolean Data Type
Type Example Description
bool is_student = True Represents logical values True or False
Example:
x = 5
y = 10
print(x < y) # Output: True
4. Sequence Data Types
Type Example Description
list fruits = ["apple", "banana", "mango"] Ordered and changeable collection
tuple colors = ("red", "green", "blue") Ordered but unchangeable collection
range r = range(5) Sequence of numbers (0 to 4)
5. DictionaryData Type
Type Example Description
dict student = {"name": "Srini", "age": 20} Stores data in key–value pairs
6. Set Data Types
Type Example Description
set a = {1, 2, 3} Unordered collection of unique items
frozenset b = frozenset({1, 2, 3}) Like set, but cannot be changed
7. None Type
Type Example Description
NoneType value = None Represents “no value” or null
Conditional statements
Conditional statements in Python are used to execute certain blocks of code based on specific conditions.
These statements help control the flow of a program, making it behave differently in different situations.
If Conditional Statement
If statement is the simplest form of a conditional statement. It executes a block of code if the given
condition is true.
Eg
age = 20
if age >= 18:
print("Eligible to vote.")
Output
Eligible to vote.
Short Hand if
Short-hand if statement allows us to write a single-line if statement.
age = 19
if age > 18: print("Eligible to Vote.")
Output
Eligible to Vote.
If else Conditional Statement
If Else allows us to specify a block of code that will execute if the condition(s) associated with an if or elif
statement evaluates to False. Else block provides a way to handle all other cases that don't meet the
specified conditions.
Ex
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output
Travel for free.
Short Hand if-else
The short-hand if-else statement allows us to write a single-line if-else statement.
marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")
Output
Result: Pass
Note: This method is also known as ternary operator. Ternary Operator essentially a shorthand for the if-
else statement that allows us to write more compact and readable code, especially for simple conditions.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple conditions, providing a way to
execute different blocks of code based on which condition is true. Using elif statements makes our code
more readable and efficient by the need for multiple nested if statement.
Eg.
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
The code checks the value of age using if-elif-else. Since age is 25, it skips the first two conditions (age <=
12 and age <= 19), and the third condition (age <= 35) is True, so it prints "Young adult.".
Nested if..else Conditional Statement
Nested if..else means an if-else statement inside another if statement. We can use nested if statements to
check conditions within conditions.
Ex
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output
30% senior discount!