0% found this document useful (0 votes)
296 views15 pages

Python - Unit I

This document provides an introduction and overview of the Python programming language. It discusses basics like variables, data types, operators, input/output, and more. Python is described as a popular, general purpose, dynamic, high-level, and interpreted programming language that supports object-oriented programming. It is easy to learn and provides high-level data structures. The document also covers topics like executing Python from the command line, editing Python files, reserved keywords, basic syntax like comments and indentation, and Python's standard data types like numbers, strings, lists, tuples, sets, and dictionaries.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
296 views15 pages

Python - Unit I

This document provides an introduction and overview of the Python programming language. It discusses basics like variables, data types, operators, input/output, and more. Python is described as a popular, general purpose, dynamic, high-level, and interpreted programming language that supports object-oriented programming. It is easy to learn and provides high-level data structures. The document also covers topics like executing Python from the command line, editing Python files, reserved keywords, basic syntax like comments and indentation, and Python's standard data types like numbers, strings, lists, tuples, sets, and dictionaries.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

BASICS OF PYTHON

BASICS : Python – Variables – Executing Python from the Command Line – Editing Python Files –
Python Reserved Words – Basic Syntax-Comments – Standard Data Types – Relational
Operators
– Logical Operators – Bit Wise Operators – Simple Input and Output.

Introduction to Python

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

● web development (server-side),


● software development,
● mathematics,
● System scripting.

Python is a general purpose, dynamic, high-level, and interpreted programming language. It


supports Object Oriented programming approach to develop applications. It is simple and easy
to learn and provides lots of high-level data structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.

Python supports multiple programming pattern, including object-oriented, imperative, and


functional or procedural programming styles.

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 1


Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

Variables

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.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.

Example of Python Variables

Var = "SKACAS"
print(Var)
Output:
SKACAS

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 2


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 underscores (A-
z, 0-9, and _ ).
● Variable names are case-sensitive (name, Name and NAME are three
different variables).
● The reserved words(keywords) cannot be used naming the variable.
Global and Local Python Variables

Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.

Example
def f():
s = "Welcome SKACAS"

print(s)
f()
Output:
Welcome SKACAS
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.
Example :
def f():
print(s)

# Global scope
s = "I love SKACAS"

f()
Output:
I love SKACAS

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 3


Executing Python from the Command Line
Python is a well known high-level programming language. The Python script is basically a file
containing code written in Python. The file containing python script has the extension ‘.py’ or
can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python
script, we need a python interpreter that needs to be downloaded and installed.

Here is a simple python script to print ‘Hello World!’:

print('Hello World!')

To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword
before the file name in the command prompt.
python hello.py
Output:

Editing Python Files

1. Download a CPython interpreter. Press the Download Python 3.6.2 button to save
one of the more updated interpreters to Windows.
2. Open the Win + X menu by pressing the Win key + X hotkey.
3. Select Command Prompt (Admin) to open the CP’s window.
4. Open the folder that includes your Python script in the Command Prompt by
entering ‘Cd’ followed by the path of the file.
5. Next, enter the full path of the CPython interpreter followed by the full location of the
PY file in the Command Prompt, which must include the Python interpreter exe and PY
file title. For example, you might enter something like this: C:Python27python.exe
C:User FolderPY Files SubfolderPy file title.PY
6. Press Enter to open and run the PY script.

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 4


7. Text editors are fine for editing files, but you’ll need a Python interpreter to open
and run the PY scripts. Some interpreters come bundled with IDE Python software.
8. However, CPython, otherwise the reference implementation, is the default
interpreter for the programming language. Use the above steps to open PY scripts
with that interpreter.

Reserved Keywords

Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:

Basic Syntax

Whitespace and indentation

If you’ve been working in other programming languages such as Java, C#, or C/C++, you
know that these languages use semicolons (;) to separate the statements.
However, Python uses whitespace and indentation to construct the code
structure. The following shows a snippet of Python code:
# define main function to print out something
def main():
i=1

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 5


max = 10
while (i < max):
print(i)
i=i+1
# call function main
main()

The meaning of the code isn’t important to you now. Please pay attention to the code
structure instead.

At the end of each line, you don’t see any semicolon to terminate the statement. And the code
uses indentation to format the code.

By using indentation and whitespace to organize the code, Python code gains the following
advantages:

● First, you’ll never miss the beginning or ending code of a block like in other
programming languages such as Java or C#.
● Second, the coding style is essentially uniform. If you have to maintain another
developer’s code, that code looks the same as yours.
● Third, the code is more readable and clear in comparison with other programming
languages.

Comments

The comments are as important as the code because they describe why a piece of code
was written.

When the Python interpreter executes the code, it ignores the comments.

In Python, a single-line comment begins with a hash (#) symbol followed by the comment.
For example:

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 6


# This is a single line comment in Python

Continuation of statements

Python uses a newline character to separate statements. It places each statement on one

line. However, a long statement can span multiple lines by using the backslash (\) character.

The following example illustrates how to use the backslash (\) character to continue a
statement in the second line:

if (a == True) and (b == False) and

\ (c == True):

print("Continuation of statements")

Standard Data Types

A Data Type describes the characteristic of a


variable. Python has six standard Data Types:
● Numbers
● String
● List
● Tuple
● Set
● Dictionary
#1) Numbers
In Numbers, there are mainly 3 types which include Integer, Float, and Complex.
These 3 are defined as a class in Python. In order to find to which class the variable belongs to
you can use type () function.
Example:
a=5

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 7


print(a, "is of type", type(a))
Output: 5 is of type <class ‘int’>
#2) String
A string is an ordered sequence of characters.
We can use single quotes or double quotes to represent strings. Multi-line strings can be
represented using triple quotes, ”’ or “””.
Strings are immutable which means once we declare a string we can’t update the already
declared string.
Example:
Single =
'Welcome' or
Multi = "Welcome"
#3) List
A list can contain a series of values.
List variables are declared by using brackets [ ]. A list is mutable, which means we can modify
the list.
Example:
List = [2,4,5.5,"Hi"]
print("List[2] = ", List[2])
Output: List[2] = 5.5
#4) Tuple
A tuple is a sequence of Python objects separated by commas.
Tuples are immutable, which means tuples once created cannot be modified. Tuples are
defined using parentheses ().
Example:
Tuple =
(50,15,25.6,"Python")
print("Tuple[1] = ", Tuple[1])
Output: Tuple[1] = 15

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 8


#5) Set
A set is an unordered collection of items. Set is defined by values separated by a comma inside
braces { }.
Example:
Set = {5,1,2.6,"python"}
print(Set)
Output: {‘python’, 1, 5, 2.6}
#6) Dictionary
Dictionaries are the most flexible built-in data type in python.
Dictionaries items are stored and fetched by using the key. Dictionaries are used to store a huge
amount of data. To retrieve the value we must know the key. In Python, dictionaries are
defined within braces {}.
We use the key to retrieve the respective value. But not the other way around.
Syntax:
Key:value
Example:
Dict = {1:'Hi',2:7.5, 3:'Class'}
print(Dict)
Output: {1: ‘Hi’, 2: 7.5, 3: ‘Class’}

Python Relational Operators

relational operator is used to compare two values. Based on the operator and values, the
operator returns either True or False.

In Python, there are six Relational Operators. They are

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 9


Symbol Name Example Description

== Equal to x == y Returns True if x and y have same value, else returns False.

> Greater than x>y Returns True if value of x is greater than value of y, else
returns False.

< Less than x<y Returns True if value of x is less than value of y, else returns
False.

!= Not equal to x != y Returns True if x and y do not have same value, else returns
False.

>= Greater than x >= y Returns True if value of x is greater than or equal to value
or equal to of y, else returns False. Equivalent to ( x>y or x==y )

<= Less than or x <= y Returns True if value of x is less than or equal to value of y,
equal to else returns False. Equivalent to ( x>y or x==y )
An Example Program Using Relational Operators
Let us consider two variables a & b of values 10 and 20 to understand relational operations
better.
a, b = 10, 20

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 10


print(a == b) # since the values 10 and 20 are different, the output of this print statement is False

print(a != b) # since both the values are not equal, the output of this print statement is True print(a

> b) # the value 10 is less than 20, hence the output of this print statement is False print(a < b) #

since the value 10 is less than 20, the output of this print statement is True print(a >= b) # Since

the value 10 is less than 20, the output of this print statement is False
print(a <= b) # Since the value 10 is less than 20, the output of this print statement is True Output:
FalseTrueFalseTrueFalseTrue

Python Logical Operators


Logical operators are used to combine conditional statements:
Operator Description Example

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

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

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

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Description

& Binary AND TThe operator sends the bit present in both operands to the output.

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 11


| Binary OR TIf a bit is present in either operand, it is copied.

^ Binary XOR TIt is copied if the bit is set inside one argument but not both.

~ Binary Ones TIt has the function of 'flipping' bits and is unary.
Complement

<< Binary Left TThe left operand's value is moved to its left by the number of bits specified in the
Shift right argument.

>> Binary Right The quantity of bits provided by the right parameter advances the position of the
Shift left operand.

Examples
x = 10
y=4
# Bitwise AND operation
print("x & y =", x & y)
Output: x & y = 0
Simple Input and Output
input() Function
Python input() function is used to get input from the user. It prompts for the user input and reads
a line. After reading data, it converts it into a string and returns that. It throws an error EOFError
if EOF is read.

Signature
input ([prompt])
Parameters
prompt: It is a string message which prompts for the user
input. Return
It returns user input after converting into a string.
Let's see some examples of input() function to understand it's
functionality. Example
III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 12
Example
# Python input() function example
# Calling function
val = input("Enter a value:
") # Displaying result
print("You entered:",val)
Output:

Enter a value:

45 You entered:

45

print() Function
Python print() function prints the given object on the screen or other standard output devices.
Signature
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameters
object(s): It is an object to be printed. The Symbol * indicates that there may be more than
one object.
sep='separator' (optional): The objects are separated by sep. The default value of sep is ' '.
end='end' (optional): it determines which object should be print at last.
file (optional): - The file must be an object with write(string) method. If it is omitted, sys.stdout
will be used which prints objects on the screen.
flush (optional): If True, the stream is forcibly flushed. The default value of flush is False.
Return
It does not return any value.
Example
print("Python is programming language.")

x=7
# Two objects passed
III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 13
print("x =", x)

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 14


y=x
# Three objects passed
print('x =', x, '= y')
Output:
Python is programming
language. x = 7
x=7=y

III B.Sc IT – B-- SKACAS Python Programming – Unit I Page 15

You might also like