Python Unit - I
Python Unit - I
UNIT - I
Python
Python is a high-level, general-purpose and a very popular programming language. It
was created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation. It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code. Python is a programming
language that lets you work quickly and integrate systems more efficiently.
Python programming language is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry. Python Programming
Language is very well suited for Beginners, also for experienced programmers with other
programming languages like C++ and Java.
Python is currently the most widely used multi-purpose, high-level programming
language.
Python allows programming in Object-Oriented and Procedural paradigms.
Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language,
makes them readable all the time.
Python language is being used by almost all tech-giant companies like – Google,
Amazon, Facebook, Instagram, Dropbox, Uber… etc.
The biggest strength of Python is huge collection of standard libraries which can be
used for the following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks
Multimedia
Scientific computing
Text processing
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
Variables
Variables provide a way to associate names with objects.
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
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 = "Kane" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting. \
Example:
Variable Names:
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
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 underscores
(A-z, 0-9, and _)
Variable names are case-sensitive (age, Age and AGE are three different
variables)
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
2myvar = "John"
my-var = "John"
my var = "John"
Camel Case
Each word, except the first, starts with a capital letter
Pascal Case
Each word starts with a capital letter
Snake Case
Each word is separated by an underscore character
x = y = z = "Orange"
print(x)
print(y)
print(z)
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:
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
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:
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside a function.
Example:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python Files
A Python program, sometimes called a script, is a sequence of definitions and
commands. These definitions are evaluated and the commands are executed by the Python
interpreter in something called the shell. Whenever a program execution begins a new shell is
created.
A command, often called a statement, instructs the interpreter to do something.
Python syntax can be executed by writing directly in the Command Line:
Example:
Hello, World!
Execute a Python program by creating a Python file using the .py extension and
running it in command line in the shell.
Example:
C:\Users\CSIT>python myfile.py
Example:
Keywords
keywords are special words that are reserved by the language and have specific
meanings. They cannot be used as variable names or function names because they are used to
indicate specific language constructs.
Here are a few key points about Python keywords:
List of keywords: Python has a predefined list of keywords that cannot be used as
variable or function names. These include words like if, else, for, while, def, class, try,
except, True, False, and None.
Specific meanings: Each keyword has a specific meaning in Python and is used to
indicate a particular language construct. For example, the if keyword is used to create
conditional statements, the def keyword is used to define functions, and the class keyword is
used to define classes.
Case-sensitive: Python keywords are case-sensitive, meaning that if and If are
considered two different keywords.
Cannot be overridden: Keywords cannot be overridden, meaning that you cannot
redefine the meaning of a keyword. This ensures that keywords always have the same
meaning in Python and makes the language more predictable.
Example:
// Keyword – if statement
x=6
if x > 5:
print("x is greater than 5")
// Keyword – for loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
// Keyword – function
def add(a, b):
return a + b
result = add(3, 4)
print(result) # output: 7
Keywords Scope
Some keywords are used to indicate the scope of variables and objects.
The global keyword in Python is used to indicate that a variable is a global variable,
rather than a local variable.
When a variable is defined inside a function or a class, it is considered a local variable
and can only be accessed within that function or class. If a variable is defined outside of any
function or class, it is considered a global variable and can be accessed from anywhere in the
code.
The global keyword is used to specify that a variable is a global variable, even if it is
defined inside a function or class. This allows you to change the value of a global variable
from within a function or class.
Example:
From the above example, x is a global variable, and the value of x is 5 before the
function my_function is called. Inside the function, the global keyword is used to specify
that the x inside the function is the global x. Then the function increases the value of x by 1
and prints it. After the function call, the value of x is 6, which can be accessed outside of the
function as well.
It's important to be careful when using the global keyword, as it can lead to naming conflicts
and make code harder to understand and maintain. As a general rule, it is recommended to
avoid using global variables whenever possible and use function arguments and return values
to pass data between different parts of the code.
Structure of Python
Python Statements In general, the interpreter reads and executes the statements line by
line 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.
a = 10; b = 20; c = b + a
Line Continuation
Some statements may become very long and may force you to scroll the screen left
and right frequently. It is possible to fit the code in such a way that no need to scroll here
and there. Python allows to write a single statement in multiple lines, also known as line
continuation. Line continuation enhances readability as well.
x = 10
y = 20
z = 30
no_of_teachers = x
no_of_male_students = y
no_of_female_students = z
a= [
[1, 2, 3],
[3, 4, 5],
[5, 6, 7]
]
print(a)
Output:
x= \
1+2\
+5+6\
+ 10
print(x)
Output:
24
Comments in Python
Writing comments in the code are very important and they help in code readability
and also tells more about the code. It helps you to write details against a statement or a
chunk of code. Interpreter ignores the comments and does not count them in commands.
Symbols used for writing comments include Hash (#) or Triple Double Quotation
marks (“““). Hash is used in writing single line comments that do not span multiple lines.
Triple Quotation Marks are used to write multiple line comments. Three triple quotation
marks to start the comment and again three quotation marks to end the comment.
Example:
Datatypes
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 Types : dict
Set Types : set, frozenset
Boolean Type : bool
Binary Types : bytes, bytearray, memoryview
Python provides the type () function to know the data-type of the variable
Text Type
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
Example:
x = "Hello World"
Numeric Types
Python supports three types of numeric data.
int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It
is accurate upto 15 decimal points.
complex - A complex number contains an ordered pair, i.e., x + iy where x and
y denote the real and imaginary parts, respectively. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
Example:
int : x = 20
float : x = 20.5
complex : x = 1j
Sequence Type
List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
Example:
x = ["apple", 1, "cherry"]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items
of a tuple.
Example:
x = ("apple", 1, "cherry")
Range
Create a sequence of numbers.
Example:
x = range(6)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative
array or a hash table where each key stores a specific value. Key can hold any primitive data
type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.
Example:
x = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. True can be represented by any non-zero value or
'T' whereas false can be represented by the 0 or 'F'.
Example:
x = bool(5) or x = bool(0) or x = True
Set
Sets are used to store multiple items in a single variable.
A set is a collection which is both unordered and unindexed.
Sets are written with curly brackets.
Set items are unordered, unchangeable, and do not allow duplicate values.
Example:
x = set(("apple", 1, "cherry", 2))
Frozenset
Freeze the list, and make it unchangeable.
Example:
x = frozenset(("apple", "banana", "cherry"))
ByteArray
The bytearray() function returns a bytearray object.
It can convert objects into bytearray objects, or create empty bytearray object of the
specified size.
Example:
x = bytearray(5)
Bytes
The bytes() function returns a bytes object.
It can convert objects into bytes objects, or create empty bytes object of the specified
size.
The difference between bytes() and bytearray() is that bytes() returns an object that
cannot be modified, and bytearray() returns an object that can be modified.
Example:
x = bytes(5)
Memoryview
The memoryview() function returns a memory view object from a specified object.
Example:
x = memoryview(bytes(5))
Type Conversion
Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming.
Implicit Type Conversion
Explicit Type Conversion
The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents Implicit Type
Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting. When type casting, data loss could happen
if the object is forced to conform to a particular data type.
print (e)
Output:
After converting to integer base 2 :
18
After converting to float :
10010.0
Operators
Operators are special symbols in Python that perform specific operations on one or
more operands (values or variables).
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
+= x += value x=x+3 x += 3
-= x -= value x=x-3 x -= 3
*= x *= value x=x*3 x *= 3
/= x /= value x=x/3 x /= 3
%= x %= value x=x%3 x %= 3
|= x |= value x=x|3 x |= 3
^= x ^= value x=x^3 x ^= 3
!= Not equal x != y x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
Example:
x = ["apple", "banana"]
print("banana" in x) #Returns True
x = ["apple", "banana"]
print("pineapple" not in x) #Returns True
From the example, the input() function is used to prompt the user to enter their
name. The input is assigned to the variable name, and then the print() function is used to
display "Hello, [name]".
To get a numerical input from the user convert the input string to a number using the
appropriate data type function such as int() or float().
Example:
Here the prompt message is "What is your age? (default 20)" and if user does not
provide the input, it will take the default value 20.
The f before the string in the print(f"Your age is {age}") statement is
called an f-string, also known as a "formatted string literal".
The expressions inside the curly braces {} are evaluated at runtime and their values
are included in the resulting string. The expressions can be variables, function calls or any
other valid Python expressions.
It is also more efficient than using the format() method or string concatenation,
since it is evaluated at runtime rather than at compile time.
raw_input()
raw_input() is a legacy function that is present in Python. It reads input from the
user as a string, without evaluating it.
Example:
>>> x = raw_input("Enter a number: ")
Enter a number: 5
>>> print(x)
'5'
The raw_input() function is used to prompt the user to enter a number. The input
is returned as a string, so the variable x is assigned the value '5' (as a string).
Output Statement
The print() function is the most commonly used function for displaying output to
the user. The print() function can take one or more arguments, which are the values to be
printed. The values are separated by spaces and a newline is added at the end of the print
statement by default.
Example:
x=5
y = 10
print("The value of x is", x)
print("The sum of x and y is", x + y)
From above example, the print() function is used to display "The value of x is 5"
and "The sum of x and y is 15"
The print() function allows to print multiple values on the same line by using the
sep parameter:
Example:
print(1, 2, 3, 4, 5, sep=" | ")
Also use the print() function to print values without a newline at the end, by using
the end parameter:
Example:
print("Hello", end=", ")
print("world!")
This will print "Hello, world!" on the same line