Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Notes for Student-1

The document provides an introduction to Python programming, highlighting its features, syntax, and various applications across different domains. It covers Python's keywords, identifiers, and the rules for naming them, along with examples of basic programming constructs. Additionally, it emphasizes Python's versatility and community support, making it a popular choice for developers.

Uploaded by

audioarena116
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Notes for Student-1

The document provides an introduction to Python programming, highlighting its features, syntax, and various applications across different domains. It covers Python's keywords, identifiers, and the rules for naming them, along with examples of basic programming constructs. Additionally, it emphasizes Python's versatility and community support, making it a popular choice for developers.

Uploaded by

audioarena116
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Python Programming

Prof. K.D.Dongare
Python Programming

Introduction to Python

• Python is a general-purpose, dynamic, high-level, and interpreted


programming language.

• Python supports multiple programming patterns, including object-oriented,


imperative, and functional or procedural programming styles.
• It was created by Guido van Rossum during 1985- 1990. Python source code
is available under the GNU General Public License (GPL).
• Python has many web-based assets, open-source projects, and a vibrant
community.
• Python is an open-source, cost-free programming language. It is utilized in
several sectors and disciplines as a result.

❖ Python Basic Syntax


There is no use of curly braces or semicolon in Python programming language.

def func():
statement 1
statement 2
…………………
…………………
statement N

Prof. K.D.Dongare
Python Programming

✓ In the above example, the statements that are the same level to the right belong to
the function. Generally, we can use four whitespaces to define indentation.

❖ Python Features
• Readability: Python's syntax emphasizes code readability and uses indentation
to define code blocks, making it easy to write and understand code.
• Versatility: Python can be used for various applications, including web
development, data analysis, scientific computing, artificial intelligence,
automation, and more.
• Dynamic Typing: Python uses dynamic typing, allowing variables to change
types on the fly, which enhances flexibility and reduces the need for explicit type
declarations.
• Interpreted Nature: Python is an interpreted language, allowing you to execute
code directly without needing a compilation step, making development and
debugging quicker.
• Large Standard Library: Python comes with a comprehensive standard library
that provides modules and functions for a wide range of tasks, reducing the need
to reinvent the wheel.
• Cross-Platform: Python is cross-platform, meaning code written on one
platform can be easily executed on other platforms without significant
modifications.
• Object-Oriented: Python supports object-oriented programming, allowing you
to structure code using classes and objects for better organization and reusability.
• Extensive Third-Party Libraries: Python has a vast ecosystem of third- party
libraries and frameworks that simplify complex tasks and accelerate development.
• Community and Support: Python has a large and active community of
developers who contribute to its growth, provide support, and create various
resources for learning.

• Open Source: Python is an open-source language, meaning its source code is


freely available to the public, promoting collaboration and enabling
customization according to specific needs.

❖ Python Application
Prof. K.D.Dongare
Python Programming

1) Web Applications

• We can use Python to develop web


applications.
• It provides libraries to handle internet
protocols such as HTML and
XML, JSON, Email processing, request, beautifulSoup,
Feedparser, etc.

2) Desktop GUI Applications

• The GUI stands for the Graphical User


Interface, which provides a smooth
interaction to any application.

3) Console-based Application

• Console-based applications run from the command-line or shell. These


applications are computer program which are used commands to execute.
• This kind of application was more popular in the old generation of computers.
Python can develop this kind of application very effectively.

4) Software Development

• Python is useful for the software development process.


• It works as a support language and can be used to build control and
management, testing, etc.

5) Scientific and Numeric

• This is the era of Artificial intelligence where the machine can perform the
task the same as the human.
• Python language is the most suitable language for Artificial intelligence or
machine learning.
• It consists of many scientific and mathematical libraries, which makes easy
to solve complex calculations.

6) Business Applications

Prof. K.D.Dongare
Python Programming

• Business Applications differ from standard applications. E-commerce and


ERP are an example of a business application.
• This kind of application requires extensively, scalability and readability, and
Python provides all these features.

7) Audio or Video-based Applications

• Python is flexible to perform multiple tasks and can be used to create


multimedia applications.
• Some multimedia applications which are made by using Python are
TimPlayer, cplay, etc.

8) 3D CAD Applications

• The CAD (Computer-aided design) is used to design engineering related


architecture.
• It is used to develop the 3D representation of a part of a system.
• Python can create a 3D CAD application by using the following
functionalities.

9) Enterprise Applications

• Python can be used to create applications that can be used within an


Enterprise or an Organization.
• Some real-time applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application

• Python contains many libraries that are used to work with the image.
• The image can be manipulated according to our requirements.

Prof. K.D.Dongare
Python Programming

❖ First Python Program


So before moving on further.. let’s do the most popular ‘Shree Krushna’ tradition .

# Python code for print " Shree Krushna"


# nothing else to type...see how simple is the syntax.
print("Shree Krushna")

Output:

Shree Krushna

Prof. K.D.Dongare
Python Programming

SHREE KRUSHNA ENGINEERING CLASSES

Keywords

• Python keywords are unique words reserved with defined meanings and
functions that we can only apply for those functions. You'll never need to
import any keyword into your program because they're permanently present.
• Python's built-in methods and classes are not the same as the keywords.
Built-in methods and classes are constantly present; however, they are not as
limited in their application as keywords.
• Assigning a particular meaning to Python keywords means you can't use them
for other purposes in our code. You'll get a message of SyntaxError if you
attempt to do the same. If you attempt to assign anything to a built-in method
or type, you will not receive a SyntaxError message; however, it is still not a
smart idea.

❖ List of Python keywords


False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Prof. K.D.Dongare
Python Programming

❖ True, False, None Keyword

• True: This keyword is used to represent a boolean true. If a statement


is true, “True” is printed.
• False: This keyword is used to represent a boolean false. If a statement
is false, “False” is printed.
• None: This is a special constant used to denote a null value or a void.
It’s important to remember, 0, any empty container(e.g. empty list)
does not compute to None.

print( 4 == 4 )
print( 6 > 9 )
print( True or False )

Output:
True

False

True

❖ Operator Keywords: and, or, not, in, is


• Several Python keywords are employed as operators to perform
mathematical operations.
• In many other computer languages, these operators are represented by
characters such as &, |, and!. All of these are keyword operations in Python:

Prof. K.D.Dongare
Python Programming

Mathematical Operations in Other Python


Operations Languages Keyword

AND, 𝖠 && and

OR, 𝗏 || or

NOT, ¬ ! not

CONTAINS, ∈ in

IDENTITY === is

Example:

x = 10
y=3

addition = x + y
comparison = x > y
logical_and = x > 5 and y < 5
assignment = x += y

print("Addition:", addition)
print("Comparison:", comparison)
print("Logical AND:", logical_and)
print("Assignment:", assignment)

Prof. K.D.Dongare
Python Programming

Output:

Addition: 13 Comparison:
True Logical AND: False
SyntaxError: cannot use assignment expressions with subscript

❖ Iteration Keywords – for, while, break, continue

• for: This keyword is used to control flow and for looping.


• while: Has a similar working like “for”, used to control flow and for
looping.
• break: “break” is used to control the flow of the loop. The statement is
used to break out of the loop and passes the control to the statement
following immediately after loop.
• continue: “continue” is also used to control the flow of code. The
keyword skips the current iteration of the loop but does not end the
loop.

Examples:

# Using the "for" loop to iterate through a list


numbers = [1, 2, 3]
for num in numbers:
print(num)
# Using the "while" loop for conditional iteration
count = 0
while count < 3:
print("Count:", count)
count += 1

Prof. K.D.Dongare
Python Programming

Output:
1
2
3

0
1
2

❖ Conditional keywords – if, else, elif

• if : It is a control statement for decision making. Truth expression


forces control to go in “if” statement block.
• else : It is a control statement for decision making. False expression
forces control to go in “else” statement block.
• elif : It is a control statement for decision making. It is short for “else
if“

Examples:

# Checking if a number is positive


number = 10

if number > 0:
print("The number is positive.")

Output:

The number is positive.

Prof. K.D.Dongare
Python Programming

❖ Return Keywords – Return, Yield

• return : This keyword is used to return from the function.


• yield : This keyword is used like return statement but is used to return a
generator.

❖ Exception Handling Keywords - try, except, raise, finally,


and assert
• try: This keyword is designed to handle exceptions and is used in
conjunction with the keyword except to handle problems in the program.
When there is some kind of error, the program inside the "try" block is
verified, but the code in that block is not executed.
• except: As previously stated, this operates in conjunction with "try" to
handle exceptions.
• finally: Whatever the outcome of the "try" section, the "finally" box is
implemented every time.
• raise: The raise keyword could be used to specifically raise an exception.
• assert: This method is used to help in troubleshooting. Often used to
ensure that code is correct. Nothing occurs if an expression is interpreted as
true; however, if it is false, "Assertion Error" is raised. An output with the
error, followed by a comma, can also be printed.

❖ Python Keyword
Python Keywords are some predefined and reserved words in Python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot be
used as an identifier, function, or variable name. All the keywords in Python are written in
lowercase except True and False. There are 35 keywords in python

In Python, there is an inbuilt keyword module that provides an is keyword() function that can
be used to check whether a given string is a valid keyword or not. Furthermore, we can check
the name of the keywords in Python by using the kwlist attribute of the keyword module.

Rules for Keywords in Python


• Python keywords cannot be used as identifiers.
• All the keywords in Python should be in lowercase except True and False.

Prof.K.D.Dongare
Python Programming

List of Python Keywords


Keywords Description

and This is a logical operator which returns true if both the operands are true else returns false.

or This is also a logical operator which returns true if anyone operand is true else returns false.

not This is again a logical operator it returns True if the operand is false else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif statement is executed if the previous
elif
conditions were not true.

Else is used with if and elif conditional statements. The else block is executed if the given condition
else
is not true.

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

assert This function is used for debugging purposes. Usually used to check the correctness of code

class It helps us to define a class.

Prof.K.D.Dongare
Python Programming

Keywords Description

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be executed no matter if there is an
finally
exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

in It’s used to check whether a value is present in a list, range, tuple, etc.

is This is used to check if the two variables are equal or not.

This is a special constant used to denote a null value or avoid. It’s important to remember, 0, any
none
empty container(e.g empty list) do not compute to None

nonlocal It’s declared a non-local variable.

raise This raises an exception.

yield It ends a function and returns a generator.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

Prof.K.D.Dongare
Python Programming

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.
or
Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.
Sometimes variable and identifier are often misunderstood as same but they are not. Well for
clarity, let’s see what is a variable?

What is Variable
A variable, as the name indicates is something whose value is changeable over time. In fact a
variable is a memory location where a value can be stored. Later we can retrieve the value to
use. But for doing it we need to give a nickname to that memory location so that we can refer
to it. That’s identifier, the nickname.

Rules for identifier


There are some rules for writing Identifiers. But first you must know Python is case sensitive.
That means Name and name are two different identifiers in Python. Here are some rules for
writing Identifiers in python

.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).

Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1

Prof.K.D.Dongare
Python Programming

SHREE KRUSHNA ENGINEERING CLASSES

Variable

• Variable is a name that is used to refer to memory location. Python variable


is also known as an identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a
infer language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but they have
to begin with a letter or an underscore.

Example:

Here we have stored “Krushna” in a var which is variable, and when we call its
name the stored information will get printed.

Var = “Krushna”
print(Var)

Output:

Krushna

Note:
• The value stored in a variable can be changed during program
execution.
• A Variables in Python is only a name given to a memory location, all the
operations done on the variable effects that memory location.

Prof.K.D.Dongare
Python Programming

❖ Rules for Python variables

➢ A Python variable name must start with a letter or the underscore


character.
➢ A Python variable name cannot start with a number.
➢ A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
➢ Variable in Python names are case-sensitive (name, Name, and NAME are
three different variables).
➢ The reserved words(keywords) in Python cannot be used to name the
variable in Python.

❖ Declaring Variable and Assigning Values


➢ Python does not bind us to declare a variable before using it in the
application. It allows us to create a variable at the required time.
➢ We don't need to declare explicitly variable in Python. When we assign any
value to the variable, that variable is declared automatically.
➢ The equal (=) operator is used to assign value to a variable.

Example:

# declaring the var


Number = 100

# display
print( Number)

Output:

100

Prof.K.D.Dongare
Python Programming

❖ Types of Variable
There are two types of variables in Python - Local variable and Global variable. Let's
understand the following variables.

◆ Local Variable

Local variables are the variables that declared inside the function and have
scope within the function.

Example:
# This function uses global variables def
f():
s = "Krushna"
print(s)

Output:

Krushna

◆ Global Variables
Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.

Example:

# This function has a variable with name same as s.


def f():
print(s)
# Global scope
s = "I love Krushna "
f()

Prof.K.D.Dongare
Python Programming

Output:

I love Krushna

❖ Delete a variable
We can delete the variable using the del keyword. The syntax is given
below.

Syntax -

del <variable_name>

❖ How does + operator work with variables?

⚫ The Python plus operator + provides a convenient way to add a value


if it is a number and concatenate if it is a string.
⚫ If a variable is already created it assigns the new value back to the
same variable.

Example:

a = 10
b = 20
print(a+b)

a = "Shree "
Output:
b = "Krushna"
30
print(a+b)
ShreeKrushna

Prof. K.D.Dongare
Python Programming

SHREE KRUSHNA ENGG. CLASSES

Data Types

• Every value has a datatype, and variables can hold values. Python is a
powerfully composed language; consequently, we don't have to
characterize the sort of variable while announcing it.
• The interpreter binds the value implicitly to its type.
a=5

We did not specify the type of the variable a, which has the value five from an
integer. The Python interpreter will automatically interpret the variable as an
integer.

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Prof. K.D.Dongare
Python Programming

Print the data type of the variable x:


x=5
print(type(x))

x = "Hello World"

#display x:
print(x)

#display the data type of x:


print(type(x))

Output
Hello World
<class 'str'>

x = 1 # 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))

Prof. K.D.Dongare
Python Programming

x = 20

#display x:
print(x)

#display the data type of x:


print(type(x))

Output=
20
<class 'int'>

x = list(("apple", "banana", "cherry"))

#display x:
print(x)

#display the data type of x:


print(type(x))

Output
['apple', 'banana', 'cherry']
<class 'list'>

Prof. K.D.Dongare
Python Programming

❖ Standard data types


➢ A variable can contain a variety of values. On the other hand, a person's
id must be stored as an integer, while their name must be stored as a
string.
➢ The storage method for each of the standard data types that Python
provides is specified by Python.

The following is a list of the Python-defined data types.

◆ Numbers
◆ Sequence Type
◆ Boolean
◆ Set
◆ Dictionary

Prof. K.D.Dongare
Python Programming

❖ Numbers
• Numeric values are stored in numbers. The whole number, float, and
complex qualities have a place with a Python Numbers datatype.
• Python offers the type() function to determine a variable's data type. The
instance () capability is utilized to check whether an item has a place with
a specific class.

Python supports three kinds of numerical data.

➢ Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, -
150, and so on. An integer can be any length you want in Python. Its worth
has a place with int.
➢ Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
➢ Complex: An intricate number contains an arranged pair, i.e., x + iy, where
x and y signify the genuine and non-existent parts separately. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.

Example:

age = 25
height = 5.9

# Arithmetic operations
total = age + height
difference = age - height
product = age * height
quotient = age / height

# Displaying the results


print("Total:", total)
print("Difference:", difference)

Prof. K.D.Dongare
Python Programming

Output:

Total: 30.9
Difference: 19.1
Product: 147.5
Quotient: 4.23728813559322

❖ Dictionary
• A dictionary is a key-value pair set arranged in any order. It stores a specific
value for each key, like an associative array or a hash table.
• Value is any Python object, while the key can hold any primitive data type.
• The comma (,) and the curly braces are used to separate the items in the
dictionary.

Example:

student = {
"name": "Alice",
"major": "Computer Science"
}
# Accessing dictionary values print("Name:",
student["name"])
print("Major:", student["major"])

Output:

Name: Alice
Major: Computer Science

Prof. K.D.Dongare
Python Programming

❖ Boolean
• True and False are the two default values for the Boolean type. These
qualities are utilized to decide the given assertion valid or misleading.
• The class book indicates this. False can be represented by the 0 or the letter
"F," while true can be represented by any value that is not Zero.

Example:

is_sunny = True
is_raining = False

print(is_sunny)
print(is_raining)

Output:

True
False

❖ Set
• The data type's unordered collection is Python Set. It is alterable, mutable(can
change after creation), and has remarkable components.
• The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces
and separated by a comma to create the set or the built-in function set() is
used to create the set.
• It can contain different kinds of values.

Prof. K.D.Dongare
Python Programming

Example:

# Creating a set
fruits = {"apple", "banana", "orange"}

# Adding an element to the set fruits.add("grape")


# Removing an element from the set
fruits.remove("banana")
# Checking membership if
"apple" in fruits:
print("I have an apple!")
# Iterating through the set for
fruit in fruits:

Output:

I have an apple!
grape
orange
apple

Prof. K.D.Dongare
Python Programming

❖ Sequence Type
➢ String

• The sequence of characters in the quotation marks can be used to


describe the string. A string can be defined in Python using single, double,
or triple quotes.
• String dealing with Python is a direct undertaking since Python gives
worked-in capabilities and administrators to perform tasks in the string.
• When dealing with strings, the operation "hello"+" python" returns "hello
python," and the operator + is used to combine two strings.

➢ List

• Lists in Python are like arrays in C, but lists can contain data of different
types. The things put away in the rundown are isolated with a comma (,)
and encased inside square sections [].
• To gain access to the list's data, we can use slice [:] operators. Like how
they worked with strings, the list is handled by the concatenation
operator (+) and the repetition operator (*).

➢ Tuple

• In many ways, a tuple is like a list. Tuples, like lists, also contain a
collection of items from various data types. A parenthetical space ()
separates the tuple's components from one another.
• Because we cannot alter the size or value of the items in a tuple, it is a
read-only data structure.

Prof. K.D.Dongare
Python Programming

CH-1 INTRODUCTION AND SYNTAX OF PYTHON PROGRAM (08 MARKS)


2 Marks
1. Explain numeric data types in python (CO1).
2. Differentiate between interactive mode and script mode of python(CO1).
3. List different Object Oriented Features supported by python(CO1).
4. Describe Python Interpreter (CO1).
5. Enlist applications for python programming.(CO1)

4 Marks
1. Explain any 4 features of python programming(CO1)
2. Write steps to install python and to run python code. (CO1)
3. List and Explain different data types used in python(CO1)
4. Describe the role of indentation in python. (CO1)
5. Define the following terms: (CO1)
i. Identifier
ii. Literal
iii. Keyword
iv. Variable

Prof. K.D.Dongare

You might also like