0% found this document useful (0 votes)
2 views

Getting Started With Python

The document provides an overview of Python, a popular programming language known for its readability and ease of use, developed by Guido Van Rossum in 1991. It outlines Python's strengths, such as simplicity and platform independence, as well as its limitations, including slower execution and less mobile development capability. Additionally, it covers Python installation, coding modes, tokens, variables, operators, and data types, along with examples and explanations of various programming concepts.
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)
2 views

Getting Started With Python

The document provides an overview of Python, a popular programming language known for its readability and ease of use, developed by Guido Van Rossum in 1991. It outlines Python's strengths, such as simplicity and platform independence, as well as its limitations, including slower execution and less mobile development capability. Additionally, it covers Python installation, coding modes, tokens, variables, operators, and data types, along with examples and explanations of various programming concepts.
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/ 15

ST JOSEPH’S SCHOOL

SUBJECT – COMPUTER SCIENCE


Unit 5 – Getting started with Python

Python is a popular programming language due to its liveliness and pleasant productivity. It offers
programming fun while coding. It was developed by Guido Van Rossum in February 1991 and
further developed by the Python software foundation. It is a general-purpose programming
language. Its syntax is easy and designed to give importance to the readability of code. It saves a
few lines of codes with easy syntax rules. It is a powerful programming middle-level language
but not so high-level language like C, C++, Java, etc.
Strengths –Python
1) Easy to use: The syntax of python is very simple to use compared to other programming
languages.
2) Fewer Lines code: It offers few lines of code, a programmer can write multiple lines of in
a single line.
3) Use of interpreter: Python is using an interpreter, not a compiler that executes code line by
line. So it is easy for a beginner.
4) No additional library required: When python is installed, all basic libraries installed with
it. So no need to install any standard library.
5) Platform Independent: Python can run on any platform such as Windows, Linux/UNIX,
Macintosh etc. Moreover, it can run on many devices like supercomputers, smartphones.
It is a portable language.
6) Free & Open Source: It’s free of cost and can be downloaded from www.python.org. It is
open-source, so source code may be available for redistribution.
7) Offers a variety of applications: Nowadays Python is used in many devices or applications
such as Scripting, Web Development, Gaming, AI, Database Development etc.
Limitations –Python
1) Slow execution: Python uses an interpreter that executes code line by line which is slower
in execution compared to a compiler-based programming language.
2) Less no. of libraries: Python offers limited libraries compared to other programming
languages like C, C++, etc.
3) Not strong for mobile development: It is good for desktop or server-based applications but
not efficient for mobile apps.
4) Memory Consumption: Python offers flexible data types so there is high memory
consumption.
5) Weak in database connectivity: It is not that much strong like JDBC or ODBC, its database
access layer has some barriers.
Python Installation
Before starting programming with python, it needs to be installed. There are few distributions of
python available like CPython (set of applications such as python interpreter, Python IDLE and
Pip), Anaconda Python distribution (Comes with preloaded packages and libraries with IDEs like
Spider, Jupyter, PyCharm etc.)
Python interpreter offers two modes for coding:
1) Interactive mode
2) Script mode
Working in Interactive Mode
Interactive mode allows one to type one statement and executes the same line when the enter key
is pressed. To start working in interactive mode follow these steps:
Step1. Click on Start → All Programs → Python 3.7 →IDLE (Python 3.7 64-bit).
A python Shell window will appear as shown in the below-given screen:

After typing a line or statement press enter, the interpreter will execute the line and gives the
result:

Working in Script Mode


Working in script mode is an essential part when you are Getting started with Python.
To work in script mode follow these steps:
Step 1. Click on Start → All Programs → Python 3.7 →IDLE (Python 3.7 64-bit). A python
shell will appear.
Step 2. Click File New. A new window will appear with the title “untitled”.
Step 3. Type the statement(s).
Step 4. Click on Run → Run Module or press F5 key.

Step 5. It prompts to save the module. Save the file with .py extension.

Step 6. The python shell display output like this:


Tokens
Tokens are the least units of programs. These tokens are as following:
• Identifiers
• Keywords
• Literals
• Operators
• Punctuators
Identifiers
Identifiers are names used in programs to identify small units of programs such as variables,
objects, classes, functions etc.

Identifiers defined by the following few rules as follows:


• It must start alphabets
• It can be a combination of numbers and letters
• Special characters are not allowed in identifiers name
• Spaces are not allowed in identifier names, underscore can be used to separate two words
• The meaning of Upper Case and Lower Case different should not use as identifier names
Few Examples: MyData, roll_no, year1 etc.
Variables
Variables are storage names with specific data types, used to store a value for use in the future. It
holds a value of any type such as numeric values, letters, or any other value. The value of the
variable can be changed at execution time by the user and it keeps changing as per the need of
the program.
A variable needs to declare first then it will assign a value or use in input statement and finally
hold output or final result. The value of a variable manipulates any time in a program. Now let’s
look at this code:
In the first code variable, a is assigned value 5. In python, when the value is assigned to the
variable, the data type of a variable is determined by python itself. So here 5 is an integer. In the
second code variable, a is declared with value 5, then value 10 is added in a and then displayed
using print() function. In the last code, two different values assigned to two different variables a
and b, 5 and 10 respectively, then added both of them along with print() functions.
There are three main properties associated with a variable:
1. Address: Memory location address in the memory cell. To know the address of memory
location python offers id() function, that accepts a variable name as parameter.

Displaying memory address through id() function


2. Value: Assigned by the programmer or changed by the statements in a program.
3. Datatype: The type of data such as number, letters or string, etc. To print datatype of a variable,
python offers type() function.

Displaying data type of variable


Keywords
Keywords are python reserved words used in a program. Each and every keyword conveys
special meaning to the python interpreter.
Ex.: def, False, if, elif, else, for etc.
Literals(Constants)
Literals or Constants means that an item(s) have a fixed value. There are several types of constants
or literals as follows:
String Literals: Ex.: ‘a’, ‘abc’, ‘my_name’, ‘t’, ‘n’ etc.
Numeric Literals: int, float, complex etc.
Boolean Literals: True or False
Special Literals: None

Operators
An operator is used to perform specific mathematical or logical operation on values.

Operand
The values that the operator works on are called operands.

For example,
>>> 10 + num,

10 & num are operands and


the + (plus) sign is an operator.
Arithmetic Operator
Operator Description

+ (unary) Explicitly express a +ve number. Example : +3, +98.36

– (unary) Explicitly express a –ve number. Example : -3, -369.36

+ (binary) Add two numbers, Example : 9 + 6 is 15

– (binary) Subtract one value from another number. Example: 9 – 3 is 6

* Product of two numbers. Example 9 * 6 is 54

/ Gives quotient, when one value is divided by the other. Example 9/ 6 is 1.5

// (floor Gives integer part of quotient, when one value is divided by the other. Example
division) 9//6 is 1.
% (Remainder) Gives remainder when one value is divided by the other. Example 9 % 6 is 3

** (Exponent) To raise a number to the power of another number. Example, 3**2 is 9

Assignment Operator

Operator Description

= Called Assignment operator. Assign a value to the variable. Example, x = 20.

Add and Assign, Add the R-Value to the L-Value and assign result to L-value. Example
+= x=20, x += 30 it means x = x + 30 so the new value of x is 50.

Subtract and Assign, Subtract the R-Value from L-Value and assign result to L-value.
-= Example x=50, x -= 30 it means x = x – 30 so the new value of x is 20.

Multiply and Assign, Multiply the R-Value with L-Value and assign product to L-value.
*= Example x=50, x *= 3 it means x = x * 3 so the new value of x is 20.

Divide and Assign Quotient, Divide the L-value with R-Value and assign quotient to L-
/= value. Example, x = 50, x /= 6 its means x = x / 6, and the new value of x is 8.33333……

Floor and assign, Divide the L-value with R-Value and assign integer quotient (floor
division) to L-value. Example, x = 50, x //= 6 its means x = x // 6, and the new value of
//= x is 8.

Divide and Assign Remainder, Divide the L-value with R-Value and assign remainder to
%= L-value. Example, x = 50, x %= 6 its means x = x % 6, and the new value of x is 2.

Exponent and Assign, Calculate (L-Value)R-Value and assign the result to L-value. Example,
**= x = 3, x**=2 its means x = x2 and the result of x is 9

Assignment Operator | mycututorial.in

Relational Operator

Operator Description

Compares two values for equality, Returns True if they are equal,
== (Equality) otherwise returns False.

Compares two values for inequality, Returns True if they are not equal,
!= (Not equal) otherwise returns False.
Compares two values, Returns True if first value is less than the second,
< (Less than) otherwise returns False.

Compares two values, Returns True if first value is greater than the second,
> (greater than) otherwise returns False.

<= (Less than or equal Compares two values, Returns True if first value is less than or equal to the
to) second, otherwise returns False.

>= (greater than or Compares two values, Returns True if first value is greater than or equal to
equal to) the second, otherwise returns False.

Relational Operator | mycstutorial.in

Logical Operator

Operator Description

not Negate a condition and Returns True if the condition is false otherwise returns False.

Combines two conditions and returns True if both the conditions are true, otherwise
and returns False.

Combines two conditions and returns True if at least one of the condition is true,
or otherwise returns False.

Logical Operator | mycstutorial.in

Bitwise Operator

Operator Description

The AND (&) operator compares two bits and generates a result of 1 if both
& (bitwise and) bits are 1 otherwise, it returns 0

The OR (|) operator compares tow bits and generate a result 1 if the bits are
| (bitwise or) complementary, otherwise it returns 0.

The EXCLUSIVE-OR (XOR) operator compares two bits and return 1 if either
^ (bitwise xor) of the bits are 1 and it gives 0 if both bits are 0 or 1

~ (bitwise
complement) The COMPLEMENT operator is used to invert all of the bits of the operand.

Note: bin( ) returns binary representation number.


Membership Operator

Operator Description

Returns True if the given value is available in the sequence (like sting, tuples, lists,
in dictionary, etc.) otherwise returns False.

Returns True if the given value is not available in the sequence (like sting, tuples, lists,
not in dictionary, etc.) otherwise returns False.

Identity Operator

Operator Description

Returns True, if both operand have same identity i.e. memory reference , otherwise return
is False

Returns True, if both operand have not same identity i.e. memory reference , otherwise
Is not return False

Operator Precedence :
Execution of operator depends on the precedence of operator.

Order Operator Description

Highest () Parentheses

↑ ** Exponentiation

| ~ Bitwise nor

| +, – Unary Plus and Minus

| *, /, //, % Multiplication, Division, floor division , remainder

| +, – Addition, Subtraction

| & Bitwise and

| ^ Bitwise XOR

| | Bitwise OR
| <, <=, >, >=, <>, !=, ==, is, is not Relational Operators, Identity Operators

| not Boolean NOT

↓ and Boolean AND

Lowest or Boolean OR

Expression
In Python, An expression is a valid combination of operators, literals and variables.
There are three types of Expression in Python, These are-
•Arithmetic Expressions :- combination of integers, floating-point numbers, complex number,
and arithmetic operators. Example ; 2+9, 9.2/3
•Relational Expression :- combination of literals and/or variables of any valid type and
relational operators . Example; x > y, 5 < 8, z == y
•Logical Expression:- combination of literals, variables and logical operators.
Example; t and q, p or g
•String Expression :- combination of string literals and string operators ( + -> concatenate,
and * -> replicate). Example;
“Hello” + “Anjeev” = “Hello Anjeev”
“Like” * 3 = “LikeLikeLike”
input() function - This function is used accept value from user. Let’s look in the following:

print() function
As I have used print() function in the above codes. It allows generating output on the screen.
The syntax of the print() function is as follows:
Basically python print() a new line when the print function is used in the program.
Datatypes in python

Numbers: It holds numeric values in a program. Python allows following built-in data types for
numbers:
Integer: A Numeric value without decimal places is considered as an integer. The inbuilt class
‘int’ represent these type of numbers. Integers can be of any length in python.
Ex. : 12345, -45465, 234, -456, 10, 0
Float: Real numbers having decimal or floating points are considered are float. Ex.: 567.90,
234.90, 3456.898989 etc. Python prints a large value post decimal places by default. Have a
look on the following code:

Complex Number: It has two parts: i) Real Number and ii) Imaginary Part. It is available in the
form of ‘x + yJ’ or ‘x + yj’, where x is a float number (real number), yJ is the imaginary part,
small letter j indicates the square root of an imaginary number -1. Example:

Sequence: It accepts values as in a sequence or specific patters. Python offers the following
sequence data types:
str (String): It is a sequence of characters that is a combination of letters, numbers, and special
symbols. A string is enclosed with a quotation. It can be enclosed with single, double, or triple
quotes. Single line text is enclosed either with single or double quotes whereas multi-line text is
enclosed with triple quotes.
Python also offers a special escape character sequence to print some non-graphic character as
following:

Escape character sequence in Python


Boolean: Boolean holds either True or False value. Any statement that has either True or False
result, has a boolean data type.
Variable Assignment
The assignment operator (=) is used to assign a new value to a variable. It takes a general form
like L-value = R-value where
L-value is always a variable
R-value is a value assigned to a variable, R-value can be a value or expression
Ex. x = 3, where L-value is x and R-value is 3.
Python allows multiple assignments in a statement.
Multiple Assignment
Python allows multiple variable assignments in one line. There are two ways to assign multiple
values:
Assign multiple values to multiple variables
The values of the variable assigned by separating them with commas. Ex.:
Multiple variable assignments
The same value assigned by using an assignment operator (=) multiple times.

Assign a same value to multiple variable


Types Casting / Explicit Type Conversion
The conversion of one type to specific type explicitly, called Type Casting / Explicit Type
Conversion.
With explicit type conversion, there is a risk of loss of information since we are forcing an
expression to be of a specific type.
Syntax: <type>( )
Example x = int ( “123”)
y = float(“5369.36”)
z = str(598698.36)
Functions in Python that are used for explicitly converting an expression or a variable to a
different types are –
int(x) – Converts x to an integer
float(x) – Converts x to a floating-point number
str(x) – Converts x to a string representation
chr(x) – Converts x to a character
unichr(x) – Converts x to a Unicode character
Program : Explicit type conversion from int to float
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
30
<class 'int'>
30.0
<class 'float'>

Program : Explicit type conversion from float to int


num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Output:
<class 'float'>
30.8
<class 'int'>
30

Implicit Conversion
Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.

Program to show implicit conversion from int to float.


num1 = 10 # num1 is an integer
num2 = 20.0 # num2 is a float
sum1 = num1 + num2
# sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output:
30.0
<class 'float'>

Debugging (Process of Identifying and Removing Errors)


Bug / Errors – The mistake (error) and problem found in the program is called Bug.
Debug – Removing the bug / error from the program is called Debug.
Debugging – The process of Identifying and removing errors from the program is called
debugging.
Types of Errors
Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors:
Python has its own rules that determine its syntax. The interpreter interprets the statements only
if it is syntactically (as per the rules of Python) correct. If any syntax error is present, the
interpreter shows error message(s) and stops the execution.
For Example : 10 = X
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A logical error
produces an undesired output but without abrupt termination of the execution of the program.
For Example : Instead of +, you writing – operator.
Total = X – Y
Runtime Error
A runtime error causes abnormal termination of program while it is executing. Runtime error is
when the statement is correct syntactically, but the interpreter cannot execute it. Runtime errors
do not appear until after the program starts running or executing.
x = int(input(“enter number”))
You entered here 25.69. It is a run time error.
Divide by a zero is also called runtime error.

You might also like