Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

PYTHON PROGRAMING

Python Programming Lab Program


Using Python 3.11

For Automotive Engineering 4rth Year Students

Instructor Name: Mr. Elias P.


Lab Objectives
 To write, test, and debug simple Python programs.
 To use operators in a python program.
 To implement Python programs with conditionals.
 To implement Python programs with loops.
 Use functions for structuring Python programs.
 Represent compound data using Python lists, tuples, and
dictionaries.
Lab Outcomes
Upon completion of the course, students will be able to:
Write, test, and debug simple Python programs.
Use operators in a python program.
Implement Python programs with conditionals.
Implement Python programs with loops.
Develop Python programs step-wise by defining functions and calling
them.
Use Python lists, tuples, dictionaries for representing compound data.
Download and Install Python Setup
Download the setup from the below link
http://python.org/downloads/
Installation steps
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed on Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Introduction to Python
What is python
Python is a popular programming language. It was created in
1991 by Guido Van Rossum.

It is used for
Game development
Web development
Desktop application
Software development
Embedded application
Data analysis
Python First Program
Write python program to display hello world on the screen
i.e print("hello world")
Python Variables
Unlike other programming languages, Python has no command for
declaring variable.
A variable is created at the moment you first assign a value to it.
Example
X=5 # x is now type of int
Y= “Elias” # Y is now type of string
Print(x)
Print(y)
Variables do not need to be declared with any particular type and can
even change type after they have been set.
Python Variables Names
A variable can have a short name (like x and y) or amore descriptive
name like (age, fnam, lname, etc).
Rules for naming Python variables
A variable name must start with letter or underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores(A-Z, 0-9, and _)
A variable names are case sensitive (age, Age and AGE are three
different variables)
Continued
The python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example
X=“Intereting.”
Print(“Python is “+ x)
The output will be
Python is Interesting.
Python Data Types
Write a program to demonstrate different OUTPUT
number data types and string in Python. a is Type of <class ‘int’>
b is Type of <class ‘float’>
INPUT
c is Type of <class ‘complex’>
a=10; #Integer Datatype
b=11.5; #Float Datatype xy is Type of <class ‘str’>
c=2.05j; #Complex Number
xy="Automotive Engineering"
print("a is Type of",type(a)); #prints type of variable a
print("b is Type of",type(b)); #prints type of variable b
print("c is Type of",type(c)); #prints type of variable c
print("xy is Type of",type(xy)); #prints type of variable xy
Reading input from Keyboard
Write a python program that reads input(your full name) from keyboard and
displays the result . Type the following code.
Input
fname=str(input("Please enter your first name :"))
lname=str(input("Please enter your Last name :"))
print("Your full name is" "\n"+fname + " " +lname)
Output
Please enter your first name :ELIAS
Please enter your Last name :PETROS
Your full name is
ELIAS PETROS
ARTHIMETIC OPERATIONS
INPUT OUTPUT
Write a Python Program that accepts two numbers and Enter the first number:24
make d/t arithmetic on it
Enter the second number:13
a = int(input ('Enter the first number:'))
b = int(input ('Enter the second number:')) Addition of a and b is :37
summ=a+b Multiplication of a and b is :312
mul=a*b Division of a and b is :1.8461538461538463
div=a/b Floar Division of a and b is :1
fdiv=a//b
Modulo devision of a and b is :11
modu=a%b
print("Addition of a and b is :" +str(summ))
print("Multiplication of a and b is :" +str(mul))
print("Division of a and b is :" +str(div))
print("Floar Division of a and b is :" +str(fdiv))
print("Modulo devision of a and b is :" +str(modu))
Continued
Continued
Python String Methods and Functions
Python String Methods and Functions
#isalnum() OUTPUT
string= "bbc123" True
print(string.isalnum())
True
#isalpha()(add 2)
string="campus" True
print(string.isalpha()) True
#isdigit() (add a letter) False
string="0123456789"
Arba Minch Univeristy
print(string.isdigit())
string="012345689"
print(string.isnumeric() )
string="Arba minch Sawla Campus"
print(string.istitle())
string="Arba Minch Technology Campus"
print(string.replace('Technology Campus','Univeristy'))
Python String Methods and Functions
Python String Methods and Functions
Write a program to create, concatenate and OUTPUT
print a string and accessing sub-string from a Enter first String: COMPUTER
given string. Enter second String: SCIENCE
INPUT First String is : COMPUTER
s1=input("Enter first String : ");
Second String is : SCIENCE
s2=input("Enter second String : ");
print("First string is : ",s1); Concatenations of two strings :
print("Second string is : ",s2); COMPUTERSCIENCE
print("concatenations of two strings :",s1+s2); Substring of given string: OMP
print("Substring of given string :",s1[1:4]); # prints
string from 1 to 3 because array Indexing starts from
0 and ends at n-1.
Python Conditional (If ) Statement
OUTPUT
Write a python program which accept one integer
It displays a if the entered
number from keyboard then display the number when
number is greater than 0
number is greater than 0 using python if statement. Unless it cant display
INPUT anything.
a = int(input ('Enter the number:'))
if a > 0:

print (a, "is greater than 0")


Python Conditional(If-Else) Statements
OUTPUT
Write a python program which accept two integer
Enter the first number:12
numbers from keyboard then display which number is
Enter the second number:23
greater using python if-else statement.
23 is greater than 12
INPUT
a = int(input ('Enter the first number:'))
b = int(input ('Enter the second number:'))
if a > b:
print (a, "is greater than ", b)
else:
print (b, "is greater than ",a)
Python Conditional(If-Elif- Else ) Statements
OUTPUT
Write a python program which takes numbers from
Please enter the number you
keyboard then display the number is either positive,
want to check ?32
negative or 0 using python if-elif-else statement. The number you entered is
INPUT positive
number=int(input("Please enter the number you want to
check ?"))
if number>0:
print("The number you entered is positive")
elif number<0:
print("The number you entered is negative")
else :
print("The number you entered is zero")
Python Conditional Nested(If-Elif- Else ) Statements

Write a python sources code that accept students score then calculate the
grade of the score?

Note:- Score range and grade were provided as bellow

Score range: Grade :


90-100 ===>A
80-89 ===>B
70-79 ===>C
60-69 ===> D
Below 60 ===>F
Continued
INPUT
OUTPUT
score=float(input("Please enter your score:")) Please enter your score:34
if score>=90: Grade = F
print("Grade = A ")
elif score>=80:
print("Grade = B ")
elif score>=70:
print("Grade = C ")
elif score>=60:
print("Grade = D ")
else :
print("Grade = F ")
Chapter 3 Understanding Python Loops
Iteration (Loops):
A loop statement allows us to execute a statement or group of
statements multiple times as long as the condition is true. Repeated
execution of a set of statements with the help of loops is called
iteration. Loops statements are used when we need to run same code
again and again, each time with a different value.
In python iteration statements there are three types of loops:
1. While loop 2. For loop 3. Nested for loops
Python While Loops
o Loops are either infinite or conditional. Python while loop keeps
reiterating a block of code defined inside it until the desired
condition is met.
o The while loop contains a Boolean expression and the code inside
the loop is repeatedly executed as long as the Boolean expression is
true.
o The statements that are executed inside while can be a single line of
code or a block of multiple statements.
while(expression):
syntax Statement(s)
continued
o Write a python source code which display “Hello World“ six times on
console.
i =1
while i < = 6:
print(“Hello World")
i=i+1
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Python For Loops
Python for loop is used for repeated execution of a group of
statements for the desired number of times. It iterates over the items
of lists, tuples, strings, the dictionaries and other iteratable objects.
o Syntax
for x in iteratable: for x in sequence:
# code to be executed # code to be executed

Or

o where, x is any variable


oiteratable is any object that can be looped over, such as a list,
tuple, or string.
Continued
Example1: Write python source code which Example2: Write python source
code which display each character
display list of items using python for loop.
in the string using python for loop.
fruits =["Apple","Orange","Banana"] for x in "Computer":
for x in fruits: print(x)
print(x) •Output
C
Output
o
Apple m
Orange p
Banana u
t
e
r
Python Range() function
o The range () is a built-in function that returns a range object that consists
series of integer numbers, which we can iterate using a for loop. In
Python, using a for loop with range () , we can repeat an action a specific
number of times.
Syntax for x in range (start, stop, step):

print(x)

where, x is any variable


default value for start is 0
default value for stop is -1
default value for step is 1
Continued
o Example1: Write python source code Example2: Write python source code
which display number from 0 to 4 using which display numbers between 2 up
python for loop. to 10 by jumping 2 steps using python
for x in range (0,5): or for x in range for loop
(5): for x in range (2,11,2):
print(x) print(x) print(x)
Output output Output
0 0 2
1 1 4
6
2 2
8
3 3 10
4 4
break and Continue keyword
break and continue are two control statements in python that are
used to alter the flow of a loop.
o break is used to terminate the loop immediately, even if the loop
condition has not become False or the entire iterable has not been
exhausted. When break is encountered inside a loop, the loop is
exited and the program continues executing from the next statement
after the loop.
The syntax of break statement within while loop is as follows:
While condition:
o Syntax if some_condition:
break
# code to be executed
continued
o Here, condition is the condition that is checked at the start of each
iteration of the while loop. If some_condition evaluates to True, the
break statement is executed and the loop is exited immediately.
Syntax Similarly, the syntax of break statement within for loop is as follows:
for variable in sequence:
if some_condition:
break
# code to be executed
o Here, variable is the variable that takes the value of each item in the sequence one
by one, and the code block following the for statement is executed for each
iteration of the loop. If some condition evaluates to True, the break statement is
executed and the loop is exited immediately.
o Note that the break statement only exits out of the innermost loop that it is
contained within. If the break statement is used within a nested loop, only the
inner loop will be exited, and the outer loop(s) will continue to run.
Continued
Example 1. Write a python source Example2. Write a python source code using break
keyword within for loop
code using break keyword within
numbers = [1, 2, 3, 4, 5]
while loop for number in numbers:
n=5 if number == 3:
while n>0: print("Found 3!")
n=n-1 break
print(number)
if n==2:
print ("Loop ended.")
break Output
print(n) 1
print ("Loop is finished") Output 2
4 Found 3!
Loop ended.
3
Note that the loop ends after we find the number 3, so
Loop is finished the numbers 4 and 5 are not printed.
Continue keyword
o continue is used to skip the current iteration of the loop and
continue with the next iteration. When continue is encountered
inside a loop, the loop immediately jumps to the next iteration,
without executing the remaining statements in the loop body for
that particular iteration.
o The syntax of continue statement within while loop is as
follows:
o syntx wth in while loop Syntax with in
While condition: for variable in sequence:
for loop
if some_condition: if some_condition:
continue continue
# code to be executed # code to be executed
continued
oHere, variable is the variable that takes the value of each
item in the sequence one by one, and the code block
following the for statement is executed for each iteration
of the loop. If some condition evaluates to True, the
current iteration of the loop is skipped and the loop moves
on to the next iteration.
oNote that the continue keyword only skips the current
iteration of the loop, and the loop continues with the next
iteration. If the continue keyword is used within a nested
loop, only the inner loop will skip the current iteration, and
the outer loop(s) will continue to run.
Continued
Example 1. Write a python source code •Example 2. Write a python source code using
using continue keyword within while loop continue keyword within for loop
n=5 numbers = [1, 2, 3, 4, 5]
for number in numbers:
while n>0:
if number == 3:
n=n-1 print("sipping 3!")
if n==2: continue
continue print(number)
print(n) print ("Loop ended.") ended.")
print("Loop is finished") Output Output
4 1
3 2
1 Skipping 3...
4
0
5
Loop is finished
Loop ended.

You might also like