Introduction to Python Programming

Author

Justin Mathew

Introduction to Python

In this tutorial, we will cover the basics of Python programming, including data types, keywords, variables, input/output statements, operators, arithmetic expressions, operator precedence, and evaluation of expressions.

Data Types

Python supports several built-in data types. Let’s explore some of the most common ones:

  • Integer (int): Represents whole numbers.
  • Floating Point (float): Represents decimal numbers.
  • String (str): Represents sequences of characters.
  • Boolean (bool): Represents True or False.

Example

# Demonstrating different data types

# Integer
a = 10
print("Integer:", a, type(a))

# Float
b = 3.14
print("Float:", b, type(b))


# String
c = "Hello, Python!"
print("String:", c, type(c))

# Boolean
d = True
print("Boolean:", d, type(d))
Integer: 10 <class 'int'>
Float: 3.14 <class 'float'>
String: Hello, Python! <class 'str'>
Boolean: True <class 'bool'>

Variables

Variables are used to store data in memory. A variable is created when you assign a value to it using the = operator.

# Variable assignment

x = 5
y = 2.5
z = x + y

print("x =", x)
print("y =", y)
print("z =", z)
x = 5
y = 2.5
z = 7.5

Input and Output Statements

Python provides the input() function to take user input and the print() function to display output.

# Input and Output
name="justin"
age=32
#name = input("Enter your name: ")
#age = int(input("Enter your age: "))

print(f"Hello, {name}! You are {age} years old.")
Hello, justin! You are 32 years old.

Operators

Operators are special symbols used to perform operations on variables and values. Python supports several types of operators:

Arithmetic Operators: +, -, *, /, //, %, ** Comparison Operators: ==, !=, >, <, >=, <= Logical Operators: and, or, not Assignment Operators: =, +=, -=, *=, /=, //=, %=, **=

# Arithmetic Operations

a = 15
b = 4

addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
modulus = a % b
exponentiation = a ** b

print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Floor Division:", floor_division)
print("Modulus:", modulus)
print("Exponentiation:", exponentiation)
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

Arithmetic Expressions

An arithmetic expression is a combination of numbers, operators, and variables that evaluates to a value.

# Evaluating arithmetic expressions

expression = (5 + 2) * (10 - 3) / 2 ** 2
print("Expression Result:", expression)
Expression Result: 12.25

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression. The following list shows the precedence from highest to lowest:

** (Exponentiation) *, /, //, % (Multiplication, Division, Floor Division, Modulus) +, - (Addition, Subtraction)

# Operator precedence

result = 5 + 3 * 2 ** 2 - 1
print("Operator Precedence Result:", result)
Operator Precedence Result: 16

Evaluation of Expressions

Python evaluates expressions from left to right, following the precedence rules.

# Evaluation of expressions

value = (10 + 5) * 2 - 3 / 3
print("Evaluation Result:", value)
Evaluation Result: 29.0

Conditional Statements in Python

Conditional statements in Python allow the execution of specific code blocks based on whether a condition is true or false. Let’s explore various types of conditional statements.

The if Statement

The if statement tests a specific condition. If the condition is true, the code block under the if statement is executed.

Example

# Example of an if statement

number = 10

if number > 0:
    print(f"{number} is a positive number.")
10 is a positive number.

Explanation The above program checks if number is greater than 0. Since 10 is greater than 0, the condition is true, and the message is printed.

The if-else Statement

The if-else statement allows you to execute one block of code if the condition is true and another block if it is false.

# Example of an if-else statement

number = -5

if number >= 0:
    print(f"{number} is a non-negative number.")
else:
    print(f"{number} is a negative number.")
-5 is a negative number.

Explanation In this example, the program checks if number is greater than or equal to 0. If true, it prints that the number is non-negative. Otherwise, it prints that the number is negative. Example 2

age = 20

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")
You are eligible to vote.

Explanation This program checks if a person’s age is greater than or equal to 18. If true, it prints that the person is eligible to vote. Otherwise, it states they are not eligible to vote. ## The elif Statement The elif statement, short for “else if,” allows you to check multiple conditions sequentially. If one of the conditions is true, the corresponding block of code is executed.

# Example of an elif statement

number = 0

if number > 0:
    print(f"{number} is a positive number.")
elif number == 0:
    print(f"{number} is zero.")
else:
    print(f"{number} is a negative number.")
0 is zero.

Explanation Here, the program checks three conditions: whether the number is positive, zero, or negative. The elif statement handles the case where number is exactly 0.

# Another example of an elif statement

marks = 85

if marks >= 90:
    grade = 'A'
elif marks >= 80:
    grade = 'B'
elif marks >= 70:
    grade = 'C'
else:
    grade = 'F'

print(f"Your grade is {grade}.")
Your grade is B.

Explanation This program assigns a grade based on the marks obtained. Depending on the range in which the marks fall, the corresponding grade is assigned and printed.

Nested if-else Statements

Nested if-else statements allow you to include an if-else statement inside another if-else block for handling more complex conditions.

# Example of nested if-else statements

number = 25

if number > 0:
    if number % 2 == 0:
        print(f"{number} is a positive even number.")
    else:
        print(f"{number} is a positive odd number.")
25 is a positive odd number.

Explanation This example checks if a number is positive and then further checks whether it is even or odd using nested if-else statements.

# Another example of nested if-else statements

score = 92

if score >= 50:
    if score >= 90:
        print("Excellent!")
    else:
        print("Good job!")
else:
    print("Better luck next time.")
Excellent!

Explanation This program checks if a score is at least 50. If true, it further checks if the score is 90 or above, printing “Excellent!” if it is, and “Good job!” if it isn’t. If the score is below 50, it prints “Better luck next time.”

Programs to Solve Numerical Problems Using Different Loop Structures in Python

Introduction to Looping Concepts

Loops are fundamental to programming, enabling the repeated execution of a block of code. In Python, loops are used to iterate over a sequence of elements, perform repetitive tasks, and solve complex numerical problems efficiently. The main types of loops in Python are for loops, while loops, and nested loops. Additionally, Python provides control flow statements like break, continue, and pass to manage loop execution.

The for Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range). It automatically handles the iteration, making it straightforward to loop through each element in the sequence.

Syntax: for variable in sequence: # Code block to be executed # Program to calculate the sum of numbers from 1 to 10

sum = 0
for i in range(1, 11):
    sum += i
print("Sum of numbers from 1 to 10 is:", sum)
Sum of numbers from 1 to 10 is: 55

The while Loop

The while loop continues to execute a block of code as long as a given condition is true. This type of loop is more flexible than the for loop because it can execute an indeterminate number of times. Syntax: while condition: # Code block to be executed

# Program to find the factorial of a number
num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print("Factorial is:", factorial)
Factorial is: 120

Nested Loops A nested loop is a loop inside another loop. This allows the execution of complex iterations, where each iteration of the outer loop triggers the full execution of the inner loop.

# Program to print a multiplication table using nested loops
for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end="\t")
    print()
1   2   3   4   5   
2   4   6   8   10  
3   6   9   12  15  
4   8   12  16  20  
5   10  15  20  25  

Control Flow Statements: break, continue, and pass

break: Terminates the loop prematurely when a specific condition is met.

# Program to find the first number divisible by 7 in a list
for num in [12, 15, 21, 29, 42]:
    if num % 7 == 0:
        print("First number divisible by 7 is:", num)
        break
First number divisible by 7 is: 21

continue: Skips the current iteration and moves on to the next one when a condition is met.

# Program to print odd numbers between 1 and 10
for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i)
1
3
5
7
9

pass: Acts as a placeholder, allowing you to write a loop without any operation when needed. It is often used in scenarios where the code block needs to be defined later.

# Example of a loop with a pass statement
for i in range(5):
    pass  # Logic will be added later

The range Function

The range function is often used in for loops to generate a sequence of numbers. It allows for iteration over a range of values with control over the start, stop, and step values. range(start, stop, step)

# Program to print numbers from 1 to 5
for i in range(1, 6):
    print(i)
1
2
3
4
5

#Sample Programs Using Looping Constructs **Sum of all even numbers between 1 and 100:

sum_even = 0
for num in range(1, 101):
    if num % 2 == 0:
        sum_even += num
print("Sum of even numbers from 1 to 100 is:", sum_even)
Sum of even numbers from 1 to 100 is: 2550

#Prime number check using a while loop:

num = 29
is_prime = True
i = 2
while i <= num // 2:
    if num % i == 0:
        is_prime = False
        break
    i += 1
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")
29 is a prime number

#Fibonacci series using nested loops:

n = 10
a, b = 0, 1
print("Fibonacci series up to", n, ":")
for i in range(n):
    print(a, end=" ")
    a, b = b, a + b
Fibonacci series up to 10 :
0 1 1 2 3 5 8 13 21 34 

Functions

In this module, we will explore the concept of functions in Python. You will learn how to define and call functions, pass parameters, return values, and utilize various types of functions, including lambda functions. Additionally, we will cover type conversion, coercion, and mathematical functions.

Understanding Functions

Functions are reusable blocks of code that perform a specific task. They enhance modularity and allow for code reuse, making programs easier to manage and maintain.

Way of Writing Functions

In Python, functions are defined using the def keyword, followed by the function name and parentheses () which may include parameters. The function body is indented and contains the code that executes when the function is called.

Example:

def function_name(parameters):
    # Function body
    statement(s)

How to Call Functions

Once a function is defined, it can be called by using its name followed by parentheses. If the function takes parameters, you need to provide arguments in the parentheses.

Example:

function_name(arguments)

Passing Parameters and Return Values

Functions can accept parameters (or arguments) that are passed to them when they are called. They can also return a value using the return statement.

Example:

def add(a, b):
    return a + b

result = add(5, 3)

In this example, 5 and 3 are passed to the add function as arguments, and the function returns their sum.

Sample Programs Using Functions

Here are a few sample programs that demonstrate the use of functions in Python:

  1. Calculate Factorial of a Number
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Output: 120
120
  1. Check if a Number is Prime
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

print(is_prime(11))  # Output: True
True

Type Conversion and Coercion

Python provides several built-in functions for type conversion, such as int(), float(), and str(). Type coercion refers to the implicit conversion of data types during operations.

Example:

x = "5"
y = 10
z = int(x) + y  # Explicit type conversion
print(z)  # Output: 15
15

Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Example:

square = lambda x: x ** 2
print(square(4))  # Output: 16
16

Mathematical Functions

Python provides a module named math that includes various mathematical functions like sqrt(), sin(), cos(), and more.

Example:

import math

print(math.sqrt(16))  # Output: 4.0
print(math.sin(math.pi/2))  # Output: 1.0
4.0
1.0

Strings

In this module, we will explore the concept of strings in Python. You will learn about various string handling functions and how to write simple programs using these functions.

Strings are sequences of characters used to store and manipulate text. In Python, strings are enclosed in either single quotes (') or double quotes (").

Example:

my_string = "Hello, World!"

Python also supports multi-line strings, which are enclosed in triple quotes (’’’ or “““).

multi_line_string = '''This is a
multi-line string.'''

String Handling Functions

Python provides several built-in functions to manipulate strings. Here are some commonly used string handling functions:

len()

The len() function returns the length of a string (i.e., the number of characters).

my_string = "Hello"
length = len(my_string)  # Output: 5

upper() and lower()

The upper() function converts all characters in a string to uppercase, while lower() converts them to lowercase.

my_string = "Hello"
print(my_string.upper())  # Output: HELLO
print(my_string.lower())  # Output: hello
HELLO
hello

strip()

The strip() function removes leading and trailing whitespace from a string.

my_string = "   Hello   "
print(my_string.strip())  # Output: "Hello"
Hello

replace()

The replace() function replaces all occurrences of a substring with another substring.

my_string = "Hello, World!"
new_string = my_string.replace("World", "Python")  # Output: "Hello, Python!"

split() and join()

The split() function splits a string into a list of substrings based on a specified delimiter. The join() function does the opposite by joining a list of strings into a single string, with a specified delimiter.

my_string = "Hello, World!"
words = my_string.split(", ")  # Output: ['Hello', 'World!']
joined_string = " ".join(words)  # Output: "Hello World!"

Writing Simple Programs Using String Handling Functions

Here are a few simple programs that demonstrate the use of string handling functions:

Check if a String is a Palindrome

def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

print(is_palindrome("Madam"))  # Output: True
print(is_palindrome("Hello"))  # Output: False
True
False

###Count the Number of Vowels in a String

def count_vowels(s):
    vowels = "aeiou"
    count = 0
    for char in s.lower():
        if char in vowels:
            count += 1
    return count

print(count_vowels("Hello World"))  # Output: 3
3

###Reverse the Words in a Sentence

def reverse_words(sentence):
    words = sentence.split()
    reversed_sentence = " ".join(reversed(words))
    return reversed_sentence

print(reverse_words("Hello World"))  # Output: "World Hello"
World Hello

Concepts of Lists, Tuples, and Dictionaries

Lists

A list is an ordered collection of items which can be of any type. Lists are mutable, meaning you can change their content after creation.

Key Features

  • Syntax: []
  • Mutable: You can modify the list after it is created.
  • Operations: append(), remove(), extend(), pop(), insert(), and more.

Example

my_list = [1, 2, 3, 'a', 'b']
my_list.append(4)
my_list.remove('a')

Tuples

A tuple is similar to a list but is immutable. Once a tuple is created, its content cannot be changed.

Key Features Syntax: () Immutable: You cannot modify a tuple after it is created. Operations: Access, slicing, and concatenation.

my_tuple = (1, 2, 3, 'a', 'b')
# my_tuple.append(4)  # This will raise an error

Dictionaries

A dictionary is an unordered collection of key-value pairs. Each key must be unique.

Key Features Syntax: {} Mutable: You can change the value associated with a key. Operations: get(), items(), keys(), values(), and more.

my_dict = {'name': 'John', 'age': 30}
my_dict['age'] = 31

Operations and Functions Associated

List Operations

Adding Elements: append(), extend(), insert() Removing Elements: remove(), pop() Accessing Elements: Indexing, slicing Sorting: sort(), sorted()

Tuple Operations

Accessing Elements: Indexing, slicing Concatenation: + Repetition: * ### Dictionary Operations Adding/Updating Elements: dict[key] = value Removing Elements: del dict[key], pop() Accessing Elements: dict.get(key) Iteration: dict.items(), dict.keys(), dict.values() ### Mutable and Immutable Data Structures ### Mutable Data Structures Lists: Can be changed after creation. Dictionaries: Can have their content modified. ### Immutable Data Structures Tuples: Cannot be changed after creation. Areas of Usage Lists Use lists when you need an ordered collection of items that can change. Example: Storing a sequence of user inputs or results from computations. Tuples Use tuples when you need an ordered collection of items that should not be changed. Example: Returning multiple values from a function. Dictionaries Use dictionaries when you need a collection of key-value pairs for fast lookups. Example: Storing user information where each user ID is a key. ## Solving Problems Using Lists, Tuples, and Dictionaries ### Example Problem 1: List Manipulation

# Given a list of numbers, find the sum of even numbers
numbers = [1, 2, 3, 4, 5, 6]
even_sum = sum(num for num in numbers if num % 2 == 0)
print(even_sum)

Example Problem 2: Tuple Usage

# Given a tuple of coordinates, compute the distance from origin
coordinates = (3, 4)
distance = (coordinates[0]**2 + coordinates[1]**2)**0.5
print(distance)

Example Problem 3: Dictionary Operations

# Given a dictionary of student grades, compute the average grade
grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
average = sum(grades.values()) / len(grades)
print(average)

Mini Projects for First-Year Engineering Students

1. Simple Calculator

Description: Create a basic calculator that performs addition, subtraction, multiplication, and division. Add error handling for division by zero and invalid input.
Concepts Covered: Functions, conditionals, basic arithmetic operations.

2. To-Do List Application

Description: Develop a command-line to-do list application where users can add, remove, and view tasks. Tasks should be stored in a text file to persist between sessions.
Concepts Covered: File handling, lists, basic CRUD operations.

3. Number Guessing Game

Description: Build a game where the computer randomly selects a number within a given range, and the user has to guess it. Provide feedback on whether the guess is too high or too low, and count the number of attempts.
Concepts Covered: Random number generation, loops, conditionals.

4. Simple Bank Management System

Description: Implement a basic bank management system where users can create an account, check balance, deposit money, and withdraw money. Use a dictionary to store user data.
Concepts Covered: Dictionaries, functions, basic data management.

5. Temperature Converter

Description: Create a program that converts temperatures between Celsius, Fahrenheit, and Kelvin. Allow users to input the temperature and select the conversion type.
Concepts Covered: Functions, user input, basic arithmetic.

6. Quiz Application

Description: Design a quiz application that presents multiple-choice questions to the user. Keep track of the score and display it at the end.
Concepts Covered: Lists, dictionaries, loops, conditionals.

7. Simple Contact Book

Description: Build a contact book where users can add, view, update, and delete contact information. Store contacts in a dictionary or text file.
Concepts Covered: File handling or dictionary operations, CRUD operations.

8. Tic-Tac-Toe Game

Description: Create a simple text-based Tic-Tac-Toe game where two players can play against each other. Implement a function to check for win conditions.
Concepts Covered: Lists, functions, game logic.

9. Password Generator

Description: Develop a program that generates random passwords with a specified length and complexity. Allow users to choose the types of characters (e.g., letters, numbers, symbols).
Concepts Covered: Random module, strings, functions.

10. Student Grade Management System

Description: Create a system to manage student grades. Users can input grades, view grades for individual students, and calculate the average grade for each student.
Concepts Covered: Lists, dictionaries, basic statistics.