Module 1
Module 1
Introduction To Python
Introduction to Python programming
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
It is used for:
web development (server-side)
software development
mathematics
system scripting.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Features:
Building blocks
In order to write any program, we must be aware of its structure, available keywords and data
types and also required to have some knowledge on Variables, constants and identifiers.
Keywords, Identifiers and variables are the basic building blocks of python
1. Variables are used to store and manipulate data in a program. In Python, you can assign a
value to a variable using the assignment operator (=).
Example
3. Data Types
Python has several built-in data types, including:
Example
x = 5 # integer
y = 3.14 # float
name = "John" # string
admin = True # boolean
numbers = [1, 2, 3] # list
colors = ("red", "green", "blue") # tuple
Variable
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.
An assignment statement creates new variables and gives them values:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
This example makes three assignments.
The first assigns a string to a new variable
named message;
The second assigns the integer 17 to n;
The third assigns the
(approximate) value of π to pi.
To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
The type of a variable is the type of the value it refers to.
>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>
Types of Assignment
1. Simple Assignment: Assigns a value to a variable using the assignment operator (=).
Example
x=5
2. Multiple Assignment: Assigns multiple values to multiple variables using the assignment
operator (=).
Example
python
x, y = 5, 10
3. Chained Assignment: Assigns a value to multiple variables using the assignment operator
(=).
Example
x=y=5
Example
python
x=5
x += 3
print(x) # output: 8
5. Parallel Assignment: Assigns multiple values to multiple variables using the assignment
operator (=) and the tuple unpacking syntax.
Example
x, y = (5, 10)
Identifiers
In Python, an identifier is a name given to a variable, function, class, module, or any other
object.
Here are the rules for identifiers in Python:
Expressions
n expression in Python is a combination of values, variables, operators, and functions that
evaluates to a single value. Expressions are used to perform calculations, manipulate data, and
make decisions.
Types of Expressions
Python has several types of expressions, including:
Example
x=5
y=3
result = x + y
print(result) # output: 8
2. Comparison Expressions: These expressions use comparison operators (==, !=, >, <, etc.)
to compare values.
Example
python
x=5
y=3
result = x > y
print(result) # output: True
3. Logical Expressions: These expressions use logical operators (and, or, not) to combine
comparison expressions.
Example
x=5
y=3
result = x > y and x == 5
print(result) # output: True
4. Assignment Expressions: These expressions use assignment operators (=, +=, -=, etc.) to
assign values to variables.
## Example
python
x=5
x += 3
print(x) # output: 8
Example
def greet(name):
print("Hello, " + name + "!")
6. List Expressions: These expressions create new lists using list comprehensions.
Example
python
numbers = [1, 2, 3, 4, 5]
double_numbers = [x * 2 for x in numbers]
print(double_numbers) # output: [2, 4, 6, 8, 10]
Example
fruits = ["apple", "banana", "cherry"]
fruit_dict = {fruit: len(fruit) for fruit in fruits}
print(fruit_dict) # output: {'apple': 5, 'banana': 6, 'cherry': 6}
Arithmetic Operator
Arithmetic operators are used to perform mathematical operations on numbers. Python
supports various arithmetic operators, including addition, subtraction, multiplication, division,
modulus, exponentiation, and floor division.
Example
x=5
y=3
result = x + y
print(result) # Output: 8
2. *Subtraction Operator (-)*: The subtraction operator is used to subtract one number from
another.
Example
python
x = 10
y=4
result = x - y
print(result) # Output: 6
3. Multiplication Operator ()*: The multiplication operator is used to multiply two numbers.
Example
x=4
y=5
result = x * y
print(result) # Output: 20
4. *Division Operator (/)*: The division operator is used to divide one number by another. It
returns a floating-point result.
## Example
python
x = 10
y=2
result = x / y
print(result) # Output: 5.0
5. Modulus Operator (%): The modulus operator is used to find the remainder of a division
operation.
Example
x = 17
y=5
result = x % y
print(result) # Output: 2
## Example
python
x=2
y=3
result = x ** y
print(result) # Output: 8
7. Floor Division Operator (//): The floor division operator is used to divide one number by
another and return the largest possible integer. It rounds down to the nearest whole number.
Example
x = 10
y=3
result = x // y
print(result) # Output: 3
Logical Operator
Logical operators are used to evaluate logical expressions and return a boolean value (True or
False). They are commonly used in conditional statements, loops, and function calls.
and Returns True if both statements are true x < 5 and x < 10
1. And Operator (and): The and operator returns True if both the operands are true.
Example
x=5
y=3
result = x > 3 and y < 5
print(result) # Output: True
2. *Or Operator (or)*: The or operator returns True if at least one of the operands is true.
## Example
python
x=5
y=3
result = x > 3 or y > 5
print(result) # Output: True
3. Not Operator (not): The not operator returns True if the operand is false, and vice versa.
Example
x=5
result = not x > 3
print(result) # Output: False
Relational Opeartor
Relational operators are used to compare two values and return a boolean value (True or False).
They are commonly used in conditional statements, loops, and function calls.
1. Equal To Operator (==): The equal to operator returns True if both operands are equal.
Example
x=5
y=5
result = x == y
print(result) # Output: True
2. *Not Equal To Operator (!=)*: The not equal to operator returns True if both operands are
not equal.
## Example
python
x=5
y=3
result = x != y
print(result) # Output: True
3. Greater Than Operator (>): The greater than operator returns True if the left operand is
greater than the right operand.
Example
x=5
y=3
result = x > y
print(result) # Output: True
4. Less Than Operator (<): The less than operator returns True if the left operand is less than
the right operand.
## Example
python
x=3
y=5
result = x < y
print(result) # Output: True
5. Greater Than or Equal To Operator (>=): The greater than or equal to operator returns True
if the left operand is greater than or equal to the right operand.
Example
x=5
y=5
result = x >= y
print(result) # Output: True
6. Less Than or Equal To Operator (<=): The less than or equal to operator returns True if the
left operand is less than or equal to the right operand.
Example
python
x=3
y=5
result = x <= y
print(result) # Output: True
Order of operations
Python has a specific order of operations, known as operator precedence, which determines the
order in which operators are evaluated.
When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence.
For mathematical operators, Python follows mathematical convention. The acronym PEMDAS
is a useful way to remember
the rules:
• Parentheses have the highest precedence and can be used to force an expression to evaluate
in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in
(minute * 100) /60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not
27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8.0, not
5
• Operators with the same precedence are evaluated from left to right. So the
expression 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is
subtracted from 2.
Example
python
x=5
y=3
result = x + y * 2
print(result)
OUTPUT: 11
Example
print("Hello\nWorld")
Output:
Hello
World
## Example
python
print("Hello\tWorld")
Output:
Hello World
Example
print("Hello\World")
Output:
Hello\World
Example
python
print('Hello\'World')
Output:
Hello'World
Example
print("Hello"World")
Output:
Hello"World
Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program.
Comments enhance the readability of the code.
Comment can be used to identify functionality or structure the code-base.
Comment can help understanding unusual or tricky scenarios handled by the code to
prevent accidental removal or changes.
Comments can be used to prevent executing any specific part of your code, while
making changes or testing.
OUTPUT
geeksforgeeks
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different
ways through which we can write multiline comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python. Each and every line
will be considered as a single-line comment.
Python allows for user input. That means we are able to ask the user for input.
Python uses the input() function.
Ex:
username= input("Enterusername:")
print("Username is: " + username)
1. input() function: The input() function is used to get user input. It returns a string.
Example
name = input("Enter your name: ")
print("Hello, " + name)
2. raw_input() function: The raw_input() function is used to get user input in Python 2.x. It
returns a string.
python
name = raw_input("Enter your name: ")
print "Hello, " + name
3. int(input()): To get integer input, use the int() function with input().
Example
age = int(input("Enter your age: "))
print("You are " + str(age) + " years old.")
4. float(input()): To get floating-point input, use the float() function with input().
Example
python
height = float(input("Enter your height: "))
print("You are " + str(height) + " meters tall.")
User Output
Python provides several ways to display output to the user, including:
1. print() function: The print() function is used to display output to the user.
Example
print("Hello, World!")
2. print() with variables: You can use variables with the print() function to display dynamic
output.
Example
name = "John"
age = 30
print("My name is " + name + " and I am " + str(age) + " years old.")
3. print() with formatting: You can use formatting with the print() function to display output
in a specific format.
Example
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Errors in Python
Run-Time Exceptions
These occur during the execution of the program, such as dividing by zero or trying to access
an index that is out of range.
Example
x=5/0
Output:
ZeroDivisionError: division by zero
Syntax errors
These are the first errors you will make and the easiest to fix. A syntax error means that you
have violated the “grammar” rules of Python.
Python does its best to point right at the line and character where it noticed it was confused.
The only tricky bit of syntax errors is that sometimes the mistake that needs fixing is actually
earlier in the program than where Python noticed it was confused. So the line and character
that Python indicates in a syntax error may just be a starting point for your investigation.
These occur when there is an error in the syntax of the program, such as a missing colon or a
mismatched parenthesis.
Example
print("Hello World"
Output:
SyntaxError: unexpected EOF while parsing
Logic Error
Logic errors A logic error is when your program has good syntax but there is a mistake in the
order of the statements or perhaps a mistake in how the statements relate to one another. A good
example of a logic error might be, “take a drink from your water bottle, put it in your backpack,
walk to the library, and then put the top back on the bottle.”
These occur when the program is syntactically correct but does not produce the expected
output, such as an infinite loop or a calculation error.
Example
python
x=5
while x > 0:
x += 1
Output:
This will cause an infinite loop.
Conditional Statement
Conditional statements let you check if something is true or false and then perform various
actions based on that.
Simple IF statement
The if statement is the most simple decision-making statement.
It is used to decide whether a certain statement or block of statements will be executed
or not.
Syntax:
if expression:
statement
Ex:
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
IF...ELSE statement
The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
Syntax:
if condition:
statements
else:
statements (else-block)
Ex1:
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Ex2:
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
else:
print("The Given Number is an odd number")
function fun() is defined but contains the pass statement, meaning it does nothing when
called.
program continues execution without any errors and the message is printed after calling
the function.
Nested Conditionals
Nested conditions in Python refer to placing one if statement inside another if, elif, or else
block. This is useful when you need to check multiple conditions that depend on each other.
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
The outer conditional contains two branches. The first branch contains a simple statement. The
second branch contains another if statement, which has two branches of its own. Those two
branches are both simple statements, although they could have been conditional statements as
well.
Although the indentation of the statements makes the structure apparent, nested conditionals
become difficult to read very quickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements.
For example, we can rewrite the following code using a single conditional:
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
The print statement is executed only if we make it past both conditionals, so we
can get the same effect with the and operator:
if 0 < x and x < 10:
print('x is a positive single-digit number.')
Iteration Statement
Loops enable you to perform repetitive tasks efficiently without writing redundant
code.
They iterate over a sequence (like a list, tuple, string, or range) or execute a block of
code as long as a specific condition is met.
Types of Loops in Python
1. For Loop
2. While Loop
3. Loop Control Statements (break, continue, pass)
While
While loop is used to execute a block of statements repeatedly until a given condition
is satisfied.
When the condition becomes false, the line immediately after the loop in the program
is executed.
Syntax:
while expression:
statement(s)
Ex:
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code.
Syntax:
while condition:
statements
else:
statements
Ex:
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print(“In else block”)
for statement
For loops are used for sequential traversal
For example: traversing a list or string or array etc.
Syntax:
for iterator_var in sequence:
statements(s)
Looping Through a String
Ex:
• for x in "banana":
print(x)
• for each_character in "Blue":
print(f"Iterate through character {each_character} in the string 'Blue'")
Nested loop
A nested loop is a loop inside another loop. The inner loop runs completely for each
iteration of the outer loop.
For Example
Break Statement
Whenever the break statement is encountered, the execution control immediately jumps
to the first instruction following the loop.
With the break statement we can stop the loop before it has looped through all the items.
Ex:
for x in range(6):
if x == 3:
break
print(x)
else:
print("Finally finished!")
# If the loop breaks, the else block is not executed.
Continue Statements
With the continue statement we can stop the current iteration of the loop, and continue
with the next.
To pass control to the next iteration without exiting the loop, use the continue statement.
Ex:
for x in range(6):
if x == 3:
continue
print(x)
while/else
The while loop is used for iteration. It executes a block of code repeatedly until the condition
becomes false and when we add an "else" statement just after the while loop it becomes a
"While-Else Loop". This else statement is executed only when the while loops are executed
completely and the condition becomes false. If we break the while loop using the "break"
statement then the else statement will not be executed.
i= 1
while i< 6:
print(i)
i+= 1
else:
print("i is no longer less than 6")
Syntax:
while(Condition):
# Code to execute while the condition is true
else:
# Code to execute after the loop ends naturally
for/else statements
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished.
WAPP to print all numbers from 0 to 5, and print a message when the loop has ended
for x in range(6):
print(x)
else:
print("Finally finished!")
Python Program to Check Prime Number
= 29
output:
29 is a prime number
42
Factorial of a Number using Loop
factorial = 1
Output
Output:
Enter a number: -3
Negative number
print("{0} is Even".format(num))
else: 43
print("{0} is Odd".format(num))
Output:
Enter a number: 43
43 is Odd
# Python program to find the largest number among the three input numbers #
change the values of num1, num2 and num3
# for a different result num1
= 10
num2 = 14
num3 = 12
Output:
The largest number is 14.0