Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Introduction to Programming with Python

February 1, 2023

1 Contents
1.0.1 1. Introduction to Computers and Programming
1.0.2 2. Input, Processing, and Output
1.0.3 3. Decision Structures and Boolean Logic
1.0.4 4. Repetition Structures
1.0.5 5. Functions
1.0.6 6. Files and Exceptions
1.0.7 7. Lists and Tuples
1.0.8 8. More About Strings
1.0.9 9. Dictionaries and Sets
1.0.10 10. Classes and Object-Oriented Programming
1.0.11 11. Inheritance
1.0.12 12. Recursion
1.0.13 13. GUI Programming
1.0.14 14. Database Programming

2 INTRODUCTION
2.1 Different Ways of Using a Computer
2.2 In School
1. Writing papers

2. Searching for articles

2.3 At work
1. Making presentations

2. Communicate with Customers

1
2.4 At Home
1. Shopping online

2. Playing games

2.4.1 N ote :
The uses of computers are almost limitless in our everyday lives.

Computers can perform such a wide variety of tasks because they can be programmed

A program is a set of instructions that a computer follows to perform a task and they
are commonly referred to as sof tware .

Software is essential to a computer because it controls everything the computer does.

2.5 Hardware and Software


Hardware refers to all of the physical devices, or components, of which a computer is
made.

Sof tware

1. System Sof tware programs that control and manage the basic operations of a computer.
Software System typically include the following types

a) Operating Systems

b) Utility Programs

c) Software Development Tools

2. Application Sof tware are programs that make a computer useful for everyday tasks.

2.6 Input and Output Devices


2.7 How Computers Store Data
All the data that is stored in a computer is converted into sequence of 0s and 1s.

2.8 Keywords, Operators and Syntax


Each high-level language has its own set of predefined words that the programmer must use to
write a program. The words that make up a high-level programming language are known as
keywords or reserved words.

2
2.9 Compilers and Interpreters
[1]: # and continue finally is raise
# as def for lambda return
# assert del from None True
# async elif global nonlocal try
# await else if not while
# break except import or with
# class False in pass yield

A compiler is a program that translates a high-level language program into a separate machine
language program.
The Python language uses an interpreter, which is a program that both translates and executes the
instructions in a high-level language program. As the interpreter reads each individual instruction
in the program, it converts it to machine language instructions then immediately executes them.

2.10 Using Python


The Python interpreter can run Python programs that are saved in files or interactively execute
Python statements that are typed at the keyboard. Python comes with a program named IDLE
that simplifies the process of writing, executing, and testing programs.

2.10.1 Installing Python

[2]: print('python programming is fun !')

python programming is fun !

2.11 Input, Processing and Output


Input is data that the program receives. When a program receives data, it usually process it by
performing some operation with it. The result of the operation is sent out of the program as output.

2.12 Displaying Output with the PRINT Function


A f unction is a piece of prewritten code that performs an operation. Python has numerous built-in
functions that perform various operations.
[3]: print('Hello world')

Hello world
Write a python program (output.py) using the print function to display your address.

[4]: print("Godfred Badu")


print("Academic City University Colloge")
print("P.O.Box AD 421")
print("Haatso Accra")
print("Ghana")

3
Godfred Badu
Academic City University Colloge
P.O.Box AD 421
Haatso Accra
Ghana

[5]: print("Godfred Badu \nAcademic City University Colloge\nP.O.Box AD 421\nHaatso,␣


,→Accra\nGhana")

Godfred Badu
Academic City University Colloge
P.O.Box AD 421
Haatso, Accra
Ghana

2.13 Strings and String Literals


A sequence of characters that is used as data is called a string. When a string appears in actual
code of a program, it is called a string literal. In python, string literals must be enclosed with
doublequotes(”...”).
Write a python program (double_quotes.py) using the print function to display your address.

[6]: print("Kate Austen")


print("123 Full Circle Drive")
print("Asheville, NC 28899")

Kate Austen
123 Full Circle Drive
Asheville, NC 28899

[7]: print('Your assignment is to read "Hamlet" by tomorrow.')

Your assignment is to read "Hamlet" by tomorrow.


N ote : Python also allows you to enclose string literals in triple quotes (either ””” or ”’). Triple
quoted strings can contain both single quotes and double quotes as part of the string.
[8]: print("""I'm reading "Hamlet" tonight.""")

I'm reading "Hamlet" tonight.

2.14 Variables
A variable is a name that represents a value in the computer’s memory.

2.15 Creating Variables with Assignment Statements


You use an assignment statement to create a variable and make it reference a piece of data. Here
is an example of an assignment statement:

4
[9]: age = 25
age_carl = 19
AgeCarl = 20

[ ]:

[10]: width = 10;


length = 5;

[11]: print(width)

10

[12]: print(length)

[13]: # This program demonstrates a variable


room = "five hundred and three"
# print(" I am staying in room number")
# print(room)
print("I am staying in room number", room , "on the first floor")

I am staying in room number five hundred and three on the first floor

[14]: #Create two variables: top_speed and distance

top_speed = 160
distance = 300

# Display the values referenced by the variables

print("The top speed is ")


print(top_speed)
print("The distance traveled is ")
print(distance)

The top speed is


160
The distance traveled is
300

[15]: # Displaying Multiple items with the print Function

# This program demonstrates a variable

5
room= 503

print('I am staying in room number', room)

I am staying in room number 503

2.16 Variable Reassignment


Variables are called “variable” because they can reference different values while a program is
running.
[16]: # This program demonstrates variable reassignment.
# Assign a value to the dollars variable.

dollars = 2.75
print('I have', dollars, 'in my account.')

# Reassign dollars so it references


# a different value.
dollars = 99.95
print('But now I have', dollars, 'in my account!')

I have 2.75 in my account.


But now I have 99.95 in my account!

2.17 Reassigning a Variable to a Different Type


[17]: x = 99
print(x)

99

[18]: x = 'Take me to your leader'


print(x)

Take me to your leader

[19]: x

[19]: 'Take me to your leader'

N ote : We use Python’s built-in input function to read input from the keyboard.

variable = input(prompt)
[20]: name = input("what is your name? ")

what is your name? Badu Godfred

6
[21]: print(name)

Badu Godfred

[ ]: # Get the user's first name.

first_name = input("Please enter your first name: ")

# Get the user's last name.

last_name = input("Please enter your last name: ")

# Print a greeting to the user

print("Hello", first_name, last_name)

2.18 Reading Numbers with the input Function


[ ]: string_value = input('How many hours did you work? ')
hours = int(string_value)

# Get the user's name, age and income

name = input('What is your name? ')


age = int(input('What is your age?'))
income = float(input('What is your income'))

# Display the data.


print('Here is the data you entered: ')
print('Name:', name)
print('Age:', age)
print('Income:', income)

2.19 Reading Numbers with the input Function


Python has numerous operators that can be used to perform mathematical calculations.
[ ]: # An addition of 12 and 2

12 + 2

[ ]: string_value = input('How many hours did you work? ')


hours = int(string_value)
pay_rate = 10

hours * pay_rate

7
[ ]: # Assign a value to a salary variable
salary = 2500.00

# Assign a value to a bonus variable


bonus = 1200.0

# Calculate the total pay by adding salary


# and bonus. Assign the result to pay

pay = salary + bonus

# Display the pay


print('Your pay is =', pay)

2.20 Calculation a Percentage


Let’s step through the process of writing a program that calculates a percentage. Suppose a retail
business is planning to have a storewide sale where the prices of all items will be 20 percent off.
We have been asked to write a program to calculate the sale price of an item after the discount is
subtracted. Here is the algorithm:
1. Get the original price of the item.
2. Calculate 20 percent of the original price. This is the amount of the discount.
3. Subtract the discount from the original price. This is the sale price.
4. Display the sale price.
[ ]: # Get the items's original price
original_price = float(input("Enter the item's original price: "))

# Calculate the amount of the discount


discount = original_price * 0.2

# Calculate the sale price


sales_price = original_price - discount

# Display the sales price


print('The sale price is: ', sales_price)

2.21 Floating point and Integer division


Python has two division operators. The “/” operator that performs floating point division and the
“//” operator that performs integer division. Both operators divides on number by another. The
difference between them is that the “/” operator gives the result of a floating-point value, and the
“//” gives the result of a whole number.

[ ]: 5/2

[ ]: 5 // 2

8
[ ]: -5//2

2.22 Calculating an Average


[ ]: # Get three test scores and assign them to the
# test1, test2, and test3 variables.
test1 = float(input('Enter the first test score: '))
test2 = float(input('Enter the second test score: '))
test3 = float(input('Enter the third test score: '))

# Calculate the average of the three scores


# and assign the result to the average variable.
average = (test1 + test2 + test3) / 3.0

# Display the average.


print('The average score is', average)

2.23 The Exponent Operator


Two asterisks written together (∗∗) is the exponent operator, and its purpose is to raise a number
to a power. For example, the following statement raises the length variable to the power of 2 and
assigns the result to the area variable:
[ ]: length = 5
area = length ** 2
area

2.24 The Remainder Operator


The “%” symbol is the remainder operator. (This is also known as the modulus operator). The
remainder operator performs division but instead of returning the quotient, it returns the remainder.
[ ]: leftover = 17 % 3
leftover

A program (time_convertor.py) that gets a number of seconds from a user and it


converts that number of seconds to hours, minutes and seconds.
[ ]: # Get a number of seconds from the user

total_seconds = float(input('Enter a number of seconds: '))

# Get the number of hours.


hours = total_seconds // 3600

# Get the number of remaining minutes


minutes = (total_seconds // 60) % 60

9
# Get the number of remaining seconds
seconds = total_seconds % 60

# Display the results


print('Here is the time in hours, minutes, and seconds: ')
print("Hours: ", hours)
print("Minutes: ", minutes)
print("Seconds: ", seconds)

2.25 Converting Math Formulas to Programming Statements


Suppose you want to deposit a certain amount of money into a savings account and leave it alone
to draw interest for the next 10 years. At the end of 10 years, you would like to have $10,000 in the
account. How much do you need to deposit today to make that happen? You can use the following
formula to find out.

F
P = (1)
(1 + r)n

The terms are as follows:


• P is the present value, or the amount that you need to deposit today.
• F is the future value that you want in the account. (In this case, F is 10,000.)
• r is the annual interest rate.
• n is the number of years that you plan to let the money sit in the account.
[ ]: # Get the desired future value
future_value = float(input('Enter the desired future value: '))

# Get the annual interest rate.


rate = float(input('Enter the annual interest rate: '))

# Get the number of years that the money will appreciate.


years = int(input('Enter the number of years the money will grow: '))

# Calculate the amount needed to deposit.


present_value = future_value / (1.0 + rate)**years

# Display the amount needed to deposit.


print( , present_value)

2.26 Breaking Long Statements into Multiple Lines


Python allows you to break a statement into multiple lines by using the line continuation character,
which is a backslash (). You simply type the backslash character at the point you want to break
the statement, then press the Enter key.

10
[4]: var1 = 2
var2 = 3
var3 = 4
var4 = 1/2

result = var1 * 2 + var2 * 3 \


+ var3 * 4 + var4 * 5
print(result)

31.5
Python also allows you to break any part of a statement that is enclosed in parentheses into multiple
lines without using the line continuation character. For example, look at the following statement:
[5]: print("Monday's sales are", "monday",
"and Tuesday's sales are", "Tuesday",
"and Wednesday's sales are", "Wednesday")

Monday's sales are monday and Tuesday's sales are Tuesday and Wednesday's sales
are Wednesday

2.27 String Concatenation


String concatenation is the appending of one string to the end of another.
[11]: first_word = "Hello"
second_word = "World"
print(first_word, second_word)

full_word = first_word + " "+ second_word


print(full_word)

Hello World
Hello World

2.28 First Assignment


Write a program (concatenation.py) that demonstrates string concentenation by ask-
ing a user to enter his/her first and last names and combines the names with a space
between them and displays the users full name.
[2]: print("Godfred Badu \nAcademic City \nP.O.Box AD 421")

Godfred Badu
Academic City
P.O.Box AD 421

[5]: print('Mon\tTues\tWed')
print('Thur\tFri\tSat')

11
Mon Tues Wed
Thur Fri Sat

[8]: print("Your assignment is to read \"Hamlet\" by tomorrow.")

Your assignment is to read "Hamlet" by tomorrow.

[ ]: print('The path is C:\\temp\\data.')

2.29 Displaying formated Output with F-strings


F − strings or f ormatted string literals are a special type of string literal that allow you to for-
mat values in a variety of ways.
F-strings are much more powerful than regular string literals, however. An f-string can contain
placeholders for variables and other expressions.
[10]: print(f'Hello world')

Hello world

[11]: name = "Johnny"


print(f"Hello { name } {name }.")

Hello Johnny Johnny.

[12]: temperature = 45
print(f'It is currently {temperature} degrees.')

It is currently 45 degrees.

2.30 Placeholder Expressions


In computer programming a placeholder is a character, word, or string of characters that tem-
porarily takes the place of the final data.
[14]: first_val = 3
second_val = 8
third_val = 4
final_value = (first_val + second_val + third_val)/3
print(final_value)

5.0

[ ]: val = 10
print(f'The value is {val + 2}.')

[ ]: first_number = int(input("Please enter your first_number: "))


second_number = int(input("Please enter your second_number: "))

12
third_number = int(input("Please enter your third_number: "))

[ ]: Sum_of_var = first_number + second_number + third_number


print("The sum number of all the three numbers is ",Sum_of_var)

[ ]:

[ ]: vaR = 'Badu Godfred'


print(vaR)

[ ]: user_name = input("Please enter your name : ")


print(user_name)

[ ]: # How long your investment is going to last


num_of_years = float(input("How many years would like your investment to last:␣
,→"))

# What is the investment interest rate


rate = 0.2

# What is your target amount

future_value = float(input("What is your target amount: "))

# Formula for finding the present value for python


present_value = future_value / (1.0 + rate ) ** num_of_years

# Display your present_value


print("The initial amount you need to invest is ", present_value)

[ ]:

13

You might also like