0% found this document useful (0 votes)
10 views56 pages

Ece Project3

The document provides an overview of language, computer language, coding, and programming, explaining the differences between low-level and high-level programming languages. It focuses on Python, detailing its history, features, applications, versions, and installation process, along with comparisons to C and Java. Additionally, it covers Python syntax, keywords, identifiers, literals, and variables.

Uploaded by

rohitbunny2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views56 pages

Ece Project3

The document provides an overview of language, computer language, coding, and programming, explaining the differences between low-level and high-level programming languages. It focuses on Python, detailing its history, features, applications, versions, and installation process, along with comparisons to C and Java. Additionally, it covers Python syntax, keywords, identifiers, literals, and variables.

Uploaded by

rohitbunny2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

1. What is Language?

Naturally a language is the source of communication between two persons, language is used
to fallow sum instructions.

2. What is computer language?

Computer language is also used to follow sum of instructions to communicate between


people to machine like computer with the help of sum instructed programs. The languages we
can use to communicate with the computer are known as computer programming languages.

3. What is Coding?

Coding is a list of step by step instructions that get computers to do what you want them to do.
Coding makes it possible for us to create computer software, games, apps and websites.
Coders or Programmers behind everything we see and do on a computer.

4. What is Programming?

Programming is the process of creating a set of instructions that tell a computer how to
perform a task.
Programming can be done using a variety of computer programming languages such as
JavaScript, Python, and C++.

PROGRAMING LANGUAGES:-

It is a kind of application software uses to develop the software.


Generally there are two major types of languages are available as fallows.

1. Low level languages:


Low level languages are machine level, machine dependent and assembly
level languages. In machine level language computer only understand digital number i.e., in
the form of 0 and 1. So, instruction given is in the form binary digit, which is difficult to
implement instruction in binary code.

2. High level languages:

These languages are machine independent & program oriented language,


means it is portable. The language in this category is C, C++, java, Pascal, basic, python, etc...
High level languages are not understood by the machine. So it needs to translate by the

1
translator in to machine level. A translator is software which is used to translate high level
languages to machine level languages.

History of Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Guido Van Rossum is known as the founder of python programming.
It was created by Guido van Rossum during 1985- 1990.

2
Features of Python
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.

2) Expressive Language
Python language is more expressive means that it is more understandable and readable.

3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.

5) Free and Open Source


Python language is freely available at official web address. The source-code is also available.
Therefore it is open source.

6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.

3
8) Large Standard Library
Python has a large and broad library and provides rich set of module and functions for rapid
application development.

9) GUI Programming Support


Graphical user interfaces can be developed using Python.

10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.

Python applications :
 Web Applications
 Enterprise Applications
 Software Development Applications
 Desktop GUI Applications
 3D CAD Applications
 Scientific and Numeric Applications
 Image Processing Applications
 Audio or Video-based Applications
 Console-based Applications
 Business Applications

Python versions:
Python Version Released Date
Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

4
Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016


Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

Flavors of Python
Flavors of Python simply refers to the different Python compilers. These flavors are useful to
integrate various programming languages into Python. Let us look at some of these flavors :

1. CPython : CPython is the Python compiler implemented in C programming


language. In this, Python code is internally converted into the byte code using
standard C functions. Additionally, it is possible to run and execute programs
written in C/C++ using CPython compiler.

2. JPython : Earlier known as JPython. JPython is an implementation of the


Python programming language designed to run on the Java platform. J Python is
extremely useful because it provides the productivity features of a mature
scripting language while running on a JVM.

3. PyPy : This is the implementation using Python language. PyPy often runs
faster than CPython because PyPy is a just-in-time compiler while CPython is
an interpreter.

4. IronPython : IronPython is an open-source implementation of


the Python programming language which is tightly integrated with
the .NET Framework.

5
5. RubyPython : RubyPython is a bridge between the Ruby and Python
interpreters. It embeds a Python interpreter in the Ruby application’s process
using FFI (Foreign Function Interface).

6. Pythonxy : Python(x,y) is a free scientific and engineering development


software for numerical computations, data analysis and data visualization
based on Python.

7. StacklessPython : Stackless Python is a Python programming language


interpreter. In practice, Stackless Python uses the C stack, but the stack is cleared
between function calls.

8. AnacondaPython : Anaconda is a free and open-source distribution of


the Python and R programming languages for scientific computing, that aims to
simplify package management and deployment. Package versions are managed
by the package management system conda.

Installation of Python

Visit the link https://www.python.org/downloads/ to download the latest release of Python. In


this process, we will install Python latest version on our Windows operating system.

6
Double-click the executable file which is downloaded; the following window will open.
Select Customize installation and proceed.

The following window shows all the optional features. All the features need to be installed
and are checked by default; we need to click next to continue.

The following window shows a list of advanced options. Check all the options which you
want to install and click next. Here, we must notice that the first check-box (install for all
users) must be checked.

7
Now, we are ready to install python-3.6.7. Let's install it.

Now, try to run python on the command prompt. Type the command python in case of
python2 or python3 . It will show an error as given in the below image. It is because we
haven't set the path.

To set the path of python, we need to the right click on "my computer" and go to Properties
→ Advanced → Environment Variables.

8
Add the new path variable in the user variable section.

9
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.

Default Path is C:\Users\[user]\AppData\Local\Programs\Python\Python[version]


Now, the path is set, we are ready to run python on our local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements.

Example:
print(“Hello World”)

10
How to Run Python Programs
There are three way to execute python code they are given below;
 Interactive Mode(Shell)
 Script Mode(.py)
 Using IDE

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest not to write the
code in a file. This is made possible because Python can be run as a command line itself.

Type the following on the Windows, Mac or Linux command line:


C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py

Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface: exit()

Execute Python Syntax


As we learned in the previous page, Python syntax can be executed by writing directly in the
Command Line:

>>> print("Hello, World!")


Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
C:\Users\Your Name>python myfile.p

Note: Python follows indentation. Indentation very important in python. If we not follow
indentation the program will not execute.

IDE
IDE is nothing but Integrated Development Environment. IDE is a tool that provides user
interface with compilers to create, compile and execute Java programs.

Python have its own platform with operating system like windows, Linux and Mac but it’s
difficult to work (complex) so we can use IDE.

These provide Integrated Development Environment with compiler for Python. Some of ides
are shown below

11
An integrated development environment (IDE) is a software suite that consolidates basic
tools required to write and test software.

Installation of VScode
1. Download vs code latest version from the browser. By searching vs code download.

Download windows flavour and click to install, accept the agreement.

12
Click on Next and Click on Install.

After successful installation go to settings and change the theme if you want, increase font
size as your wish and change auto save option to yes.

Practice creation of files and folders.

Download the extensions:


1. Material icon theme.----- To change the icons as effectively.
2. Python(Microsoft)--------- to get run  button when we write the code and save
as .py
3. Python preview
4. Arepl for python ---------- to get output while writing the code.
5. Code runner ---------------- to run the code and to see output.
6. Python indent

git config user.name “ram”


git config user.email “[email protected]

13
C vs Python:
C Python
 C is a procedure-oriented  Python is object oriented
programming language. programming language
 C language does not contain the  Python contain the features like
features like Class, object, Class, Object, Inheritance, etc.
inheritance, etc.  In python datatype declaration is
 In C language datatype declaration not required.
is compulsory.  Python Only supports single
 C supports single and multi- Dimensional Array. By using third
dimensional arrays. party like NumPy library we can
 It works on Positive index only. run multi dim Array.
 Pointer – yes  It works on both positive and
 C program execute faster.(compiler) negative index.
 C supports Do while, switch.  Pointer – no
 C does not have Exception  Python program are slower than
handling then programs are Weak. C.(dynamic typed
 C should be responsible for variables)(interpreter)
allocate and deallocate memory.  Python not supports Do-While,
switch. (we can use for else also)
 Python have exceptions handling
then programs are robust.
 In python memory allocation and
deallocation is done automatically
by PVM.

JAVA vs PYTHON:
JAVA
 Java type declaration compulsory.
 Java supports single and multi-dimensional arrays.
 It works on Positive index only.
 Java supports Do while, switch.
 In Java memory allocation and deallocation is done automatically by JVM.

Python
 In python datatype declaration is not required.
 Python Only supports single Dimensional Array. By using third party like NumPy
library we can run multi dim Array.
 It works on both positive and negative index.
 Python not supports Do-While, switch. (we can use for else also)

14
In general, the interpreter reads and executes the statements line by line i.e sequentially.
Though, there are some statements that can alter this behavior like conditional statements.
Mostly, python statements are written in such a format that one statement is only
written in a single line. The interpreter considers the ‘new line character’ as the terminator of
one instruction. But, writing multiple statements per line is also possible that you can find
below.

Example:
print(“Hello World”)

Comments:
# I am single line comment

""" Multi-line comment used


print("Python Comments") """

15
Tokens

Keywords in Python
Keyword is a predefined or reserved word in Python with a fixed meaning and used to
perform.
Every Keyword exists in lower case letter like auto, break, case, const, continue, int etc.
There are nearly 35 keywords in Python.

Identifier
Identifiers in Python are names given to different parts of a Python program like variables,
functions, classes, etc. They are user-defined and the users must follow a set of rules to define
them in a python program.

Literals
A literal in Python is a syntax that is used to completely express a fixed value of a specific
data type. Literals are constants that are self-explanatory and don’t need to be computed or
evaluated. They are used to provide variable values or to directly utilize them in expressions.
Types of Literals in Python
 String literals
 Character literal
 Numeric literals

16
 Boolean literals

String Literals
# in single quote
s = 'geekforgeeks'

# in double quotes
t = "geekforgeeks"

# multi-line String
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)

Numeric Literals
 Integer
Integer values can represent in 4 ways:
1. Binary (base 2) ----------- 0 and 1
2. Decimal (base 10)------- 0,1,2,3,4,5,6,7,8,9
3. Octal (base 8) -------------0,1,2,3,4,5,6,7
4. Hexadecimal (base 16)---------0,1,2,3,4,5,6,7,8,9 & A,B,C,D,E,F

 Float
 Complex
Example:
# integer literal
# Binary Literals
#we can specify literal value even in binary form also, allowed digits are 0 and 1. Literals
value should be prefixed with 0b or 0B.
a = 0b10100

# Decimal Literal
b = 50

# Octal Literal(Base 8)
#Here Octal number should be prefix with 0o.
c = 0o320

# Hexadecimal Literal(Base 16)


#In this form, the allowed digits are 0-9, and characters are a-f. We can use both uppercase
and lowercase characters as we know that java is a case-sensitive programming language, but
here java is not case-sensitive.
#The hexa-decimal number should be prefix with 0X or 0x.
d = 0x12b

17
print(a, b, c, d)

Example:
# Float Literal
e = 24.8
f = 45.0

print(e, f)

Example:
z = 7 + 5j
k = 7j

print(z, k)

Boolean Literal
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7

print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)

Variable
● Python Variable is containers which store values.
● Python is not “statically typed”.
● We do not need to declare variables before using them or declare their
type.
● A variable is created the moment we first assign a value to it.
● A Python variable is a name given to a memory location.
● It is the basic unit of storage in a program.

Rules for creating variables in Python:

● A variable name must start with a letter or the underscore character.


● A variable name cannot start with a number.
● A variable name can only contain alpha-numeric characters and

18
underscores(A-z, 0-9, and _ ).
● Variable names are case-sensitive (name, Name and NAME are
three differentvariables).
● The reserved words(keywords) cannot be used naming the variable.

Example
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type and can even
change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

String variables can be declared either by using single or double quotes:


Example
x = "John"
# is the same as
x = 'John'

Assign Value to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

And you can assign the same value to multiple variables in one line:
Example

19
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example
x = "awesome"
print("Python is " + x)

You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)

For numbers, the + character works as a mathematical operator:


Example
x=5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give you an error:
Example
x=5
y = "John"
print(x + y)

Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example

20
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()

If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.
Example
Create a variable inside a function, with the same name as the global
variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)

Global Keyword
A global keyword is a keyword that allows a user to modify a variable outside
the current scope. It is used to create global variables in Python from a non-
global scope, i.e. inside a function. Global keyword is used inside a function
only when we want to do assignments or when we want to change a variable.
Global is not needed for printing and accessing.

Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Example

21
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Data Types
Variables can hold values of different data types. Python is a dynamically typed language
hence we need not define the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function which returns the type of the variable passed.

Example
>>a=10
>>print(type(a))

A variable can hold different types of


values. For example, a person's name must
be stored as a string whereas its id must be
stored as an integer.

Python provides various standard data


types that define the storage method on
each of them. The data types defined in
Python are given below.

22
Example:
a=10
b=20.5
c=1+3j
d=True
e={2,4,5}

f={1:'x',2:'z'}
g=[1,'4.5','ram']
h=(3,4,5)
i='y'
j="Ram"

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
print(type(i))
print(type(j))

Numbers: The number data type in Python is used to store numerical values. It is used to
carry out normal mathematical operations.

Strings: Strings in Python are used to store textual information. They are used to carry out
operations that perform positional ordering among items.

Lists: The list data type is the most generic Python data type. Lists can consist of a collection
of mixed data types, stored by relative positions.

23
Tuples: Python Tuples are one among the immutable Python data types that can store values
of mixed data types. They are basically a list that cannot be changed.

Sets: Sets in Python are a data type that can be considered as an unordered collection of data
without any duplicate items.

Dictionaries: Dictionaries in Python can store multiple objects, but unlike lists, in
dictionaries, the objects are stored by keys and not by positions.

Number Datatype
Python supports 3 types of numeric data.
 int (signed integers like 10, 2, 29, etc.)
 float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
 complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
Example:
x = 8 # int
y = 2.8 # float
z = 1j # complex
# To verify the type of any object in Python, use the type() function:
# Example
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
 implicit type conversion (Automatic Type casting) -------------- no data loss (ex:int
to float) (a=100,b=3,c=a/b print(type(c))
 explicit type conversion -------------- data loss(ex: float to int)
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)

24
print(a)
print(b)
print(c)
print(x.real)
print(x.imag)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.

SOME IMP INBUILT FUNCTIONS Before concept :


Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:

Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))

input function
Input function is used to send the data dynamically by using terminal.
The below program takes the input of any data type
a=input("Enter the input:")
print(a)

If suppose if we give specific data type it will take that type of data only as input.
a=int(input("Enter the input:"))
print(a)

print(type(a))

But the input() default type is string.

Types to print the output


1. Print with the print function
X=10
print(X)

25
2. Print with string formatting %
name="Rama Krishna"
age=29
print("My name is %s and my age is %d"%(name,age))

3. Print with the str.format() method


age=29
print("My name is {} and my age is {}".format(name,age))

name1="Gopal"
print("My name is {name} and my age is {age}".format(name=name1,age=age))

course="Python"
price=2.99 #print this is dollar format
print("My course is {} and the price is ${price:.1f}".format(course,price=price))

4. Print with the ‘f-string’


name="Rama Krishna"
print(f"my name is {name}")

salary=10000
tax=0.2
print(f"my monthly salary is ${salary-tax}")

5. Print to a file or a stream


#printing to a file
with open('result.txt','w') as f:
print("This will retun to a file", file=f)

#printing to a stream
import sys
print("This will return to a stream", file=sys.stderr)

Operators
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
particular programming language. Python provides a variety of operators described as follows.

26
 Arithmetic operators
 Comparison operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes +(addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**).

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value result negative. For example,
if a = 20, b = 10 => a - b = 10

/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b = 10
(Multiplication) => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0 Example: if a=17 b=7 =>b%a =7
here if it is not possible then returns above value.

** (Exponent) It is an exponent operator represented as it calculates the first operand power to


second operand. Print(2**4)=2*2*2*2=16.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division) print(20//10)=2 its not gives any decimal value.

Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As

= x=5 x=5

27
+= x += 3 x=x+3

-= x -= 3 x=x–3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
boolean true or false accordingly. The comparison operators are described in the following
table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition
becomes true.

>= If the first operand is greater than or equal to the second operand, then the condition
becomes true.

> If the first operand is greater than the second operand, then the condition becomes
true.

< If the first operand is less than the second operand, then the condition becomes true.

Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements x < 5 or x < 4

28
is true

not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)

Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands.
Example:
if a = 7;
b = 6;
then, binary (a) = 0111
binary (b) = 0011

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will
be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit
will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
bit will be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in the right
operand.

>> (right The left operand is moved right by the number of bits present in the right operand.
shift)

Membership Operators
Membership operators are used to test if a sequence is presented in an object:

29
Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

Example:
x = ["apple", "banana"]

print("banana" in x)
# returns True because a sequence with the value "banana" is in the list

Example:
x = ["apple", "banana"]

print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list

Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not x is not y


the same object

Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x

print(x is not z)
# returns False because z is the same object as x

print(x is not y)
# returns True because x is not the same object as y, even if they have the same content

print(x != y)

30
# to demonstrate the difference betweeen "is not" and "!=": this comparison returns False
because x is equal to y.

Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x

print(x is y)
# returns False because x is not the same object as y, even if they have the same content

print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because
x is equal to y

Control Statements
Conditional statements
 If
 If-else
 If-elif-else
 Nested-if
Looping statements
 for
 while
 Nested loops
Transfer Statements
 Break
 Continue
 Pass
 Return

31
Conditional statements
In programming languages, most of the time in large projects we have to controlthe flow of
execution of our program and we want to execute some set of statements only if the given
condition is satisfied, and a different set of statements when it’s not satisfied.
Conditional statements are also known as decision-making statements. We needto use these
conditional statements to execute the specific block of code if the given condition is true or
false.

In Python we can achieve decision making by using the following statements:


 If
 If-else
 If-elif-else
 Nested-if
If
Python if statement is one of the most commonly used conditional statements inprogramming
languages. It decides whether certain statements need to be executed or not.
It checks for a given condition, if the condition is true, then the set of codepresent inside the ”
if ” block will be executed otherwise not.
Syntax:
if (EXPRESSION == TRUE):
Block of code

32
Here, the condition will be evaluated to a Boolean expression (true or false).

If the condition is true, then the statement or program present inside the ” if ” block will be
executed and if the condition is false, then the statements or program present insidethe “else”
block will be executed.

Note :In every programming language only "0" is the false value. Remaining integer
values( either +ve or -ve) are all true values.

Example:
if(1):
print("Hi")
print("Hello")

Example:
age=int(input("Enter your age:"))
if(age>18):
print("your are Major")

If-else
The statement itself says if a given condition is true then execute the statementspresent inside
the “if block” and if the condition is false then execute the “else” block.
The “else” block will execute only when the condition becomes false. It is theblock where you
will perform some actions when the condition is not true.
Syntax :
if (EXPRESSION == TRUE):
Statement (Body of the block)
else:
Statement (Body of the block)
Example:
if(0):

33
print("Hi")
else:
print("Hello")

Example:
age=int(input("Enter your age:"))
if(age>18):
print("You are major")
else:
print("You are minor")

If-elif-else
In Python, we have one more conditional statement called “elif” statements.
“elif” statement is used to check multiple conditions only if the given condition is false.
It’s similar to an “if-else” statement and the only difference is that in “else” we willnot check
the condition but in “elif” we will check the condition.
“elif” statements are similar to “if-else” statements but “elif” statements evaluate multiple
conditions.

Syntax:
if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be execute when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false

34
WAP to find biggest among 3 numbers :
Example:
a,b,c=input("Enter a,b,c value:").split()
if((a>b)&(a>c)):
print("a is big")
elif(b>c):
print("b is big")
else:
print("c is big")

Nested if-else
Nested “if-else” statements mean that an “if” statement or “if-else” statement is present inside
another if or if-else block.

Python provides this feature as well, this in turn will help us to check multiple conditions in a
given program.

An “if” statement is present inside another “if” statement which is present inside another “if”
statements and so on.

Syntax:
if boolean_expression:
if Boolean_expression:
statement(s)
else:
statement(s)
else:
statement(s)

Example:
a,b,c=input("Enter a b c value:").split()
if(a>b):
if(a>c):
print("a is big")
else:
print("c is big")
else:
if(b>c):
print("b is big")

35
else:
print("c is big")

Example:
year=int(input("Enter the year:"))
if(year%100==0):
if(year%400==0):
print("Leap Year")
else:
print("It is not Leap Year")
else:
if(year%4==0):
print("Leap Year")
else:
print("It is not Leap Year")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example:
if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:
Example:

a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.


You can also have multiple else statements on the same line:
Example:
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

36
Looping statements
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.

Name of the loop Loop Type & Description


While loop Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.

For loop This type of loop executes a code block multiple times andabbreviates
the code that manages the loop variable.
Nested loops We can iterate a loop inside another loop.

while
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
while condition:
statements(s)
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any non-zero value. The loop iterates while the condition
is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Example: Print 1 to 5 numbers
i=1
while(i<=5):
print(i)
i+=1

Example: Print Even numbers


i=0
while(i<25):
if(i%2==0):
print(i)
i+=1

Example: Print divided by numbers


i=10
count=0
while(i>0):
if(i%2==0):

37
print(i)
count+=1
i=i-1
print("The count is:",count)

Example: print difference numbers


i=100
count=0
while(i>0):
if(i%2==0):
print(i)
i=i-1
count+=1
print(count)

Nested while loop


Defining while-loop inside another while loop.
syntax :
while expression:
while expression:
statement(s)
statement(s)
Example:
i=1
while(i<=3):
print(i)
j=1
while(j<=3):
print(j)
j=j+1
i=i+1

for
It has the ability to iterate over the items of any sequence, such as a list or a string

Syntax:
for iterating_var in sequence:
statement(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var.

38
Next, the statements block is executed. Each item in the list is assigned to iterating_var,and
the statement(s) block is executed until the entire sequence is exhausted.

Example:
fruits=["apple", "banana", "cherry"]
for x in fruits:
print(x)

Example: Looping through string


for x in "fruits":
print(x)

Range() Function:
To loop through a set of code a specified number of times, we can use the range() function,
range() function returns a sequence of numbers, starting from 0 by default, and increment by
1(by default) and ends with specified number.
Parameters:
Start: Optional. An integer number specifying at which position to start. Default is 0.
Stop: Required. An integer number specifying at which position to stop (not excluded).
Step: Optional. An integer number specifying the incrementation. Default is 1.

Example:
for x in range(6):
print(x)

Example: sum of first n numbers.


sum=0
for x in range(0,7):
sum=sum+x
print(sum)

Example: sum of first n natural numbers without for loop


n=5
sum=n*(n+1)/2
print(sum)

Example: Factorial of given number


fact=1

39
for x in range(1,5):
fact=fact*x
print(fact)

Example: WAP to print natural numbers.


for x in range(0,10,2): //(start,stop,step)
print(x)

Nested for loop:


Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.

Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statement(s)
statement(s)

Example:
for i in range(1,101):
for j in range(1,11):
print(i*j,end=" ")
print()

Example:
for i in range(2,3):
for j in range(1,11):
print(i,"*",j,"=",i*j)
print()
Transfer Statements
Break
The break statement is used to break out of a loop. It is used inside for and while loops to
alter the normal behavior. the break will end the loop it is in and controlflows to the
statement immediately below the loop.

Continue
The continue keyword is used to end the current iteration in a for loop or a while loop
and continues to the next iteration.
The continue statement is a temporary break in a loop.

Pass
The pass statement in Python is used when a statement is required syntactically but you
do not want run any code to execute.

40
The pass statement is a null operation; nothing happens when it executes.

The pass is also useful in places where your code will eventually go, but has not been
written yet.

Example: Using Break


fruits=["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x=="banana":
break

Example: Using continue


fruits=["apple", "banana", "cherry"]
for x in fruits:
if x=="banana":
continue
print(x)

Example: Using pass


if True:
pass

Python List

A list in Python is used to store the sequence of various types of data.


Python lists are mutable type its mean we can modify its element after it created.
A list can be defined as a collection of values or items of different types.
The items in the list are separated with the comma (,) and enclosed with the square
brackets []

Create a List:
L1=[]
L2 = ["John", 102, 'USA',10,"20"]
L3 = [1, 2, 3, 4, 5, 6]
L4=list([1,"Ram"]) #in this case we can use [],{}() ---inside brackets
print(type(L1))

41
print(type(L2))
print(type(L3))
print(L1)

#Creation of list Dynamically by using eval() function.


L1=eval(input("Enter the L1 Elements:")) #input ------ [10,20,30] ---- brackets compulsary
print(type(L1))
print(L1)

#Creation of list by using range() function.


L5=list(range(0,11))
print(type(L5))
print(L5)

#List can hold any complex data type like dict,tuple, etc
L1=[40,{"name":"Ram"},list((10,20,30))]
print(type(L1))
print(L1)

#Creation of a list by using split()


a="Welcome to python world"
print(type(a))
L1=a.split()
print(type(L1))
print(L1)

a="Welc-ome to pyt-hon wo-rld"


L2=a.split('-') # based up on('-') by default space
print(L2)

Characteristics of Lists :
The list has the following characteristics:
 The lists are ordered.
 The element of the list can access by index.
 The lists are the mutable type.
 A list can store the number of various elements in [].
 Allow Duplicate values.

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and soon.

42
We can get the sub-list of the list using the following
syntax:
list_varible(start:stop:step)
 The start denotes the starting index position of the list.
 The stop denotes the last index position of the list.
 The step is used to skip the nth element within a start:stop

Consider the following example:


list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])

# Slicing the elements


print(list[0:6])

# By default the index value is 0 so its starts from the 0th element and gofor index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])

43
Unlike other languages, Python provides the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (rightmost) of the list has the
index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.

Let's have a look at the following example where we will use negative indexing to access the
elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])

As we discussed above, we can get an element by using negative indexing. In the above
code, the first print statement returned the rightmost element of the list. The second print
statement returned the sub-list, and so on.

Updating List values


Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.
Python also provides append() and insert() methods, which can be used to add values to
the list.
Consider the following example to update the values inside the list
list = [1, 2, 3, 4, 5, 6]
print(list)

# It will assign value to the value to the second index


list[2] = 10
print(list)

# Adding multiple-element list[1:3] = [89, 78]


print(list)

# It will add value at the end of the list


list[-1] = 25
print(list)

44
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.

list = ["John", "David", "James", "Jonathan"]


for i in list:
print(i)

#Visiting all the elements in a sequence is called Traversing

Using While:
list = ["John", "David", "James", "Jonathan"]
i=0
while i<len(list):
print(list[i])
i=i+1

List Methods
Method Description
append() Adds an element at the end of the list
extend() Add the elements of a list to the end of the current list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified
positionremove() Removes the first item with the
specified valuereverse() Reverses the order of the list
sort() Sorts the list

Adding elements to the list:


append():
Python provides append() function which is used to add an element to the list. However,the
append() function can only add value to the end of the list.

45
Example:
list=[1,2,3]
list.append(4) #To add as sub list use list.append([4])
print(list)

insert():
Inserts an element at the specified position.

Syntax:
list.insert(position, element)

Note: Position mentioned should be within the range of List, as in this case between 0
and 4, else wise would throw IndexError.

Example:
l1=[1,2,3,4,2,5,6,7,2,8,9,10]
l1.insert(3,24)
print(l1)
Output:
[1,2,3,24,4,2,5,6,7,2,8,9,10]

count():
Calculates total occurrence of a given element of List.
Syntax: List.count(element)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output: 4

index():
Returns the index of the first occurrence. The start and End index are not necessary
parameters.
Syntax:
List.index(element,start,end)

Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]

46
print(List.index(2))
Output:
1

Removing elements from the list


Python provides the remove() function which is used to remove the element from the list.
Consider the following example to understand this concept.
Example:
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")

list.remove(2)
print("\nprinting the list after the removal of second element...")

for i in list:
print(i,end=" ")

Example: It is used to delete by index numbering


l1=[1,2,3,4,5,6,7,8,9,10]
l1.remove(l1[2])
print(l1)

pop():
The index is not a necessary parameter, if not mentioned takes the last
index.Syntax:
list.pop([index])

Note: Index must be in range of the List, elsewise IndexErrors occurs.

Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())
Output:
2.5

extend():
Adds contents to List2 to the end of List1.

Example:
list=[1,2,3]

47
list.extend([4]) #we cannot process this extend as sublist
print(list)

Example:
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]

# Add List2 to List1


List1.extend(List2)
print(List1)
# now Add List1 to List2
List2.extend(List1)
print(List2)

Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]

sum():
Calculates the sum of all the elements of the List.

Syntax:
sum(List)
Example:
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15

Length():
Calculates the total length of the List.
Syntax: len(list_name)
Example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(Li
st))Output:
10

48
Example:
list=[1,3,2,5,2,7,8]
for i in range(len(list)):
if list[i]==2:
print(i)

min():
Calculates minimum of all the elements of List.
Example:
List = [8, 2, 3, 5,8,9]
print(min(List))

clear:
It is used to clear the list.
Example:
List = [8, 2, 3, 5,8,9]
List.clear()
print(List)

copy:
It is used to copy the list
Example:
List = [8, 2, 3, 5,8,9]
print(List)
b=List.copy()
List.append(10)
print(List)
print(b)

To Delete one or more elements, i.e. remove an element, many built-in functions can
be used, such as pop() & remove() and keywords such as del.

Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop
(0))Output:
2.3

del():
Element to be deleted is mentioned using list name and index.

49
Syntax:
del list.[index]
Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)

Output:
[4.445, 3, 5.33, 1.054, 2.5]

remove():
Element to be deleted is mentioned using list name and element.
Syntax:
list.remove(elem
ent)

Example:
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)

Outpu
t:
[2.3, 4.445, 5.33, 1.054, 2.5]

Reverse():
It is used to reverse the list.
Example:
List = [8, 2, 3, 5,8,9]
List.reverse()
print(List)

sort(): It is used to sort the order.


Ascending to descending order.
Example:
list = [8, 2, 3, 5,8,9]
list.sort()
print(list)

Descending to Ascending order.

50
Example:
list = [8, 2, 3, 5,8,9]
list.sort(reverse=True)
print(list)

Example:
sample=["Even" if a%2==0 else "Odd" for a in range(10)]
print(sample)

Example:
NewList=[]
for i in["Apple","Banana","Mango"]:
if "a" in i:
NewList.append(i)

print(NewList)

Example:
List=["Apple","Banana","Kiwi"]
NewList=[x for x in List if "a" in x]
print(NewList)

Concatenate of Lists:
Joining of list is known as Concatenation of lists.
+ Operator is used for concatenate list.
Example:
L1=[20,30,40,50,60]
S1=['Ram','Priyanka',40,50]
C1=L1+S1
print(C1)

Repetition of Lists:
It will repeat the list based on specified number of times.
* operator is used to repeat list.
Example:
L1=[10,20,40]
Rep=L1*5
print(Rep)

51
project=1
SUM GAME
#sum game with random numbers
import os
from random import randint
count=0
while True:
os.system("cls") #To clear the screen
a=randint(1,50)
b=randint(1,50)
c=a+b
question=randint(1,3)
print("Type your answer: ")

match question:
case 1:
print(f"? + {b}= {c}")
correct_answer=a

case 2:
print(f"{a} + ?= {c}")
correct_answer=b

case 3:
print(f"{a} + {b}= ?")
correct_answer=c

while True:
try:
your_answer=int(input())
break
except:
print("Please Enter the numbers only")

if your_answer==correct_answer:
print("Correct. Press Enter to continue...")
count=count+1
input() #pause the program wait for Enter.
else:
print("Not Correct.")
break

print(f"You have answered {count} questions Correctly")

52
project=2

MATH GAME

from random import randint


import os
import time

correct=0
wrong=0
level=int(input("Choose Difficulty Level(1= Easy, 2=Medium, 3=Hard):"))
Difficulty_level="None"
if level==1:
Difficulty_level="Easy"
elif level==2:
Difficulty_level="Medium"
elif level==3:
Difficulty_level="Hard"

# store starting time


begin = time.time()

for i in range(10):
os.system("cls") #To clear the screen
a=randint(1,50)
b=randint(1,50)
c=a+b
question=randint(1,3)
print(f"Difficulty Level :{Difficulty_level} | Questions: {i}/10 | Correct
Answers: {correct} | Wrong Answers: {wrong}")
print("Type your answer: ")

match question:
case 1:
print(f"? + {b}= {c}")
correct_answer=a

53
case 2:
print(f"{a} + ?= {c}")
correct_answer=b

case 3:
print(f"{a} + {b}= ?")
correct_answer=c

while True:
try:
your_answer=int(input())
break
except:
print("Please Enter the numbers only")

if your_answer==correct_answer:
print("Correct. Press Enter to continue...")
correct=correct+1
input() #pause the program wait for Enter.
else:
print("Not Correct.")
wrong=wrong+1

time.sleep(1)
# store end time
end = time.time()

if correct==10:
grade="A"
elif correct in range(7,10):
grade="B"
elif correct in range(5,7):
grade="C"
else:
grade="D"

54
print("Your Test Result:")
print(f" > Scores: {correct}/10 ({correct/10*100} %)")
print(f" > Time to complete: {end-begin} seconds")
print(f" > Grade : {grade}")

55
conclusion:

The Python programming language stands out as one of the most


essential tools in the field of computer engineering, thanks to its simplicity,
readability, and powerful capabilities. Throughout the course of this project, we
delved into the foundational aspects of Python, including variables, data types,
control flow statements, functions, and object-oriented programming. By
implementing various concepts such as data manipulation, user-defined
functions, error handling, and list operations, we were able to develop practical
solutions and interactive programs that reflect real-world applications.

One of the key takeaways from this project is the flexibility Python offers
across multiple domains such as web development, automation, artificial
intelligence, data science, and software engineering. We also gained experience
in using Python tools like IDEs (e.g., VS Code), packages (like random and
time), and best practices such as modular programming and code readability.
The development of small games and logic-based applications enhanced our
problem-solving skills and reinforced our understanding of computational logic.

Moreover, we explored Python's cross-platform compatibility and its open-


source nature, which makes it accessible for diverse development environments.
Its vast standard library and third-party support provide developers with the
ability to build robust, scalable, and efficient applications with minimal effort.

In conclusion, this project not only strengthened our grasp of Python


programming but also laid a strong foundation for pursuing advanced fields
within computer engineering. The knowledge and experience gained will
undoubtedly prove valuable in future academic research, software development
projects, and professional career paths involving modern technologies.

56

You might also like