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

Python (UNIT 1 mul exclusive

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)
13 views

Python (UNIT 1 mul exclusive

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/ 17

UNIT- 1

Introduction: The Programming Cycle for Python, Python IDE, Interacting with Python Programs, Elements of Python,
Type Conversion. Basics: Expressions, Assignment Statement, Arithmetic Operators, Operator Precedence, Boolean
Expression.

❖ INTRODUCTION
• Python is a widely used general-purpose, high level programming language. It was initially designed by
Guido van Rossum in 1991.
• It is a cross-platform programming language, which means it runs on all the major operating systems.
o Python on Windows
o Python on Mac OS
o Python on Linux
• Python Applications
o Web Development
o Game Development
o Machine Learning and Artificial Intelligence
o Data Science and Data Visualization
o Desktop GUI
o Business Applications
o Audio and Video Applications
o CAD Applications
o Embedded Applications

❖ PROCESS OF PROGRAMMING:
Programming is the process of creating a set of instructions that tell a computer how to perform a task. For
programming there is the need of programming language. A programming language is a computer
language that is used by programmers (developers) to communicate with computers. It is a set of
instructions written in any specific language ( C, C++, Java, Python) to perform a specific task.

With experience, these three stages of programming get merged and the separation between the stage’s
blurs.
1. Problem Description: The first step is describing the problem. It is the most difficult and the most
important of all the steps. It involves diagnosing the situation so that the focus on the real problem and
not on its symptoms.
2. Model the problem: In real-time this is important and complicated. In this step we implement picture
of the separate steps of a process in sequential order. For example, consider modeling the Indian
Railways Reservation System. If the model is not proper the end result will be unsatisfactory.
3. Logical Solution: Next step is to obtain a logical solution to your problem. A logical solution is a finite
and clear step-by-step procedure to solve your problem i.e algorithm.
4. Solution Code: The last step is to convert the algorithm into working code. This is the stage where you
require a language to communicate with the computer. If your model or the logical solution is wrong,
the program will also be wrong.

❖ PROGRAMMING CYCLE FOR PYTHON:

WRITE/ EDIT

NO RUN
(with some input)

OK
with some input YES

YES

More
Inputs

No

FINISH
1. Write your program or edit (i.e., change or modify) your program.
2. Run your program on an input.
-Python is an interpreted language (unlike C, C++, Java). There is no separate compilation step.
3. If the output is not correct, return to editing step and
4. Repeat step 2 and 3.
4. If the output is correct then check it on more inputs if any and then run it again.
5. If there is no more input then the program is finished.

❖ INTERACTING WITH PYTHON PROGRAMS:


Python is a cross-platform programming language, which means it runs on all the major operating systems.
❖ Python on Windows
❖ Python on Mac OS
❖ Python on Linux
1. Python on Windows
• First, check whether Python is installed on your system, Open a command window.
• In the terminal window, enter python in lowercase.
• If you get a Python prompt (>>>) in response, Python is installed on your system.
• If you see an error message telling you that python is not a recognized command, Python isn’t installed.

Download Python:
• Go to https://python.org/ and hover over the Download link.
• See a button for downloading the latest version of python.
• Click the button, which should download the correct installer for your system.
• After downloaded the file, run the installer.
• Make sure you select the option Add Python to PATH.

Running Python in a Terminal Session –


• Open a command window and enter python in lowercase. You should see a Python prompt (>>>), which
means Windows has found the version of Python you just installed.
• Enter the following line in your Python session, and make sure you see the output Hello Python
interpreter

>>> print("Hello Python interpreter!")


Hello Python interpreter! >>>

Installing Sublime Text –


Download an installer for Sublime Text at https://sublimetext.com/. Click the download link and look for a
Windows installer. After downloading the installer, run the installer and accept all of its defaults.
2. Python on macOS
• First, check whether Python is installed on your system, open a terminal window by going to
Applications → Utilities →Terminal.
• You can also press z-spacebar, type terminal, and then press enter.
• To see which version of Python is installed, enter python with a lowercase.
• You should see output telling you which Python version is installed on your system and a >>> prompt
where you can start entering Python commands.

Download Python
• You can find a Python installer for your system at https://python.org/
• Hover over the Download link, and you should see a button for downloading the latest Python version.
• Click the button, which should automatically start downloading the correct installer for your system.
• After the file downloads, run the installer.

Running Python in a Terminal Session –


• Open a terminal and typing python3. Enter the following line in the terminal session:

>>> print("Hello Python interpreter!")


Hello Python interpreter!

• Your message should print directly in the current terminal window

Installing Sublime Text –


To install the Sublime Text editor, you need to download the installer at https://sublimetext.com/. Click
the Download link and look for an installer for macOS. After the installer downloads, open it and then
drag the Sublime Text icon into your Applications folder

3. Python o n Linux
• Linux systems are designed for programming, so Python is already installed on most Linux computers.

Checking Your Version of Python –


• Open a terminal window by running the Terminal application on your system (in Ubuntu, you can press
ctrl-alt-T).
• To find out which version of Python is installed, enter python3 with a lowercase.

Running Python in a Terminal Session –


• Open a terminal and entering python3, as you did when checking your version.
• Do this again, and when you have Python running, enter the following line in the terminal session:

>>> print("Hello Python interpreter!")


Hello Python interpreter! >>>
Installing Sublime Text –
On Linux, you can install Sublime Text from the Ubuntu Software Center. Click the Ubuntu Software icon
in your menu, and search for Sublime Text. Click to install it, and then launch it.

❖ PYTHON IDE
• A Python Integrated Development Environment (IDE) provides all the essential tools needed for
software development with Python.
• IDE is a software package that consists of several tools for developing and testing the software.
• An IDE helps the developer by automating the process. It helps to automate the tasks and enhance the
productivity and efficiency of the developer.
• IDEs integrate many tools that are designed for SDLC.
• IDEs were introduced to diminish the coding and typing errors.
• A Python IDE primarily consists of a code editor, a compiler, automation tools, debugging tools, and
much more and you can conveniently write, compile, execute, and debug the code with the help of it.
• Some of the additional requirements for a better Python IDE are – Source Code Backup, Automatic Code
Formatting, Debugging Support, Syntax Highlight, and many others.
• Some Python IDE’s are:

a. Pycharm: PyCharm assists the developers to be more productive and provides smart suggestions. It
saves time by taking care of routine tasks, hence increases productivity.
Features of PyCharm:
i. It has smart code navigation, good code editor, a function for quick refactoring.
ii. The integrated activities with PyCharm are profiling, testing, debugging, remote development, and
deployments.
iii. PyCharm supports Python web development frameworks, Angular JS, JavaScript, CSS, HTML and live
editing functions.

b. Spyder: Spyder is widely used for data science works. It is mostly used to create a secure and scientific
environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can add as an
extension.
Features of Spyder :
i. It has good syntax highlighting and auto code completion features.
ii. Spyder Python explores and edits variables directly from GUI.
iii. It performs very well in multi-language editor.

c. PyDev: It is an external plug-in for Eclipse and is very popular as Python interpreter.
Features of PyDev :
i. PyDev has strong parameters like refactoring, debugging, type hinting, code analysis, and code
coverage function.
ii. PyDev supports tokens browser, interactive console, remote debugger etc.
d. IDLE : IDLE is a basic IDE mainly used by beginner level developer.
Features of IDLE:
i. IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.
ii. It is developed only in Python in collaboration with Tkinter GUI toolkit.
iii. The feature of multi-window text editor in IDLE has some great functions like smart indentation, call
tips, Python colorizing, and undo option.
iv. It supports browsers, editable configurations, and dialog boxes.

e. Visual studio: It enables development for various platforms and has its own marketplace for extensions.
Features of visual studio:
i. It supports Python coding in visual studio, debugging, and other activities.
ii. It has both paid and free versions in the market with great features.

How to Install Pycharm


Step 1) To download PyCharm visit the website https://www.jetbrains.com/pycharm/download/ and Click
the “DOWNLOAD” link under the Community Section.
Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard should have
started. Click “Next”.
Step 3) On the next screen, Change the installation path if required. Click “Next”.
Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.
Step 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.
Step 6) Wait for the installation to finish.
Step 7) Once installation finished, you should receive a message screen that PyCharm is installed. If you
want to go ahead and run it, click the “Run PyCharm Community Edition” box first and click “Finish”.

❖ VARIABLES:
• 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 and y are
variables

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, 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.
❖ CONSTANTS:
• A constant is like a variable whose value stays the same throughout the life of a program
• Python doesn't have built-in constant types, but Python programmers use all capital letters to indicate a
variable should be treated as a constant and never be changed

MAX_CONNECTIONS = 5000

❖ PYTHON COMMENTS:
• Comments can be used to explain Python code. It can be used to make the code more readable.
• Comments starts with a # symbol in python.

EXAMPLE:

#This is a comment
print("Hello, World!")

Python does not really have a syntax for multiline comments. To add a multiline comment you could
insert a # for each line:

EXAMPLE:
#This is a comment
#written in
#more than just one line
print("Hello, World!")

❖ ELEMENTS IN PYTHON:
A Python program is a sequence of definitions and commands (statements). Commands are manipulated by
objects where each object is associated with a type.

DATATYPES IN PYTHON:
1. NUMBERS:
There are two main number types we will work with:
o Integers which are whole numbers.
o Floating Point numbers which are numbers with a decimal.

Underscores in Numbers
• When you're writing long numbers, you can group digits using underscores to make large numbers more
readable:
When you print a number that was defined using underscores, Python prints only the digits:

Multiple Assignment
• You can assign values to more than one variable using just a single line.
• This can help shorten your programs and make them easier to read; you'll use this technique most often
when initializing a set of numbers
2. STRINGS:
• Strings are sequences of characters, using the syntax of either single quotes or double quotes:
o 'hello'
o "Hello"
o "I don't do that "
• Because strings are ordered sequences it means we can using indexing and slicing to grab sub-sections of
the string.
• Indexing notation uses [ ] notation after the string (or variable assigned the string).
• Indexing allows you to grab a single character from the string.
• These actions use [ ] square brackets and a number index to indicate positions of what you wish to grab.

• Slicing allows you to grab a subsection of multiple characters, a “slice” of the string.
• This has the following syntax:
[start:stop:step]
• start is a numerical index for the slice start
• stop is the index you will go up to (but not include)
• step is the size of the “jump" you take.
3. LISTS:
• Lists are ordered sequences that can hold a variety of object types.
• They use [] brackets and commas to separate objects in the list.
[1,2,3,4,5]
• Lists support indexing and slicing. Lists can be nested and also have a variety of useful methods that can
be called off of them.

4. DICTIONARIES:
• Dictionaries are unordered mappings for storing objects. Previously we saw how lists store objects in an
ordered sequence, dictionaries use a key-value pairing instead.
• This key-value pair allows users to quickly grab objects without needing to know an index location.
• Dictionaries use curly braces and colons to signify the keys and their associated values.

{‘key1’:‘valuel’, ‘ key2’:‘value2’}
5. TUPLES:
• Tuples are very similar to lists. However they have one key difference - immutability.
• Once an element is inside a tuple, it can not be reassigned.
• Tuples use parenthesis: Eg: (1,2,3)

6. SETS:
• Sets are unordered collections of unique elements.
• Meaning there can only be one representative of the same object.
7. BOOLEANS:
• Booleans are operators that allow you to convey True or False statement
• Boolean expression uses Relational operator for comparison of values.

• Relational operators in Python are also called as Comparison operators. They are used to compare the
operands on either side and determine the relation between them. The output of the comparison
results in a Boolean value.

Finding Types of Expression:

❖ TYPE CONVERSION (TYPE CASTING):


• Python defines type conversion functions to directly convert one data type to another.
• We are used to int →float conversion in Math
o Integer 3 is treated as float 3.0 when a real number is expected.
o Float 3.6 is truncated as 3, or rounded up as 4 for integer contexts.
• Type names also work as Type converter functions in Python.
• There are two types of Type Conversion in Python:
o Implicit Type Conversion
o Explicit Type Conversion

1. Implicit Type Conversion


In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data
type to another without any user involvement.

PROGRAM:
x = 25 OUTPUT:
print("x is of type:",type(x))
y = 25.6
print("y is of type:",type(y))
x=x+y
print(x)
print("x is of type:",type(x))

2. Explicit Type Conversion


• In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement.
• Mainly in type casting can be done with these data type function:
1. int() : int() function take float or string as an argument and return int type object.
2. float() : float() function take int or string as an argument and return float type object.
3. str() : str() function take float or int as an argument and return string type object.

PROGRAM:
a. Type Casting int to float:

# int variable OUTPUT:


a = 10
# typecast to float
n = float(a)
print(n)
print(type(n))

b. Type Casting float to int:

# float variable OUTPUT:


a = 10.4
# typecast to int
n = int(a)
print(n)
print(type(n))
c. Type casting int to string:

# int variable OUTPUT:


a=6
# typecast to str
n = str(a)
print(n)
print(type(n))

❖ EXPRESSIONS
• An expression is a combination of symbols that evaluates to a value.
• An expression is a combination of variables, operators, values sub-expressions and a reserve keyword.
• Whenever we type an expression in the command line, the interpreter evaluates it and produces the
result.
• Expressions that evaluate to a numeric type are called arithmetic expressions.
• A sub-expression is any expression that is part of a larger expression.
• Sub-expressions are also denoted by the use of parentheses.

For example: 4 + (3 * k)

An expression can also consist of a single literal or variable. Thus, 4, 3 and k are each expression.

This expression has two sub-expressions, 4 and (3 * k). Sub-expression (3 * k) itself has two sub-
expressions, 3 and k.

❖ ASSIGNMENT STATEMENT:
• Assignment statements are used to create new variables, assign values, and change values.
• A simple assignment statement

Variable = Expression

• Computes the value (object) of the expression on the right hand side (RHS).
• Associates the name (variable) on the left hand side (LHS) with the RHS value.
• = is known as assignment operator.
• Examples
x = 10
disc_2 = b*b 4*a*c
count = count + 1
• Evaluation of an assignment statement:
- Expression on the RHS of the = operator is first evaluated.
- Value of the expression is bound to the variable on the LHS.
• Multiple Assignments:

➢ Python allows multiple assignments


➢ Evaluation of multiple assignment statement:

- All the expressions on the RHS of the = are first evaluated before any binding happens.
- Values of the expressions are bound to the corresponding variable on the LHS.

❖ ARITHMETIC OPERATORS:

• Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division etc.
• Assume variable a holds 10 and variable b holds 20, then −

❖ OPERATOR PRECEDENCE
• The computer scans an expression which contains the operators from left to right and performs only
one operation at a time.
• The expression will be scanned many times to produce the result.
• The order in which various operations are performed is known as hierarchy of operations or operator
precedence.
• Some of the operators of the same level of precedence are evaluated from left to right or right to left.
This is referred to associativity.
• Example of Operator Precedence are:

❖ BOOLEAN EXPRESSION:

• Boolean expressions are evaluated to either true or false.


• Boolean expression uses Relational operator for comparison of values.
• Relational operators in Python are also called as Comparison operators. They are used to compare the
operands on either side and determine the relation between them. The output of the comparison
results in a Boolean value.
• Below is the list of relational operators in Python. Relational operators are the same in all versions of
Python.
Operator Name Description

== Equal to Checks whether two operands are equal

!= Not equal to Checks whether two operands are not equal

Checks whether the left side operand is greater than the right side
> Greater than
Operand

< Less than Checks whether the left side operand is less than the right side operand

Checks whether the left side operand is either greater or equal to the
>= Greater than or equal to
right side operand

Checks whether the left side operand is either less than or equal to the
<= Lesser than or equal to
right side operand

Example:

Program:

a, b = 15, 22 Output:

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)

You might also like