[Go to site: main page, start]

0% found this document useful (0 votes)
8 views37 pages

Python Basics for Problem Solving

Uhbb

Uploaded by

chiamakaf76
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)
8 views37 pages

Python Basics for Problem Solving

Uhbb

Uploaded by

chiamakaf76
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

COS 102: Problem Solving

Using Python Programming


Language (Python Basics)
Dr. Irene N. Ezeasomba
Learning Outcome/Objective
Learning Outcome 6:
 Solve problems using programming language
Objectives: At the end, the student should be able to,
 Understand why we chose Python Programming Language as
our choice of programming language.
 Download and install Python in your system
 Learn Python Programming Language Basic such as:
Comments, Inputs and Output, Data Types, Variables,
Operators and Conditional Statements
 Solve problems using Python programming Language
Why Python?
 Any programming language can be used to demonstrate
problem solving but we will use Python.
 Python is a high-level, general-purpose, and very popular
programming language.
 Python programming language (latest Python 3) is being
used in web development, and Machine Learning
applications, along with all cutting-edge technology in
Software Industry.
 Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram,
Dropbox, Uber… etc.
Python Features
 Simple and Easy to Learn: Python has a simple syntax, which
makes it easy to learn and read. It’s a great language for
beginners who are new to programming.
 Interpreted: Python is an interpreted language, which means
that the Python code is executed line by line. This makes it easy
to test and debug code.
 High-Level: Python is a high-level language, which means that it
abstracts away low-level details like memory management and
hardware interaction. This makes it easier to write and
understand code.
Python Features Cont.
 Dynamic Typing: Python is dynamically typed, which means
that you don’t need to declare the data type of a variable
explicitly. Python will automatically infer the data type based
on the value assigned to the variable.
 Strong Typing: Python is strongly typed, which means that the
data type of a variable is enforced at runtime. This helps
prevent errors and makes the code more robust.
 Extensive Standard Library: Python comes with a large
standard library that provides tools and modules for various
tasks, such as file I/O, networking, and more. This makes it
easy to build complex applications without having to write
everything from scratch.
Python Features Cont..
 Cross-Platform: Python is a cross-platform language, which
means that Python code can run on different operating
systems without modification. This makes it easy to develop
and deploy Python applications on different platforms.
 Community and Ecosystem: Python has a large and active
community, which contributes to its ecosystem. There are
many third-party libraries and frameworks available for various
purposes, making Python a versatile language for many
applications.
 Versatile: Python is a versatile language that can be used for
various purposes, including web development, data science,
artificial intelligence, game development, and more.
Downloading and Installing Python
on Windows 10 and above
 Since Windows doesn’t come with Python preinstalled, it
needs to be downloaded and installed explicitly.
 Steps to Download Python on Windows 10 and above
 Step 1: Open a browser and type [Link]
 Step 2: Click on downloads to see the window below
 Step 3: Click on Download Python 3.12.1 (It will now
download Windows x86-64 executable installer for 64-bit)
 Step 4: Click the downloaded Windows x86-64 executable
installer for 64-bit to install python (check downloaded
files from download icon if you are not seeing it)
Python Download Window
Installing Python

 Make sure to mark Add Python 3.11 to PATH otherwise you will have to
do it explicitly. It will start installing Python on Windows.
 After installation is complete click on Close.
 Congratulations...!! Python is installed
Getting Started with Python
 IDLE comes bundled with every Python installation.
 IDLE means Integrated Development and Learning Environment
 The IDLE shell is the default mode of operation for Python IDLE.
 The best place to experiment with Python code is in
the interactive interpreter, otherwise known as a shell.
 The shell is a basic Read-Eval-Print Loop (REPL). It reads a
Python statement, evaluates the result of that statement, and
then prints the result on the screen. Then, it loops back to read
the next statement
 When you click on the icon to open the program, the shell is
the first thing that you see:
IDLE Shell -An Interactive Interpreter

 IDLE Shell is a blank Python interpreter window.


 You can use it to start interacting with Python immediately. You
can test it out with a short line of code
 I typed “Hello My Dear Students” and pressed enter
 The three greater than >>> sign is called the Python command
prompt, where we write our program and with a single enter
key, it will give results so instantly.
 You can type your own message enclosed in quote.
Restarting IDLE Shell
 You can restart the shell from the >Shell
>Restart Shell menu.
 This clears the state of the shell. It will act as
though you’ve started a fresh instance of
Python IDLE. The shell will forget about
everything from its previous state and act as
though you’ve started a fresh instance of
Python IDLE.
 In the image, you first declare a variable, x = 5.
When you call print(x), the shell shows the
correct output, which is the number 5.
 However, when you restart the shell and try to
call print(x) again, you can see that the shell
prints a traceback. This is an error message
that says the variable x is not defined.
Python IDLE File Editor

 Every programmer needs to be able to edit and save text


files.
 Python programs are files with the .py extension that contain
lines of Python code.
 Python IDLE offers a full-fledged file editor, which gives you
the ability to write and execute Python programs from
within this program.
 To start a new Python file, select File → New File from the
menu bar. This will open a blank file in the editor, as shown:
Creating (Editing) your Python Programs

 From this window, you can write a brand new Python file.
 You can also open an existing Python file by selecting File →
Open… in the menu bar. This will bring up your operating
system’s file browser. Then, you can find the Python file you
want to open.
Creating (Editing) your Python Programs:
 Type this program for written for our algorithm to find the larger
number between A and B in the file editor and save with extension .py
Algorithm:
Read A, B
If A is less than B
BIG=B
SMALL = A
Else
BIG=A
SMALL = B
Display BIG,
SMALL

Don’t worry if you don’t


understanding the code
Executing Your Program file in IDLE
 To execute a file in IDLE, simply press the F5 key on your
keyboard or select Run → Run Module from the menu bar.
 Either option will restart the Python interpreter and then run
the code that you’ve written with a fresh interpreter.
 Type in a value for A when prompted and press enter, Also
type in a value for A when prompted and press enter. The
output will be displayed as shown.
Learning Python Basics
Python Basics
 The python basics we will learn to help us
understand our demonstrate how algorithms are
implemented in any programming language
includes:
Comments
Inputs and Output
Data Types
Variables
Operators
Conditional Statements
Comments

Comments in Python start with the # symbol and are


used to explain code or make notes.
Comments are ignored by the Python interpreter.

Example
# This is a program to solve ….
Output with print() Function
 The print() function is used to display
output in various formats.
 We will just see the basic form.
 Example
Print ("Hello, World!")
Example 2
Output x = 10 # Integer no
y = 3.14 # Float no
Hello, World!
name = "John" # String type
print (x,y,name) #Output
Input with the input() function
 The input() function enables interaction with users by
gathering input during program execution.
Example
# Getting input from a user
num = int(input ("Enter a value: "))
add = num + 5
# Output
print(“The sum is ”, add)

Output when Run


Enter a value: 50
The sum is 55
Data Types in Python
 Data types are the categorization of data items.
 It represents the kind of value that tells what
operations can be performed on a particular data.
 There are many Data types in python such as:
Numeric, Sequence Type, Boolean, Set, Dictionary
and Binary Type.
 For now, we may be needing little of Numeric and
Sequence data types.
Numeric Data Types in Python
 Integers – This value is represented by int class. It
contains positive or negative whole numbers (without
fractions or decimals). In Python, there is no limit to
how long an integer value can be.
 Float – This value is represented by the float class. It
is a real number with a floating-point representation.
It is specified by a decimal point.
 Complex Numbers – A complex number is represented
by a complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
Sequence Data Type in Python
 The sequence Data Type in Python is the ordered
collection of similar or different Python data
types. Sequences allow storing of multiple values
in an organized and efficient fashion.
 The sequence types in Python are String, List and
Tuple. For now we need only the string.
 A string is a collection of one or more characters
put in a single quote, double-quote, or triple-
quote.
 Example in the statement: print (“Hello world”)
 “Hello world” is a string.
Variables
 Variables are used to store data.
 In Python, you don’t need to declare the data
type of a variable explicitly. Python will
automatically infer the data type based on the
value assigned to the variable.
 Variable names must start with a letter or
underscore.
 Can only contain alphanumeric characters and
underscore (A-z, 0-9. and _ )
 Variable names are case sensitive e.g. age, Age
and AGE are three different variables
Operators
 In Python programming, Operators in general are used to
perform operations on values and variables. These are
standard symbols used for the purpose of logical and
arithmetic operations
 OPERATORS: Are the special symbols. Eg- + , * , /, etc
 OPERAND: It is the value on which the operator is applied.
 Operators in Python include:
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Assignment Operators
Arithmetic Operators in Python
 Python Arithmetic operators are used to perform
basic mathematical operations like addition,
subtraction, multiplication, and division.

In Python 3.x the result of division is a floating-point


while in Python 2.x division of 2 integers was an
integer. To obtain an integer result in Python 3.x
floored (// integer) is used

Arithmetic operators used in Java is shown in the


next slide.
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
Division (float): divides the first operand by
/ x/y
the second
Division (floor): divides the first operand by
// x // y
the second
Modulus: returns the remainder when the first
% x%y
operand is divided by the second
** Power: Returns first raised to power second x ** y
Comparison Operators: Returns True or False
Operator Description Syntax
Greater than: True if the left operand is
> x>y
greater than the right
Less than: True if the left operand is less than
< x<y
the right
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
Greater than or equal to True if the left
>= x >= y
operand is greater than or equal to the right
Less than or equal to True if the left operand
<= x <= y
is less than or equal to the right
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR,
and Logical NOT operations. It is used to combine conditional
statements.
Operator Description Syntax

Logical AND: True if both the


and x and y
operands are true

Logical OR: True if either of the


or x or y
operands is true

Logical NOT: True if the operand


not not x
is false
Assignment Operators in Python
Python Assignment operators are used to assign values to the variables.

Operator Description Syntax


Assign the value of the right side
= of the expression to the left side x=y+z
operand
Add AND: Add right-side operand
+= with left-side operand and then a+=b a=a+b
assign to left operand
Subtract AND: Subtract right
-= operand from left operand and a-=b a=a-b
then assign to left operand
Conditional Statements
 What are Conditional Statements?
 Conditional Statements are statements in that provide a
choice for the control flow based on a condition.
 It means that the control flow of the program will be
decided based on the outcome of the condition.
 Conditional Statement in Python include: If, If else,
Nested if..else , If-elif-else and Ternary Expression
Conditional Statements.
 We will Look at If and If else conditional statements.
If Conditional Statement
 If the simple code of block is to be performed if the
condition holds then the if statement is used. Here the
condition mentioned holds then the code of the block
runs otherwise not
 Syntax of If Statement:
 if condition:
# Statements to execute if
# condition is true
 Example
# if statement example
if 10 > 5:
If else Conditional Statements
 In a conditional if Statement the additional block
of code is merged as an else statement which is
performed when if condition is false
 Syntax of Python If-Else:
 if (condition): Example
# if..else example
# Executes this block if
# condition is true x = 3
else: if x == 4:
# Executes this block if #Do this
# condition is false else:
#Do this
PROGRAM TO FIND LARGER OF TWO NUMBERS
# Program to find larger of two numbers
# Taking input from the user
A = int(input("Enter a value for A: "))
B = int(input("Enter a value for B: "))
big: int We now understand
small: int and can write the
# checking the Larger number
if A < B: python solution to
big = B our algorithm in
small = A
else: our previous lesson
big = A
small = B
# Output
print ("The larger number is :", big)
print("The Smaller number is :", small)
Summary
Thanks and Remain
Blessed

You might also like