0% found this document useful (0 votes)
3 views40 pages

Learn Python Program 2025

The document provides a comprehensive guide on writing programs in Python, covering essential topics such as Python syntax, operators, data types, and control structures like loops and conditionals. It includes examples of assignment, arithmetic, comparison, and logical operators, as well as input/output operations and formatting. Additionally, it discusses the implementation of payroll calculations based on employee hours and pay rates.

Uploaded by

nseaton
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)
3 views40 pages

Learn Python Program 2025

The document provides a comprehensive guide on writing programs in Python, covering essential topics such as Python syntax, operators, data types, and control structures like loops and conditionals. It includes examples of assignment, arithmetic, comparison, and logical operators, as well as input/output operations and formatting. Additionally, it discusses the implementation of payroll calculations based on employee hours and pay rates.

Uploaded by

nseaton
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

It is Programming Time!!!!

Mr. W. Edwards 1/29/2021


Writing Programs in Python

When preparing to write a well documented Python


program you need know
syntax of the python language
Operators used in python
Data types used in python

Mr. W. Edwards 1/29/2021


PYTHON OPERATORS

❑Operators are used to perform operations on variables and


values.
❑Python divides the operators in the following groups:
➢Assignment operators
➢Arithmetic operators
➢Comparison operators
➢Logical operators

Mr. W. Edwards 1/29/2021


Types of values
Each value in python is called an object.
Each object is of particular type.

There are several data types in python

Accepted Python Data type Comments


value type
Integer int Any whole number ( positive and negative)
float or real float Any whole number with fraction ( positive and
numbers negative)
character chr A single value from ASCII character set
String str Sequence of characters
boolean bool Accept two values - True or False
Mr. W. Edwards 1/29/2021
PYTHON ASSIGNMENT OPERATOR
Assignment operators are used to assign values to variables:

General form : Identifier = expression

Example using assignment operator in python

Width = 10
Num1 = 83
Num2 = 2
Item _Price = 455.99

X = 34
Y=X
Mr. W. Edwards 1/29/2021
PYTHON ARITHMETIC OPERATORS

• Arithmetic
operators are used
with numeric
values to perform
common
mathematical
operations:

Mr. W. Edwards 1/29/2021


Activity
Type of value you will get as a result of some operations.

Addition Result = 83 +2 85
Result = float (54) 54.0
Subtraction Result =83-2 81
Result = int(45.23) 45
Multiply Result = 83 *2 166
Result = abs (-56) 56
Division Result = 83 / 2 41.5
Result = round (46.6) 47
Floor division Result = 83 // 2 41

Modulus Result = 83% 2 1

Exponential Result = 8 ** 2 64
Mr. W. Edwards 1/29/2021
STRING OPERATIONS

• name = ‘Junior’ + ‘ Flemmings ’


• print( name) Junior Flemmings

• Result = str(65.3)
• print ( Result) 65.3

Result = chr(65)
A

Mr. W. Edwards 1/29/2021


+ is used as concatenation
Python has no command for declaring a variable.

A variable is created the moment you first assign a value


to it.

x = 5
y = "John"
print(x)
print(y)

Mr. W. Edwards 1/29/2021


Getting Input
Consider the simple program

item_Name = input (‘ Enter name of the product ‘)

print ( ‘ The product name is ’, item_Name)

prompts the user to enter something


at the keyboard by printing the prompt
string to the screen, and then waits
Mr. W. Edwards for the user to press the Enter key. 1/29/2021
Getting Input with different Data Type
Pseudocode algorithm
OUTPUT “ Enter the age of the student “
INPUT age

Python Programming language


age = input ( “ Enter the age of the student :” )
student_Age = int( age)

student_Age = int (input ( “ Enter the age of the student :” ))

Mr. W. Edwards 1/29/2021


Getting input with different data type
Python PL Code
Pseudocode algorithm
Price = input ( “ Enter the item price :” )
OUTPUT “ Enter the item price : “
item_Price = float( Price)
INPUT item_price

item_Price = float( input ( “ Enter the item price :” ))

Mr. W. Edwards 1/29/2021


input will wait for the user to enter text and then return the result as a string.

foo = input ("Put a message here that asks the user for input")

In the above example foo will store whatever input the user provides.

print("This string will be displayed in the output")


# This string will be displayed in the output
print("You can print \n escape characters too.")
# You can print
# escape characters too.
username = input("Enter username:")
print("Username is: " + username)
Mr. W. Edwards 1/29/2021
Formatting Output

Mr. W. Edwards 1/29/2021


PYTHON COMPARISON OPERATOR

• Comparison
operators are used
to compare two
values:

Mr. W. Edwards 1/29/2021


PYTHON LOGICAL OPERATOR

• Logical operators are used to combine conditional statements:

Mr. W. Edwards 1/29/2021


IF Statements in Python
General Format for if then:
< statements before if statement >
if < condition > :
Indentation
< then statements >
< statement after the if statement >

General Format for if then else:-


< statements before if statement >
if < condition > :
Indentation
< then statements >
else :
Indentation
< else statements >
Mr. W. Edwards < statement after the if statement > 1/29/2021
IF Statements in Python
General Format for nested if :-
< statements before if statement >
if < first condition > :
Indentation <first alternative >

elif < second condition > :


Indentation <second alternative >

elif < third condition > :


Indentation
< third alternative >
else :
Indentation
< catch all alternative >

<statement after the if statement>


Python relies on indentation (whitespace at the
beginning of a line) to define scope in the code

Pseudocode Python Code


a ← 33 a = 33
b ← 200 b = 200
IF ( b > a) THEN if b > a:
OUTPUT "b is greater than a" print("b is greater than a")
ENDIF Print (“ Thank you”)
OUTPUT “ Thank you”

Mr. W. Edwards 1/29/2021


Pseudocode Python Code
a ← 200 a = 200
b ← 33 b = 33
IF ( a > b) THEN if a > b:
OUTPUT “a is greater than b" print(“a is greater than b")
ELSE else:
OUTPUT “b is greater than a" print("b is not greater than a")
ENDIF Print (“ Thank you”)
OUTPUT “ Thank you”

Mr. W. Edwards 1/29/2021


a ← 33 a = 33
b ← 33 b = 33
IF(b > a ) THEN if b > a:
print "b is greater than a" print("b is greater than a")
ELSE IF( a == b) THEN elif a == b:
print "a and b are equal" print("a and b are equal")
ENDIF
ENDIF

a ← 200 a = 200
b ← 33 b = 33
IF ( b > a) THEN if b > a:
print("b is greater than a") print("b is greater than a")
ELSE IF( a == b) THEN elif a == b:
print("a and b are equal") print("a and b are equal")
ELSE else:
print("a is greater than b") print("a is greater than b")
ENDIF
ENDIF 1/29/2021
Mr. W. Edwards
Loops in python

Python make use of two type of loops


➢ while ( indefinite loop)
➢ for ( definite loop )

Mr. W. Edwards 1/29/2021


General Format for while loop:
< statements before loop statement >
while < condition > :
< body of the while loop >
< statement after the while loop >

Mr. W. Edwards 1/29/2021


Pseudocode Python code
LIMIT = 3
LIMIT = 3
count ← 0
WHILE (count <= LIMIT) DO count = 0
PRINT count while count <= LIMIT:
count ← count+1 print(count)
ENDWHILE count = count + 1
PRINT “All done!” print (“ All done! ”)

Loops (repeated steps) have iteration variables that change each


time through a loop. Often these iteration variables go through a
sequence of numbers.
Mr. W. Edwards 1/29/2021
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop

• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
Break statement
With the break statement we can stop the
loop even if the while condition is true:

i = 1 =
while true:
print(i)
i = i + 1
if i == 6:
break
print (“ All done! ”)
No Yes
while True: True ?
line = input('> ')
if line == 'done' :
....
break
print(line)
print('Done!')
break

...

[Link]
print('Done')
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration

while True:
> hello there
line = input('> ')
if line == ‘skip line' : hello there
continue > skip line
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
START
oddCount ← 0
evenCount ← 0
count ←1

WHILE ( count <= 10 )DO


PRINT “Enter next number”
READ number Convert to
IF (number MOD 2 = 0) THEN python
evenCount ← evenCount +1
PRINT “ Even Number”
ELSE
oddCount ← oddCount +1
PRINT “ Odd number”
ENDIF
count ← count +1
ENWHILE
PRINT “ Total odd numbers are ”, oddCount
PRINT “ Total even numbers are”, evenCount
Indefinite Loops

• While loops are called “indefinite loops” because they keep


going until a logical condition becomes False

• The loops we have seen so far are pretty easy to examine to see
if they will terminate or if they will be “infinite loops”

• Sometimes it is a little harder to be sure if a loop will terminate


Definite Loops
Iterating over a set of items…

Mr. W. Edwards 1/29/2021


Definite Loops
• Quite often we have a set of items of the lines in a file -
effectively a finite set of things

• We can write a loop to run the loop once for each of the items in
a set using the Python for construct

• These loops are called “definite loops” because they execute an


exact number of times

• We say that “definite loops iterate through the members of a set”


General Format for … in loop:
< statements before loop statement >
for <variable> in < sequence>:
< body of the for loop >

< statements after loop statement >

For … in loop is very adaptive. You can use it with any sequence
type ( list, string, tuple)
We will be focus on using indexing with a range function

Mr. W. Edwards 1/29/2021


The range( ) Function

To loop through a set of code a specified number of times, we


can use the range() function,
The range() function returns a sequence of numbers
starting from 0 by default, and increments by 1 (by default),
and ends before a specified number.

The range function has a start stop and step

Start at zero Increment


by default the count by
End before the 1 by default
specified
number
Mr. W. Edwards 1/29/2021
The following python code will
Given range ( 6) as a sequence
repeat 6 times
type. A range of numbers in
sequence will be returned
for x in range(6):
print(x) 1. What will be the first number x
receive from range of 6 ?
What will be printed from the 0 by default
above python code?

0 2. What will be the last number x


receive from range of 6 ?
1
5
2 3. How did x receive the range of
3 numbers to get to the last number ?
4 (By default)- Increment each number by 1
5
Mr. W. Edwards 1/29/2021
Range function Range function can
be given as follows
range ( 6)
range ( start, stop, step ) range (0,6)
range (0,6,1)

I need to write a for


Start at 0 loop that repeat 10
by default Increment in
step of 1 by times starting at 1.
when not
given default when Which of the following
not given range statements is TRUE

Stop before
the given a. Range(10)
value b. Range (1,10)
c. Range (1, 11,2)
d. Range ( 1,11,1)
Mr. W. Edwards
1/29/2021
Pseudocode
Start
PRINT “ Enter a positive number”
INPUT num
FOR index ← 1 to 12 DO Convert the pseudocode into
result ← num * index python code.
print num,“ x ”,index, “=”, result
ENDFOR Python Code
Stop Num = int (input ("Enter a positive number" ))
for index in range (1,13):
result = Num * index
print (Num, "x", index, "=", result)
print("Timetable finish")
Mr. W. Edwards 1/29/2021
A company needs a program to figure its weekly payroll. The input data,
consisting of each employee’s name, pay rate, and hours worked. The program
should prompt the user to input the data for each employee, and determine the
total wages for the week . If employee worked over 4o hours use the formula
pay rate times 40 hours plus (hours worked – 40) times 1 ½ times pay rate to
calculate the total wage otherwise calculate total wage: hours worked times pay
rate. The program should also count and display the total wages for the week
for each employee , and grand total wages for the week, so that the payroll clerk
can transfer the appropriate amount into the payroll account. The program
terminate data entry when the user enter EOF for customer name.

Mr. W. Edwards 1/29/2021


Start
total_Payroll ← 0.0 total_Payroll = 0.0
timeAhalf = 1.5 timeAhalf=1.5 # Variable initialize
emp_count ← 0 emp_count =0
OUTPUT “ Enter employee name ”
INPUT emp_name emp_name = input (“Enter employee name ”)
WHILE emp_name <> “ EOF” while emp_name != “EOF” :
OUTPUT “Enter pay rate ”
rate = input (“Enter pay rate ”)
INPUT pRate
pRate = float (rate)
OUTPUT “ Enter hours worked ”
Hr = input (“Enter hours worked ”)
INPUT hrs_work
hrs_worked = int ( Hr )
IF hrs_work >40 THEN
totWage ← pRate *40 + (hrs_work-40)*timeAhalf *pRate if hrs_worked > 40 :
ELSE totWage = pRate *40+(hrs_work-40)* timeAh
totWage ← pRate * hrs_work else:
ENDIF totWage =pRate * hrs_work
Emp_count ← emp_count +1
emp_count =emp_count+1
total_Payroll ← total_Payroll + totWage
total_Payroll = total_Payroll + totWage
OUTPUT “ The total wage for ”, emp_name,” is $“ , totWage
OUTPUT “ Enter employee name ” print(“ The total wage for ” +emp_name+ “ is $”
INPUT emp_name emp_name = input (“Enter employee name ”)
ENDWHILEMr. W. Edwards
OUTPUT “ The number of employee ”, emp_count, print(“ The number of employee ”,emp_count)
1/29/2021

OUTPUT “The total payroll is $” , total_Payroll print(“ The total payroll is $ ” , total_Payroll)
Stop
total_Payroll = 0.0
timeAhalf=1.5 Write the following python code in
emp_count =0 atom text editor
emp_name = input (“Enter employee name ”)
while emp_name != “EOF” :
rate = input (“Enter pay rate ”)
pRate = float (rate)
Hr = input (“Enter hours worked ”)
hrs_worked = int ( Hr )
if hrs_worked > 40 :
totWage = pRate *40+(hrs_work-40)* timeAhalf* pRate
else:
totWage =pRate * hrs_work
emp_count =emp_count+1
total_Payroll = total_Payroll + totWage
print(“ The total wage for ” +emp_name+ “ is $”,totWage)
emp_name = input (“Enter next employee name or EOF to end”)
print(“ The number of employee ”,emp_count)
print(“ The total payroll is $ ” , total_Payroll)
Mr. W. Edwards 1/29/2021

You might also like