SlideShare a Scribd company logo
Department of Electrical Engineering
The University of Faisalabad
LAB No: 01
Title:
Introduction to PyCharm.
Objective:
 How to download and install IDLE Python and PyCharm.
 Codes and results demonstrating the use of conditional statements, loops, lists,
dictionaries etc.
Introduction:
Python is a widely used high-level programming language first launched in 1991. Since then,
Python has been gaining popularity and is considered as one of the most popular and flexible
server-side programming languages.
It isusedfor:
 web development (server-side)
 software development
 mathematics
 system scripting.
What can Python do?
 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping or for production-ready software
development.
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.
Python Syntax compared to otherprogramming languages:
 Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
 Python uses new lines to complete a command as opposed to other programming
languages which often use semicolons or parentheses.
Department of Electrical Engineering
The University of Faisalabad
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops functions and classes. Other programming languages often use curly-brackets for
this purpose.
Download the Python:
Step_1:
Select the version of to install the Python. Python is available from its website, Python.org.
Once there, hover your mouse over the download menu, then over the Windows option, and
then click the button to download the latest release in the fig 1.1.
Figure 1.1
 We select the Add Python 3.9 to PATH and then click on Customize installation.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.2
 Thenclickon Next.
Figure 1.3
Department of Electrical Engineering
The University of Faisalabad
 Clickon Install forall usersfromthe Advanced Option and then click on Install.
Figure 1.4
 Then click on install option. Now installation has been started in fig.1.5.
figure 1.5
 And then close the installation. We can see that our setup was successful.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.6
 Verification of our installation on Command Prompt. We can see our installation is
complete.
Figure 1.7
 Interface with the Python Window. Run a print program in fig. 1.8.
Figure 1.8
IntroductiontoPyCharm:
Department of Electrical Engineering
The University of Faisalabad
PyCharm is the most popular IDE used for Python scripting language. This chapter will give you
an introduction to PyCharm and explains its features.
PyCharm offers some of the best features to its users and developers in the following aspects:
 Code completion and inspection
 Advanced debugging
 Support for web programming and frameworks such as Django and Flask.
Features of PyCharm:
Besides, a developer will find PyCharm comfortable to work with because of the features
mentioned below:
Code Completion:
PyCharm enables smoother code completion whether it is for built in or for an external
package.
SQLAlchemy as Debugger:
You can set a breakpoint, pause in the debugger and can see the SQL representation of the user
expression for SQL Language code.
Git Visualization in Editor:
When coding in Python, queries are normal for a developer. You can check the last commit
easily in PyCharm as it has the blue sections that can define the difference between the last
commit and the current one.
Code Coverage in Editor:
You can run .py files outside PyCharm Editor as well marking it as code coverage details
elsewhere in the project tree, in the summary section etc.
Package Management:
All the installedpackagesare displayedwithpropervisual representation.Thisincludeslist of installed
packagesand the abilitytosearchand add new packages.
Steps Involved:
You will have tofollowthe stepsgivenbelowtoinstall PyCharmonyoursystem.These stepsshow the
installationprocedure startingfromdownloadingthe PyCharmpackage fromitsofficialwebsite to
creatinga newproject.
Step1:
Download the required package or executable from the official website of PyCharm
https://www.jetbrains.com/pycharm/download/#section=windows. Here you will observe two
versions of package for Windows as shown fig 1.9 given below:
Department of Electrical Engineering
The University of Faisalabad
Figure 1.9
Note that the professional package involves all the advanced features and comes with free trial
for few days and the user has to buy a licensed key for activation beyond the trial period.
Community package is for free and can be downloaded and installed as and when required. It
includes all the basic features needed for installation. Note that we will continue with
community package throughout this tutorial.
Here we can see, we have two options in fig.1.10.
PyCharm Professional Edition PyCharm Community Edition
Department of Electrical Engineering
The University of Faisalabad
Figure 1.11
 Click on Next to continue.
Figure 1.12
Step_2:
Department of Electrical Engineering
The University of Faisalabad
Download the community package (executable file) onto your systemand mention a
destination folder as shown below:
 Click on all the options and then on Next.
Figure 1.13
Step3:
Now, begin the installation procedure similar to any other software package.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.14
 Our Installation is started.
Figure 1.15
Department of Electrical Engineering
The University of Faisalabad
Step4:
Once the installation is successful as shown in fig.1.16, PyCharm asks you to import settings of
the existing package if any.
Figure 1.16
User Interface of PyCharm
Editor The user interface of PyCharm editor is shown in the screenshot given below. Observe
that the editor includes various features to create a new project or import from an existing
project.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.17 1
PyCharm – Understanding Basics:
This chapter will discuss the basics of PyCharm and make you feel comfortable to begin working
in PyCharm editor.
When you launch PyCharm for the first time, you can see in fig. 1.18 welcome screen with
entry points to IDE such as:
 Creating or opening the project
 Checking out the project from version control
 Viewing the documentation
 Configuring the IDE
Recall that in the last chapter, we created a project named demo1 and we will be referring to
the same project throughout this tutorial. Now we will start creating new files in the same
project to understand the basics of PyCharm Editor.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.18
You can see in fig.1.19 snapshot describes the project overview of demo1 and the options to
create a new file. Let us create a new file called main.py.
Figure 1.19
Task #2:
Python WHILELoop:
Python While loop is a control statement that accepts a condition as the input. As long the
condition is True, loop-block statements are executed for each iteration of loop-counter. If you
forget to increment or decrement the counter, you will end up with an infinite loop.
Any infinite loop consumes more RAM (Random Access Memory) and crashes the PC.
The condition of a WHILE loop should yield a Boolean value like True or False. The condition
may contain a number of sub-conditions separated by Boolean operators.
Syntax:
Department of Electrical Engineering
The University of Faisalabad
while condition:
statement1;
statement2;
#end of while
Example:
#program to print numbers 1-10
c=1 #loop counter
while c<=10:
print(c, end=' ')
c = c+1 #incrementing counter
 We execute the code the in fig 1.20.
Figure 1.20
 Run a program andgive outputinfig.1.21.
Figure 1.21
Python WHILEwith BREAK:
Sometimes, it is necessary to come out of a loop based on certain conditions. Hence a BREAK
statement is used in Python to break the While loop (or even FOR loop or any loop).
Once the Python runtime encounters this BREAK statement, the control goes to the first
statement after the While-loop. All the statements below the break statement and within the
While-block are not executed (ignored). A Python Break statement is usually kept inside an IF or
ELSE block.
Syntax:
while condition:
statement1;
break
statement2;
Department of Electrical Engineering
The University of Faisalabad
#end of while
Example:
The below program prints Even numbers up to 20 using a WHILE and BREAK control
statements.
 We execute the code the in fig 1.22.
Figure 1.22
 Run a program and give output in fig. 1.23.
Figure 1.23
Python WHILEwith CONTINUE:
The Python CONTINUE statement is the reverse of the BREAK statement. When the Python
runtime encounters this CONTINUE statement, the control goes back to the beginning of the
loop. So, you should increment or decrement the loop-counter before writing any CONTINUE
statement to avoid infinite loops.
Remember that the Continue statement does not stop or halt the loop. It just instructs to
continue with the next iteration.
Syntax:
while condition:
statement1;
continue;
statement2
#endof while
 We execute the code the in fig 1.24.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.24
 Run a program and give output in fig. 1.25.
Figure 1.25
Else-statements:
An else statement can be combined with an if statement. An else statement contains a block of
code that executes if the conditional expression in the if statement resolves to 0 or a FALSE
value.
The else statement is an optional statement and there could be at the most only
one else statement following if.
Syntax:
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
 We execute the code the infig3.7.
Department of Electrical Engineering
The University of Faisalabad
Figure 1.26
 Run a program and give output in fig. 1.27.
Output:
In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the
amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it
produces the following result.
The elif Statement:
The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be
at the most one statement, there can be an arbitrary number of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case as follows
Department of Electrical Engineering
The University of Faisalabad
 We execute the code the infig3.9.
Figure 3.9
 Run a program and give output in fig. 1.28.
Figure 1.28
Python conditional statemnts (Task 3):
Introduction:
Decision-making is as important in any programming language as it is in life. Decision-making in
a programming language is automated using conditional statements, in which Python evaluates
the code to see if it meets the specified conditions.
The conditions are evaluated and processed as true or false. If this is found to be true, the
program is run as needed. If the condition is found to be false, the statement following the If
condition is executed.
Python has the following conditional statements that are used in decision-making:-
1. If the statement
2. If else statement
3. Nested if statement
4. Switch statement
What is Python If Statement?
Department of Electrical Engineering
The University of Faisalabad
Python if Statement is used for decision-making operations. It contains a body of code which
runs only when the condition given in the if statement is true. If the condition is false, then the
optional else statement runs which contains some code for the else condition.
When you want to justify one condition while the other condition is not true, then you use
Python if else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement
Example 1:
def main():
x,y =2,8
if(x < y):
st= "x is less than y"
print(st)
if __name__ == "__main__":
main()
What happen when “if condition” does not meet?
In this step, we will see what happens when if condition in Python does not meet.
def main():
x,y=8,2
if(x < y):
st= "x isless thany"
print(st)
if __name__ == "__main__":
main()
Department of Electrical Engineering
The University of Faisalabad
How to use “else condition”:
The “else condition” is usually used when you have to judge one statement on the basis of
other. If one condition goes wrong, then there should be another condition that should justify
the statement or logic.
Example:
def main():
x, y = 8, 4
if (x < y):
st = "x is less than y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
Department of Electrical Engineering
The University of Faisalabad
When “else condition” does not work?
There might be many instances when your “else condition” won’t give you the desired result. It
will print out the wrong result as there is a mistake in program logic. In most cases, this
happens when you have to justify more than two statement or condition in a program.
def main():
x, y = 8, 8
if (x < y):
st = "x is less than y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
Department of Electrical Engineering
The University of Faisalabad
Here both the variables are same (8,8) and the program output is “x is greater than y”, which
is WRONG. This is because it checks the first condition (if condition in Python), and if it fails,
then it prints out the second condition (else condition) as default. In next step, we will see how
we can correct this error.
How to use “elif” condition?
To correct the previous error made by “else condition”, we can use “elif” statement. By using
“elif” condition, you are telling the program to print out the third condition or possibility when
the other condition goes wrong or incorrect.
Example:
def main():
x, y = 8, 8
if (x < y):
st = "x is less than y"
elif (x == y):
st = "x is same as y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
Department of Electrical Engineering
The University of Faisalabad
Python List Operations(Task_3):
Python Lists allow us to hold items of heterogeneous types. There are no arrays in Python
unlike in many other popular programming languages. But the Python Lists would be sufficient
for all the requirements where you may need arrays.
In this lab, we will learn how to create a list in Python; access the list items; find the number of
items in the list, how to add an item to list; how to remove an item from the list; loop through
list items; sorting a list, reversing a list; and many more transformation and aggregation actions
on Python Lists.
Given below are some of the most widely used list operations in Python.
Python List Length:
Python List Length represents the number of elements in the list.To get the length of list in
Python, call the python global function len() with the list passed as argument.
You could also use looping statements, like for loop or while loop, to find the number of
elements in a list. But, that would become inefficient, since we have inbuilt function.
Syntax – len(list)
The syntax of len() function to find the list length is as shown below.
n = len(listname)
Example:
List_car = ['Ford', 'Volvo', 'BMW', 'Tesla']
length = len(List_car)
print('Length of the list is :', length)
Code:
Output:
To append or add an item to Python List:
To append or add an item to Python List, use append() function. List.append() function modifies
the list in place and returns None.
Department of Electrical Engineering
The University of Faisalabad
In this labl, we shall learn how to use append() function to append an item at the end of List,
with some example programs.
Syntax – List.append():
The syntax of using append() function with a Python List is given below.
mylist.append(new_element)
where new_item is appended to the list mylist.
Example:
List_cars = ['Ford', 'Volvo', 'BMW', 'Tesla']
#append item to list
List_cars.append('Honda')
print(List_cars)
Output:
Python – Remove an Item from List:
To remove an item from Python List, you can use remove() method on the list with the item
passed as argument.
In this lab, we shall go through examples, to understand how to use remove() function, to
delete an item from the list.
Syntax – remove():
The syntax of remove() method is:
mylist.remove(thisitem)
where thisitem has to be removed from mylist.
The remove() method removes only the first occurrence of the item in the list. The subsequent
occurrences are untouched. At the end of this article, we will also learn to remove all of those
items with a specific value.
Example:
mylist = [21, 5, 8, 52, 21, 87]
item = 5
#Remove the item
mylist.remove(item)
print(mylist)
Code:
Department of Electrical Engineering
The University of Faisalabad
Output:
Create a dictionary froma string:
In this lab, we will be creating a dictionary from a string in python. Dictionary is a very useful
data structure in python and quite often we need to convert a string into a dictionary. This
string is of a dictionary format or similar to it. We will be going through two methods to create
a dictionary from a string.
We will create a dictionary from a string in two different ways.
Using eval() function
One scenario is that the inputted string completely resembles a dictionary object (key value
pair with colon and each pair separated by commas and all the elements inside curly brace).
Then this string can be converted to a dictionary easily using the eval() function.
Example:
str='SEMESTER-IV:'
str1='Cource Title of 4[3+1] credit hours:'
str2="{1:'ELECTRONIC CIRCUIT AND DESIGN',2:'DATA STRUCTURE AND
ALGORITHM',3:'SIGNAL AND SYSTEM'}"
dictionary = eval(str2)
print(str)
print(str1)
print(dictionary[1])
print(dictionary[2])
print(dictionary[3])
 We execute the code the in fig 1.29.
Department of Electrical Engineering
The University of Faisalabad
Figure1.29
 Run a program and give outputinfig.1.30.
Figure1.30

More Related Content

What's hot

RMMM
RMMMRMMM
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manual
pkaviya
 
Metrics for project size estimation
Metrics for project size estimationMetrics for project size estimation
Metrics for project size estimationNur Islam
 
Unit2 Software engineering UPTU
Unit2 Software engineering UPTUUnit2 Software engineering UPTU
Unit2 Software engineering UPTU
Mohammad Faizan
 
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Visualizing Progress.pptx
Visualizing Progress.pptxVisualizing Progress.pptx
Visualizing Progress.pptx
ShanmugapriyaSenthil3
 
Slicing and testing
Slicing and testingSlicing and testing
Slicing and testing
TaegeonLee1
 
Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1
NANDINI SHARMA
 
System programming
System programmingSystem programming
System programming
jayashri kolekar
 
User and Operating System Interface
User and Operating System InterfaceUser and Operating System Interface
User and Operating System Interface
Nusrat Jahan Shanta
 
isl mini project report Akshay
isl mini project report Akshayisl mini project report Akshay
isl mini project report Akshay
AkshayKalapgar
 
Detecting Fake News Through NLP
Detecting Fake News Through NLPDetecting Fake News Through NLP
Detecting Fake News Through NLP
Sakha Global
 
comparison of various sdlc models
comparison of various sdlc modelscomparison of various sdlc models
comparison of various sdlc models
sadaf ateeq
 
C Programming- Features of C language
C Programming-  Features of C languageC Programming-  Features of C language
C Programming- Features of C language
Trinity Dwarka
 
Decomposition technique In Software Engineering
Decomposition technique In Software Engineering Decomposition technique In Software Engineering
Decomposition technique In Software Engineering
Bilal Hassan
 
Market and business drivers for mobile application
Market and business drivers for mobile applicationMarket and business drivers for mobile application
Market and business drivers for mobile application
K Senthil Kumar
 
Software Engineering Practice
Software Engineering PracticeSoftware Engineering Practice
Software Engineering Practice
Research & Development LAB QUEST Nawabshah
 
Coal 11 jumps in Assembly Programming
Coal 11 jumps in Assembly ProgrammingCoal 11 jumps in Assembly Programming
Coal 11 jumps in Assembly Programming
Muhammad Taqi Hassan Bukhari
 
File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.net
Everywhere
 

What's hot (20)

RMMM
RMMMRMMM
RMMM
 
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manual
 
Metrics for project size estimation
Metrics for project size estimationMetrics for project size estimation
Metrics for project size estimation
 
Unit2 Software engineering UPTU
Unit2 Software engineering UPTUUnit2 Software engineering UPTU
Unit2 Software engineering UPTU
 
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
 
Visualizing Progress.pptx
Visualizing Progress.pptxVisualizing Progress.pptx
Visualizing Progress.pptx
 
Slicing and testing
Slicing and testingSlicing and testing
Slicing and testing
 
Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1
 
PAC
PACPAC
PAC
 
System programming
System programmingSystem programming
System programming
 
User and Operating System Interface
User and Operating System InterfaceUser and Operating System Interface
User and Operating System Interface
 
isl mini project report Akshay
isl mini project report Akshayisl mini project report Akshay
isl mini project report Akshay
 
Detecting Fake News Through NLP
Detecting Fake News Through NLPDetecting Fake News Through NLP
Detecting Fake News Through NLP
 
comparison of various sdlc models
comparison of various sdlc modelscomparison of various sdlc models
comparison of various sdlc models
 
C Programming- Features of C language
C Programming-  Features of C languageC Programming-  Features of C language
C Programming- Features of C language
 
Decomposition technique In Software Engineering
Decomposition technique In Software Engineering Decomposition technique In Software Engineering
Decomposition technique In Software Engineering
 
Market and business drivers for mobile application
Market and business drivers for mobile applicationMarket and business drivers for mobile application
Market and business drivers for mobile application
 
Software Engineering Practice
Software Engineering PracticeSoftware Engineering Practice
Software Engineering Practice
 
Coal 11 jumps in Assembly Programming
Coal 11 jumps in Assembly ProgrammingCoal 11 jumps in Assembly Programming
Coal 11 jumps in Assembly Programming
 
File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.net
 

Similar to Lab (1) installation of python

Tutorial_Python1.pdf
Tutorial_Python1.pdfTutorial_Python1.pdf
Tutorial_Python1.pdf
MuzamilFaiz
 
Core python programming tutorial
Core python programming tutorialCore python programming tutorial
Core python programming tutorial
Amarjeetsingh Thakur
 
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
Umar Yusuf
 
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
Umar Yusuf
 
python-handbook.pdf
python-handbook.pdfpython-handbook.pdf
python-handbook.pdf
RaviKumar76265
 
C PROGRAMMING p-2.pdf
C PROGRAMMING p-2.pdfC PROGRAMMING p-2.pdf
C PROGRAMMING p-2.pdf
D.K.M college for women
 
Introduction to python3.pdf
Introduction to python3.pdfIntroduction to python3.pdf
Introduction to python3.pdf
Mohammed Aman Nawaz
 
Django Article V0
Django Article V0Django Article V0
Django Article V0Udi Bauman
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
Celine George
 
Using Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) EnvironmentUsing Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) Environment
Mahmoud Samir Fayed
 
L2 - Install Python.pptx
L2 - Install Python.pptxL2 - Install Python.pptx
L2 - Install Python.pptx
EloAOgardo
 
Python_Module_1.pdf
Python_Module_1.pdfPython_Module_1.pdf
Python_Module_1.pdf
R.K.College of engg & Tech
 
Programming in c_in_7_days
Programming in c_in_7_daysProgramming in c_in_7_days
Programming in c_in_7_days
Ankit Dubey
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
Ramakrishna Reddy Bijjam
 
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
jsievers
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
Rajani S Togarsi
 
Pic microcontroller step by step your complete guide
Pic microcontroller step by step your complete guidePic microcontroller step by step your complete guide
Pic microcontroller step by step your complete guide
Ashraf Said AlMadhoun - Educational Engineering Team
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
Batra Centre
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
cigogag569
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
Student
 

Similar to Lab (1) installation of python (20)

Tutorial_Python1.pdf
Tutorial_Python1.pdfTutorial_Python1.pdf
Tutorial_Python1.pdf
 
Core python programming tutorial
Core python programming tutorialCore python programming tutorial
Core python programming tutorial
 
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
 
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!DESKTOP GUI APP DEVELOPMENT USING PYTHON!
DESKTOP GUI APP DEVELOPMENT USING PYTHON!
 
python-handbook.pdf
python-handbook.pdfpython-handbook.pdf
python-handbook.pdf
 
C PROGRAMMING p-2.pdf
C PROGRAMMING p-2.pdfC PROGRAMMING p-2.pdf
C PROGRAMMING p-2.pdf
 
Introduction to python3.pdf
Introduction to python3.pdfIntroduction to python3.pdf
Introduction to python3.pdf
 
Django Article V0
Django Article V0Django Article V0
Django Article V0
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Using Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) EnvironmentUsing Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) Environment
 
L2 - Install Python.pptx
L2 - Install Python.pptxL2 - Install Python.pptx
L2 - Install Python.pptx
 
Python_Module_1.pdf
Python_Module_1.pdfPython_Module_1.pdf
Python_Module_1.pdf
 
Programming in c_in_7_days
Programming in c_in_7_daysProgramming in c_in_7_days
Programming in c_in_7_days
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
Building Eclipse Plugins and RCP Applications with Tycho - ECE 2012
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Pic microcontroller step by step your complete guide
Pic microcontroller step by step your complete guidePic microcontroller step by step your complete guide
Pic microcontroller step by step your complete guide
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 

Recently uploaded

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
Nettur Technical Training Foundation
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 

Recently uploaded (20)

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdfThe Role of Electrical and Electronics Engineers in IOT Technology.pdf
The Role of Electrical and Electronics Engineers in IOT Technology.pdf
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 

Lab (1) installation of python

  • 1. Department of Electrical Engineering The University of Faisalabad LAB No: 01 Title: Introduction to PyCharm. Objective:  How to download and install IDLE Python and PyCharm.  Codes and results demonstrating the use of conditional statements, loops, lists, dictionaries etc. Introduction: Python is a widely used high-level programming language first launched in 1991. Since then, Python has been gaining popularity and is considered as one of the most popular and flexible server-side programming languages. It isusedfor:  web development (server-side)  software development  mathematics  system scripting. What can Python do?  Python can be used on a server to create web applications.  Python can be used alongside software to create workflows.  Python can connect to database systems. It can also read and modify files.  Python can be used to handle big data and perform complex mathematics.  Python can be used for rapid prototyping or for production-ready software development. 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. Python Syntax compared to otherprogramming languages:  Python was designed for readability, and has some similarities to the English language with influence from mathematics.  Python uses new lines to complete a command as opposed to other programming languages which often use semicolons or parentheses.
  • 2. Department of Electrical Engineering The University of Faisalabad  Python relies on indentation, using whitespace, to define scope; such as the scope of loops functions and classes. Other programming languages often use curly-brackets for this purpose. Download the Python: Step_1: Select the version of to install the Python. Python is available from its website, Python.org. Once there, hover your mouse over the download menu, then over the Windows option, and then click the button to download the latest release in the fig 1.1. Figure 1.1  We select the Add Python 3.9 to PATH and then click on Customize installation.
  • 3. Department of Electrical Engineering The University of Faisalabad Figure 1.2  Thenclickon Next. Figure 1.3
  • 4. Department of Electrical Engineering The University of Faisalabad  Clickon Install forall usersfromthe Advanced Option and then click on Install. Figure 1.4  Then click on install option. Now installation has been started in fig.1.5. figure 1.5  And then close the installation. We can see that our setup was successful.
  • 5. Department of Electrical Engineering The University of Faisalabad Figure 1.6  Verification of our installation on Command Prompt. We can see our installation is complete. Figure 1.7  Interface with the Python Window. Run a print program in fig. 1.8. Figure 1.8 IntroductiontoPyCharm:
  • 6. Department of Electrical Engineering The University of Faisalabad PyCharm is the most popular IDE used for Python scripting language. This chapter will give you an introduction to PyCharm and explains its features. PyCharm offers some of the best features to its users and developers in the following aspects:  Code completion and inspection  Advanced debugging  Support for web programming and frameworks such as Django and Flask. Features of PyCharm: Besides, a developer will find PyCharm comfortable to work with because of the features mentioned below: Code Completion: PyCharm enables smoother code completion whether it is for built in or for an external package. SQLAlchemy as Debugger: You can set a breakpoint, pause in the debugger and can see the SQL representation of the user expression for SQL Language code. Git Visualization in Editor: When coding in Python, queries are normal for a developer. You can check the last commit easily in PyCharm as it has the blue sections that can define the difference between the last commit and the current one. Code Coverage in Editor: You can run .py files outside PyCharm Editor as well marking it as code coverage details elsewhere in the project tree, in the summary section etc. Package Management: All the installedpackagesare displayedwithpropervisual representation.Thisincludeslist of installed packagesand the abilitytosearchand add new packages. Steps Involved: You will have tofollowthe stepsgivenbelowtoinstall PyCharmonyoursystem.These stepsshow the installationprocedure startingfromdownloadingthe PyCharmpackage fromitsofficialwebsite to creatinga newproject. Step1: Download the required package or executable from the official website of PyCharm https://www.jetbrains.com/pycharm/download/#section=windows. Here you will observe two versions of package for Windows as shown fig 1.9 given below:
  • 7. Department of Electrical Engineering The University of Faisalabad Figure 1.9 Note that the professional package involves all the advanced features and comes with free trial for few days and the user has to buy a licensed key for activation beyond the trial period. Community package is for free and can be downloaded and installed as and when required. It includes all the basic features needed for installation. Note that we will continue with community package throughout this tutorial. Here we can see, we have two options in fig.1.10. PyCharm Professional Edition PyCharm Community Edition
  • 8. Department of Electrical Engineering The University of Faisalabad Figure 1.11  Click on Next to continue. Figure 1.12 Step_2:
  • 9. Department of Electrical Engineering The University of Faisalabad Download the community package (executable file) onto your systemand mention a destination folder as shown below:  Click on all the options and then on Next. Figure 1.13 Step3: Now, begin the installation procedure similar to any other software package.
  • 10. Department of Electrical Engineering The University of Faisalabad Figure 1.14  Our Installation is started. Figure 1.15
  • 11. Department of Electrical Engineering The University of Faisalabad Step4: Once the installation is successful as shown in fig.1.16, PyCharm asks you to import settings of the existing package if any. Figure 1.16 User Interface of PyCharm Editor The user interface of PyCharm editor is shown in the screenshot given below. Observe that the editor includes various features to create a new project or import from an existing project.
  • 12. Department of Electrical Engineering The University of Faisalabad Figure 1.17 1 PyCharm – Understanding Basics: This chapter will discuss the basics of PyCharm and make you feel comfortable to begin working in PyCharm editor. When you launch PyCharm for the first time, you can see in fig. 1.18 welcome screen with entry points to IDE such as:  Creating or opening the project  Checking out the project from version control  Viewing the documentation  Configuring the IDE Recall that in the last chapter, we created a project named demo1 and we will be referring to the same project throughout this tutorial. Now we will start creating new files in the same project to understand the basics of PyCharm Editor.
  • 13. Department of Electrical Engineering The University of Faisalabad Figure 1.18 You can see in fig.1.19 snapshot describes the project overview of demo1 and the options to create a new file. Let us create a new file called main.py. Figure 1.19 Task #2: Python WHILELoop: Python While loop is a control statement that accepts a condition as the input. As long the condition is True, loop-block statements are executed for each iteration of loop-counter. If you forget to increment or decrement the counter, you will end up with an infinite loop. Any infinite loop consumes more RAM (Random Access Memory) and crashes the PC. The condition of a WHILE loop should yield a Boolean value like True or False. The condition may contain a number of sub-conditions separated by Boolean operators. Syntax:
  • 14. Department of Electrical Engineering The University of Faisalabad while condition: statement1; statement2; #end of while Example: #program to print numbers 1-10 c=1 #loop counter while c<=10: print(c, end=' ') c = c+1 #incrementing counter  We execute the code the in fig 1.20. Figure 1.20  Run a program andgive outputinfig.1.21. Figure 1.21 Python WHILEwith BREAK: Sometimes, it is necessary to come out of a loop based on certain conditions. Hence a BREAK statement is used in Python to break the While loop (or even FOR loop or any loop). Once the Python runtime encounters this BREAK statement, the control goes to the first statement after the While-loop. All the statements below the break statement and within the While-block are not executed (ignored). A Python Break statement is usually kept inside an IF or ELSE block. Syntax: while condition: statement1; break statement2;
  • 15. Department of Electrical Engineering The University of Faisalabad #end of while Example: The below program prints Even numbers up to 20 using a WHILE and BREAK control statements.  We execute the code the in fig 1.22. Figure 1.22  Run a program and give output in fig. 1.23. Figure 1.23 Python WHILEwith CONTINUE: The Python CONTINUE statement is the reverse of the BREAK statement. When the Python runtime encounters this CONTINUE statement, the control goes back to the beginning of the loop. So, you should increment or decrement the loop-counter before writing any CONTINUE statement to avoid infinite loops. Remember that the Continue statement does not stop or halt the loop. It just instructs to continue with the next iteration. Syntax: while condition: statement1; continue; statement2 #endof while  We execute the code the in fig 1.24.
  • 16. Department of Electrical Engineering The University of Faisalabad Figure 1.24  Run a program and give output in fig. 1.25. Figure 1.25 Else-statements: An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at the most only one else statement following if. Syntax: The syntax of the if...else statement is − if expression: statement(s) else: statement(s)  We execute the code the infig3.7.
  • 17. Department of Electrical Engineering The University of Faisalabad Figure 1.26  Run a program and give output in fig. 1.27. Output: In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it produces the following result. The elif Statement: The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if. Syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows
  • 18. Department of Electrical Engineering The University of Faisalabad  We execute the code the infig3.9. Figure 3.9  Run a program and give output in fig. 1.28. Figure 1.28 Python conditional statemnts (Task 3): Introduction: Decision-making is as important in any programming language as it is in life. Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions. The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed. If the condition is found to be false, the statement following the If condition is executed. Python has the following conditional statements that are used in decision-making:- 1. If the statement 2. If else statement 3. Nested if statement 4. Switch statement What is Python If Statement?
  • 19. Department of Electrical Engineering The University of Faisalabad Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. If the condition is false, then the optional else statement runs which contains some code for the else condition. When you want to justify one condition while the other condition is not true, then you use Python if else statement. Python if Statement Syntax: if expression Statement else Statement Example 1: def main(): x,y =2,8 if(x < y): st= "x is less than y" print(st) if __name__ == "__main__": main() What happen when “if condition” does not meet? In this step, we will see what happens when if condition in Python does not meet. def main(): x,y=8,2 if(x < y): st= "x isless thany" print(st) if __name__ == "__main__": main()
  • 20. Department of Electrical Engineering The University of Faisalabad How to use “else condition”: The “else condition” is usually used when you have to judge one statement on the basis of other. If one condition goes wrong, then there should be another condition that should justify the statement or logic. Example: def main(): x, y = 8, 4 if (x < y): st = "x is less than y" else: st = "x is greater than y" print(st) if __name__ == "__main__": main()
  • 21. Department of Electrical Engineering The University of Faisalabad When “else condition” does not work? There might be many instances when your “else condition” won’t give you the desired result. It will print out the wrong result as there is a mistake in program logic. In most cases, this happens when you have to justify more than two statement or condition in a program. def main(): x, y = 8, 8 if (x < y): st = "x is less than y" else: st = "x is greater than y" print(st) if __name__ == "__main__": main()
  • 22. Department of Electrical Engineering The University of Faisalabad Here both the variables are same (8,8) and the program output is “x is greater than y”, which is WRONG. This is because it checks the first condition (if condition in Python), and if it fails, then it prints out the second condition (else condition) as default. In next step, we will see how we can correct this error. How to use “elif” condition? To correct the previous error made by “else condition”, we can use “elif” statement. By using “elif” condition, you are telling the program to print out the third condition or possibility when the other condition goes wrong or incorrect. Example: def main(): x, y = 8, 8 if (x < y): st = "x is less than y" elif (x == y): st = "x is same as y" else: st = "x is greater than y" print(st) if __name__ == "__main__": main()
  • 23. Department of Electrical Engineering The University of Faisalabad Python List Operations(Task_3): Python Lists allow us to hold items of heterogeneous types. There are no arrays in Python unlike in many other popular programming languages. But the Python Lists would be sufficient for all the requirements where you may need arrays. In this lab, we will learn how to create a list in Python; access the list items; find the number of items in the list, how to add an item to list; how to remove an item from the list; loop through list items; sorting a list, reversing a list; and many more transformation and aggregation actions on Python Lists. Given below are some of the most widely used list operations in Python. Python List Length: Python List Length represents the number of elements in the list.To get the length of list in Python, call the python global function len() with the list passed as argument. You could also use looping statements, like for loop or while loop, to find the number of elements in a list. But, that would become inefficient, since we have inbuilt function. Syntax – len(list) The syntax of len() function to find the list length is as shown below. n = len(listname) Example: List_car = ['Ford', 'Volvo', 'BMW', 'Tesla'] length = len(List_car) print('Length of the list is :', length) Code: Output: To append or add an item to Python List: To append or add an item to Python List, use append() function. List.append() function modifies the list in place and returns None.
  • 24. Department of Electrical Engineering The University of Faisalabad In this labl, we shall learn how to use append() function to append an item at the end of List, with some example programs. Syntax – List.append(): The syntax of using append() function with a Python List is given below. mylist.append(new_element) where new_item is appended to the list mylist. Example: List_cars = ['Ford', 'Volvo', 'BMW', 'Tesla'] #append item to list List_cars.append('Honda') print(List_cars) Output: Python – Remove an Item from List: To remove an item from Python List, you can use remove() method on the list with the item passed as argument. In this lab, we shall go through examples, to understand how to use remove() function, to delete an item from the list. Syntax – remove(): The syntax of remove() method is: mylist.remove(thisitem) where thisitem has to be removed from mylist. The remove() method removes only the first occurrence of the item in the list. The subsequent occurrences are untouched. At the end of this article, we will also learn to remove all of those items with a specific value. Example: mylist = [21, 5, 8, 52, 21, 87] item = 5 #Remove the item mylist.remove(item) print(mylist) Code:
  • 25. Department of Electrical Engineering The University of Faisalabad Output: Create a dictionary froma string: In this lab, we will be creating a dictionary from a string in python. Dictionary is a very useful data structure in python and quite often we need to convert a string into a dictionary. This string is of a dictionary format or similar to it. We will be going through two methods to create a dictionary from a string. We will create a dictionary from a string in two different ways. Using eval() function One scenario is that the inputted string completely resembles a dictionary object (key value pair with colon and each pair separated by commas and all the elements inside curly brace). Then this string can be converted to a dictionary easily using the eval() function. Example: str='SEMESTER-IV:' str1='Cource Title of 4[3+1] credit hours:' str2="{1:'ELECTRONIC CIRCUIT AND DESIGN',2:'DATA STRUCTURE AND ALGORITHM',3:'SIGNAL AND SYSTEM'}" dictionary = eval(str2) print(str) print(str1) print(dictionary[1]) print(dictionary[2]) print(dictionary[3])  We execute the code the in fig 1.29.
  • 26. Department of Electrical Engineering The University of Faisalabad Figure1.29  Run a program and give outputinfig.1.30. Figure1.30