Sachin SK - Python For Practice

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

1

Content

1. Introduction ……………………………………………………………………………… 3.
2. Basics of Python programming ……………………………………………………. 5.
3. Python input and output statement ……………………………………………… 12.
4. Python program on string …………………………………………………………… 17.
5. Python List ………………………………………………………………………………. 23.
6. Python tuples …………………………………………………………………………… 29.
7.

2
Chapter – 1
Introduction to Python
Python was created by Guido van Rossum and first released in 1991. Its design philosophy emphasizes
code readability and ease of use, which has made it a favorite among beginners and experienced
developers alike. To start using Python, you need to have it installed on your system.

History of Python
Python's history dates back to the late 1980s when Guido van Rossum, a Dutch programmer, began
working on it. He aimed to create a successor to the ABC language, which was known for its simplicity. In
February 1991, Python 0.9.0 was released, marking the birth of Python as we know it today.

Installing Python
Before we can start writing Python code, we need to install the Python interpreter on our system.
Python is available for various operating systems, including Windows, macOS, and Linux. Let's walk
through the installation process for your specific platform.

Windows Installation
1. Visit the official Python website at https://www.python.org
2. Navigate to the Downloads section and click on the "Python X.X.X" link (where X.X.X
represents the latest Python version).
3. Scroll down to the Files section and choose the installer that corresponds to your system
architecture (32-bit or 64-bit).
4. Run the downloaded installer.
5. On the first installation screen, make sure to check the box that says "Add Python X.X to
PATH." This option ensures that you can run Python from the command line.
6. Click the "Install Now" button.

3
7. Python will be installed on your system.

MacOS installation
1. Open a web browser and go to https://www.python.org/.
2. Navigate to the Downloads section and click on the "Python X.X.X" link (where X.X.X
represents the latest Python version).
3. Scroll down to the Files section and download the macOS installer.
4. Run the downloaded installer.
5. Follow the installation instructions, and Python will be installed on your macOS system.

Linux Installation
Python is often pre-installed on Linux systems. You can check if it's available by opening a
terminal and running the following command:

If Python is not installed, you can typically install it using your distribution's package manager. For
example, on Delian-based systems like Ubuntu, you can use the following command:

Now that you have Python installed, let's move on to writing your first Python program.

4
Chapter – 2.
Basics of python programming
What is python?
Python was visualized in the late 1980s. Its implementation began in 1989 by Guido van Rossum from
Netherlands. Python got Its name from “Monty python’s Flying circus”. Python 2.0 was released in the
year 2000. In brief Python is a multi-paradigm programming interpreted programming language. This is
because it supports, procedural programming (structured), fully object-oriented programming and his
features that supports functional programming.

Python is an interpreted language and Python programs are executed by an interpreter.

Python keywords
Keywords are reserved words and they cannot be used as names for identifiers or programmer defined
variable. The keywords are listed in the keyword module and can be printed with the example python
program:
Keyword_python.py

5
Output

Python variable

A variable is a name that refers to a value stored in memory location. Rules followed for writing python
variable are as follow.

 A python variable must begin with a latter (a-z, A-Z) or underscore (_) followed by letters,
numbers or underscore.
 Python variable are case sensitive (variable name sum and Sum are two different variables)
Happy_new_year valid variable
1_happy_new_year invalid variable
Happy_new_year@ invalid variable
_happy_new_year valid variable

Variables can be assigned values with the assignment statement. Look at the Following
assignment.
>>>str = ‘Hello!’
>>>sum = 0
>>>term = 0.0000256

The variable str hold a string ‘Hello!’, whereas the variable sum holds an integer value 0 and the
variable term holds a floating point value of 0.0000256.

It Is observed that no data type was specified while specifying variables. This is because python
decided the type of variable based upon the value that holds it at runtime. This is known as
dynamic type interpretation.

Python Data Types


Variables in python are type less. Python supports dynamic typing and the variable type is
decided at run type. Python data types can be categorized as shown in below figure.

6
Python Data Types

Numeric Sequence Sets Mapping

Int String Dictionary


Set
Float List
Frozen set
Complex Tuple
Boolean

To determine the data type of the variable, use the type () function in python.

Python program: Datatype.py

Example: -

Input

7
Output

python constant

The following are built-in constant in python:

 True – represent the true value of Boolean type


 False - represent the true value of Boolean type
 None – is used to represent the absence of value

Write a python program (TestBool.py) using Boolean data types

Input

Output

8
Note: Boolean data type are subtypes of integers and when they are used in context of arithmetic
expressions they become 0 and 1 representing False and True.

Python operators
An operator is a special symbol that helps the user to write arithmetic or logical computations. The
operand specifies the data that is to be manipulated by the operator.

Example: operand

8+3

Operator

 Arithmetic operators
Arithmetic operators are symbol that can be used for mathematical operations. The common
operators are addition (+), subtraction (-), multiplication (*), integer division (//), floating point
division (/), reminder (%). Now these operators are applied to binary expressions. i.e., the
operator requires two operands. However, the + operators can be used for both binary from
and unary from. Also the minus operators in the Python can be used for both binary as well as
unary operations. Note in case of unary operations the operator works only on one operand.
Operator Description Example
+ Addition operator >>>20+67
87
- Subtraction operator >>>87-20
67
* Multiplication >>>20*67
1340
/ Division operator >>>60/3
20.0
// Floor Division operator >>>60//3
20
% Modulus operator >>>3.5%1.0
0.5

9
** Exponentiation operator >>>4**10
1048576
+ Unary Plus operator >>>+44
>>>+4.0
4.0
- Unary Minus operator >>>-44
>>>-4.0
-4.0

 Relational operators
Python supports the following relational operators:
Operator Description Example
== Logical comparison >>>40==20
False
!= Not equal to >>>866! =786
True
> Greater than >>>786>678
True
< Less then >>>987<999
True
>= Greater then equal to >>>50>=39
True
<= Less than equal to >>>50<=39
False

The relational operators compare their operands and return a Boolean value as a result of the
comparison.

 Assignment operators
The following is the list of assignment operators supported in python.
Operat Description Example
or
= Assignment >>>a=10
operator >>>print(a)
10
+= Compound >>>a=10
Addition >>>a+=a
>>>print (a)

10
assignment 20
operator
-= Compound >>>a= 20
subtraction >>>a - = a
assignment >>>print(a)
operator 0
*= Compound >>> a =20
multiplicatio >>>a*=a
n >>>print(a)
assignment 400
operator
/= Compound >>>a = 30
division >>>a / = 3
assignment >>>print(a)
operator 10.0
%= Compound >>>a = 40
modulus >>>a% = a
assignment >>>print(a)
operator 0
**== Compound >>>a = 39
exponentiati >>>a**=a
on >>>print(a)
assignment 112595147462071192539789448988889059930192105219196517
operator 009951959
//== Compound >>>a=98
floor division >>>a//=a
assignment >>>print(a)
operator 1

11
Chapter – 3
Python Input and Output Statement

Input statement of python


Most programs accept inputs from the user through the keyword. Python provides built-in function for
the same.

Input () function

Input () prompt the user to enter a data and returns the output as a string. It takes a string argument
that gives the prompt for the user to enter data.

Example: - write a python program to input a user name, age and city.

Output:

12
Output statements in python

 Print () function \
As the program has to generate output to the standard console, we have the print () function for
the same.
Example: - write a python program to accept your name and display your name by appending it
with a greeting.

Output:

13
Python math Library

Python provides useful mathematical function in a math Library. This Library is implemented as
a module. Some of the functions provide in the math library are specified in Table.
Name Description
sqrt(x) Returns the square root of x
pow(x, y) Returns x raised to y
log10(x) Returns the base 10 logarithm of x
pi Returns the mathematical constant pi= 3.141592
e Returns the mathematical constant e = 2.718281
ceil(x) Returns the smallest integer value greater than or equal to x.
Fabs(x) Returns the absolute value of x.
Factorial(x) Returns the x factorial
Sin(x) Returns the sin of x in radians.
Cos(x) Returns the cosine of x in radians.
Tan(x) Returns the tangent of x radians.
Radians(x) Convert the angle x from degrees to radians.
Degrees(x) Convert the angle x from radians to degrees.

Example: write a python program to demonstrate the usage of built-in mathematical functions.

14
Output:

15
16
Chapter – 4
Python programs on string

String in python

Strings in python are created by enclosing them in double quotes. For example, “Hello
World”. The enclosed quote can be single or double. Example ‘Hello’, ‘World’. There is no
different between strings enclosed in single or double quotes.

Notes: there is no char data type supported in python.

Reading string from keyword


As we have seen earlier input () helps to read a string from the keyword.

Output

17
Accessing strings
To access string in python we can use index in square brackets.

Example:

Output:

Note: single and double quoted strings in python are identical.

Modifying strings in python


Strings in python are immutable. Once they have been created they cannot be modified.

18
Output:

String Concatenation
You can concatenate two string by using the + operator. The plus operator takes the string on the
left side and clubs it with the string on the right side.

Example:

19
Output:

String updating
You can update a string by creating a new string variable and assigning the required substrings.

Output:

20
Finding the Length of a String
To find the length of a string you can use the built-in method Len().

Output:

Iterating through a string


We can use a for loop or while loop to iterate through a string.

Example:

21
Output:

22
Chapter – 5
Python Lists
Introduction
In python a sequence is considered as a generic term for an ordered set. The example of data structures
which are types of sequences are List, tuples and strings. List is considered as the most versatile
sequence type data structure. It is mutable.

i.e., the element of the list can change over a period of time.

Example:

output:

Accessing Element of a list


We can access element of a list with square brackets [] and an index value. The index value for list
begins with the value 0 in python.

23
Output:

Modifying Element of a list


List are mutable, i.e., they can be modified. Lists can be modified as a single object or through slice
operators.

Example: A python program to demonstrate list modification.

24
Output:

Deleting Elements of a list


The del statement can be used to remove a single element or all element through the slice operation.

Example: python program to demonstrate deletion of elements in a list.

25
Output:

Built-in List Function


 Len(list): returns the number of items in a list.
 max(list): returns the element from the list which has the maximum value.
 min(list): returns the element from the list which has the minimum value.

Note: cmp(list1,list2) is no longer supported in python 3.0

 list(sequence): The built-in function returns the input sequence as a list.

Example: Write a python program to demonstrate the built-in function for lists.

Output:

26
Python List Methods
 list. insert (index, element): the list method inserts the element at the specified index by
shifting the element to the right.
 list. Index (element): This list method searches for the specified element from the start and if
the element is found it returns the index or else returns an error.
 list. Remove (element): This list searches for the first instance of the element and removes it
from the list else it generates an error.
 list. Count (element): This list method counts how many times the element occurs in the list.
 list. append (element): This list method adds an element to the end of the list.
 list. sort (): This list method sorts the element of the list in place.
 list. extend (list A): This list method adds the element of list A at the end of the list with which
the extend method was invoked.
 list. reverse (): This list method reverses the element of the list in place.
 list. pop (element): This list method removes and returns the element specified by the index.

Example: Write an python program to demonstrate Lists methods.

27
Output:

28
Chapter – 6
Python Tuples
Introduction
Tuple are sequence similar to lists expect that they are immutable, i.e., they cannot be changed and
they use parenthesis. A tuple is also defined as set of comma-separated sequence of values. It has
similarity with what is defined as a Record in most of the programming language, i.e., it is used to club
heterogeneous types. For example, an employee whose information consists of Employee_Id, Name,
and Age.

Accessing Element of a Tuple


To access tuple elements, you can use square brackets with an index number or you can use slicing
operations to get tuples elements.

Example: Python program to access elements of a tuple.

Output:

29
Deleting Elements of a Tuple
Individual elements of a tuple cannot be deleted. However, you can delete an entire tuple with the del
statement.

Output:

30
Practice:

1. write the output of the following python program

2. Write a python program using tuples to compute if the number of odd value elements and even
value elements are the same.

31

You might also like