0% found this document useful (0 votes)
10 views

Heba Programming1 Book-First Part

Uploaded by

elkassas380
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)
10 views

Heba Programming1 Book-First Part

Uploaded by

elkassas380
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
You are on page 1/ 67

Structure Programming 1 with Python

3
Prepared by: Dr. Heba El Hadidi

2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

• Introduction
What is a computer?

▪ Hardware (Processor, Memory, I/O units)


▪ Software (System Software, Application Software, PL)

What does a Computer work?

It executes instructions fast. How? With software, i.e. Programs.

Programming …… is giving a set of instructions to a computer to execute.

Program

Program is a set of logically ordered instructions (statements) to perform specific


task.

Today computer programs are being used in almost every field, household,
agriculture, medical, entertainment, defense, communication, etc.

❖ Applications of Computer Programs

- Computer Programs is used in graphics and movie making.

- Examples of Computer Programs are MS Word, MS Excel, Adobe Photoshop,


Internet Explorer, Chrome, etc.

- Computer programs are used in our mobile phones for SMS, Chat, and voice
communication.

Program Statements
Program statement is an instruction written in high level PL to do a specific task
in a program.

Page 2 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

There are 3 types of programming statements:

1. Simple statement: it is a single line expression used to carry out an


assignment, calculation or test a logical decision.
Ex., x=1; assign integer 1 to variable x, y>=30 logical statement
checks whether y is greater than or equal to 30.
2. Compound statement: statement consists of 2 or more instructions.
Ex., A=x**y two statements: multiplication and assignment.
3. Control statement: A statement that controls the flow of program
execution. 3 types: sequence, selection and iteration (repetition).

Programming Languages (PL)


PL is a tool to write programs (codes- instructions for computers to follow). For
example, java, Python, c#, c++, vBasic, Algol, Ada, F#, …

Although many languages share similarities, each has its own syntax. Once a
programmer learns the languages rules, syntax, and structure, they write the
source code in a text editor or IDE. Then, the programmer often compiles the
code into machine language that can be understood by the computer.

➢ Machine Language (low level)


➢ Assembly Language (middle level)
➢ High Level PLs

Compiler and Interpreter.


• Computers “think” in binary — strings of 1s and 0s.
• PLs allow us to translate the 1s and 0s into something that humans can
understand and write.

Page 3 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

• A PL is made up of a series of symbols that serves as a bridge that allow


humans to translate our thoughts into instructions computers can
understand.

Programming languages classifications:

1. High level programming languages

▪ closer to how humans communicate.


▪ closer to the words we use in our everyday lives.
▪ This means they’re easier to program in than low-level programming
languages,
▪ although they do take more time to translate into machine code for the
computer.
▪ Python-Java-JavaScript-C#- R- C++- PHP- Kotlin- Swift

2. Middle Level PLs-Assembly language

• close to machine code.


• Still difficult for humans to read (although they’re still easier to understand
than 1s and 0s).
• faster and more precise control over how the computer will function.

3. Low Level PLs-machine language

❑ closer to machine code, or binary.


❑ Therefore, they’re more difficult for humans to read (1s and 0s).
❑ fast and offer precise control over how the computer will function.

What is a Compiler?

❑ Compilation is the process the computer takes to convert a high-


level programming language into a machine language that the computer can
understand. The software which performs this conversion is called
a compiler.
❑ What is an Interpreter?
❑ What is the difference between Compiler and Interpreter?

Page 4 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Programming Error Types:

When executing programs, errors (bugs) may occur. The process of locating and
correcting bugs is called debugging.

➢ Syntax Errors

Errors caused by the syntax rules of the PL.

ex., ‘;’ missing ‘{‘ missing

Syntax errors are detected by the compiler.

➢ Semantic Errors

Errors impossible to assign a meaning to a program statement. Causes the


wrong output due to wrong calculation or wrong input of data.
A wrong variable doing operations in a wrong order.
Or even just use wrong operator.
Some of these errors are detected by the compiler (static semantic errors) and
some are detected only at runtime (dynamic semantic errors).
Ex:

➢ Logical (Run-time) Errors

Errors which appear during the program execution. ex., division by zero, or
variable assigned a large value beyond its capacity.

Page 5 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Exercise:

Which of the following is a semantic error?

a) Semi-colon forgotten at the statement end.


b) Divide by zero.
c) Forget to divide by 100 when printing a percentage amount..

Which of the following detect the semantic error?

a) The Programmer.
b) The Computer
c) The Compiler/Interpreter
d) The Instructor

Now, you need to understand the following concepts:

• A statement is a single line of code.


• Understand how to declare variables.
• Create conditional statements (e.g., if, elif, and else).
• Learn about data structures like a string, array, or list/tuple.
• Perform loops (e.g., do, for, foreach, goto, and while).
• Learn about packaging common code into functions.
• How to make comments or temporarily disable parts of the code.
• Learn more about algorithms.

Page 6 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

• Introduction to Python
Python is a high-level programming language, commonly used for general
purposes. It was originally developed by Guido van Rossum in 1980s.

- Python is an easy to learn, powerful programming language.

- It has efficient high-level data structures and a simple but effective approach to
object-oriented programming.

- Suitable for beginner to get into programming.

- Readability: Python reads a lot like the English language.

- Operating Systems: Python is easily accessible and can be operated across


different Operating systems, including Linux, Unix, Mac, Windows among others.

- Open Source: Python is "open source”, which means that the developer
community can seamlessly make updates to the code, which are always available
to anyone using Python for their software programming needs.

- Libraries: Python has many libraries.

- Free

Applications areas where python can be applied.


1) Web Applications

Python can be used to develop web applications.

Page 7 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

It provides libraries to handle internet protocols such as HTML and XML, JSON,
Email processing, request, beautiful Soup, Feed parser etc. It also provides
Frameworks such as Django, Pyramid, Flask etc to design and develop web
based applications.

Some important developments are: Python Wiki Engines, Pocoo, Python Blog
Software etc.

2) Desktop GUI Applications

Python provides Tk GUI library to develop user interface in python based


application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on
several platforms. The Kivy is popular for writing multitouch applications.

3) Software Development

Python is helpful for software development process. It works as a support


language and can be used for build control and management, testing etc.

4) Scientific and Numeric

Python is popular and widely used in scientific and numeric computing. Some
useful library and package are SciPy, Pandas, IPython etc. SciPy is group of
packages of engineering, science and mathematics.

5) Business Applications

Python is used to build Bussiness applications like ERP and e-commerce


systems. Tryton is a high level application platform.

Page 8 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

6) Console Based Application

We can use Python to develop console based applications. For


example: IPython.

7) Audio or Video based Applications


Python is awesome to perform multiple tasks and can be used to develop
multimedia applications. Some of real applications are: TimPlayer, cplay etc.

8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full
features of CAD.

9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise
or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.

10) Applications for Images


Using Python several application can be developed for image. Applications
developed are: VPython, Gogh, imgSeek etc.

How to write your Python code?


You can interact with Python with:
➢ the Python command shell, which is also called the Python Interpreter
or Console. A shell or console is just a window on your computer that you
use to issue written commands. The standard Python interactive shell uses
the prompt >>>
➢ Other ways of interacting with Python, such as IDLE, Jupyter Notebooks,
Spyder, Pysharm, VSCode,…

Structured Programming in Python


Page 9 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Structured programming is a program written with only the three


constructions sequence, decision (if..elif statements),
and repetition (while or for statements).

1- Sequence. Lines or blocks of code are written and executed in sequential


order.

EX:

x=5

y = 10

z=x+y

print(z)

2- Decision. Execute a block of code (action) if a condition is true. The block of


code is executed at most once.

3- Repetition (Looping)

Repeat a block of code (action) while a condition is true. There is no limit to the
number of times that the block can be executed.

Ex:
n=1

Page 10 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

while n < 100:

print(n)

n = n +1

Indentation in Python

Python doesn't allow the use of parentheses for the block. Instead, indentation is
used to declare a block. If two statements are at the same indentation level, then they
are the part of the same block.

Indentation enhances the code readability.

# nothing to print

Page 11 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Python as calculator
Python can do simple arithmetic. For example, 2+2 is a simple arithmetic
expression.

Not all expressions are numerical, for example, 5 > 7 is an expression that
evaluates to the Boolean value False.

Expressions can become more complex by combining many operations and


functions. For example, 5 * (3 + abs(-12) / 3) in this example the functions are
executed in the following order: abs , / , + , * . operator precedence

Calculate remainder of 17 divide by 3 17 % 3 Output: 2

Binary arithmetic operations in Python

Operation Symbol Example Out


Addition + 10+6 16
Subtraction - 10-6 4
Multiplication * 10*6 60

Page 12 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Division / 10/6 1.6666667


Floor division // 10//6 1
Remainder % 10%6 4
Exponentiation ** 10**6 1000000

Note:
12 .*3 =36.0
5**0.5 =2.23606797749979

Page 13 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

11. /5. = 2.2


11. // 5. 2.0
11. % 5. 1.0

Python Assignment Operators


= Assigns the right operand to the left operand x=5

+= Adds the right operand to the left operand and x+=2 x=7

places the result in the left operand.

-= subtracts the right operand to the left operand and x-=3 x=4

places the result in the left operand.

*= multiplies the right operand by the left operand and x*=2 x=8

places the result in the left operand.

/= divides the left operand by the right operand and x/=2 x=4

places the result in the left operand.


Page 14 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

%= divides the left operand by the right operand and x%=3 x=1

places the remainder in the left operand.

**= Determines the exponential of left operand raised to the power of the right
operand and places the result in the left operand (2*x)**=2 x=4

//= Divides the left operand by the right operand and places the integer result in
the left operand x//=3 x=1

Page 15 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Python Membership Operators


In operator: Determines whether the value in the left operand appears in the
sequence found in the right operand.

Page 16 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

not in operator: Determines whether the value in the left operand is missing
from the sequence found in the right operand.

Python Identity Operators


Is operator: Gives True if the type of the value or expression in the right operand
points to the same type in the left operand.

Is not operator: Gives True if the type of the value or expression in the right
operand points to a different type in the left operand.

Commenting
- In computer programming, a comment is a programmer readable explanation
or annotation in the source code of a computer program. They are added with the
purpose of making the source code easier for humans to understand, and are
generally ignored by compilers and interpreters.

- In Python, # or hashtag is used to declare it as a comment.


- For example:
# print(2 + 2)

Output: Nothing because it is a comment.

Page 17 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Python -print blank lines

Variable in Python

- The problem with previous examples is the value calculated is not stored in the
memory. If you are trying to work out some math problem without a computer,
then you need a paper. Same in programming.

So if you want to use it again, then you need to type the formula again.

- To overcome this problem, variable is used.

- Assign the value to the variable.

We store information in variables. In Python, a variable is created by an


assignment statement. That is a statement of the form:
variable_name = value

- For example:
X=10
Y=”Heba”

Page 18 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Height = 142
Width = 34
- The variable is Height with value 142, second variable is Width with value 34
a= 23
p, q= 83.4, 2**0.5

The equal sign “=” is the assignment operator. In the first statement,
it creates an integer a (object) and assigns it a value of 23. In the second
statement it creates two floating point numbers p and q and assigns them
the values of 83.4 and 1.4142135623730951, respectively.

Note:

Case sensitive

Example:

firstName=”Heba”

SurName=”Hamed”

fullName=firstName+” “ + SurName # Concatenation????

Example:

FirstName=”Heba”

SurName=”Hamed”

fullName=firstName+” “ + surNam # Concatenation????

# Is there error???

Page 19 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Multiple assignments: a = b = c = 1

The order of evaluation is very important. Having the right side evaluated first
means that assignments like x = x + 1 make sense, because the value of x
doesn’t change until after x + 1
is evaluated. Incidentally, there is a shorthand for this kind of update: x += 1 .
There are similar notations for -= , *= , and /= .

Page 20 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Page 21 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

- To assign a formula to a variable

- For example:
Area = Height * Width
print(Area)

variables Height and Width is used to calculate Area. i.e., the value is stored in
variable Area.

Variable is a name which is used to refer memory location. Variable also known
as identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a type
infer language and smart enough to get variable type.

Variable names can be a group of both letters and digits, but they have to begin
with a letter or an underscore.

It is recommended to use lowercase letters for variable name.

User_Name and user_name are two different variables. Python is case


sensitive.

In python:

X=Y=Z=10 is correct (multiple assignment).

Also,

Assigning multiple values to multiple variables:


Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15

Page 22 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Importing Modules:
import numpy as np
import math #import all the module
from numpy import log #import part of the module
from numpy import log, sin, cos
from numpy import *

Example 1: Write program to print “Hello, world!”


# This program prints Hello, world!

print('Hello, world!')

Output
Hello, world!

Note:

A string is a sequence of characters. In Python, strings are enclosed inside single


quotes, double quotes, or triple quotes.

Example 2: Write program to add two numbers

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


# assignment

sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Output
The sum of 1.5 and 6.3 is 7.8

>>> print(‘Hello', 30, 82.2)


Hello 30 82.2
>>> print(‘HELLO', 30, 82.2, sep=',’)
‘HELLO', 30, 82.2

Page 23 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

>>> print(‘HELLO', 30, 82.2, sep=',', end='!!\n’)


‘HELLO', 30, 82.2!!

You can re-declare Python variables even after you have declared once.

swapping numbers in Python is as easy as writing (a, b)= (b, a).

Identifier Naming

Variables are the example of identifiers.

An Identifier is used to identify the literals used in the program.

The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).

o All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore or digit (0-9).

o Identifier name must not contain any white-space, or special character (!, @,
#, %, ^, &, *).

o Identifier name must not be similar to any keyword defined in the language
(not reserved words).

Page 24 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

o Identifier names are case sensitive for example myname, and MyName is not
the same.

• Examples of valid identifiers : a123, _n, n_9, etc.


• Examples of invalid identifiers: 1a, n%4, n 9, etc.

Spaces are not allowed in variable names. No other character that is not a
letter or a number is permitted.
Although variable names can start with the underscore character, you should
avoid doing so in most cases. Variables beginning with an underscore are
generally reserved for special cases.
Remember:
Python is case sensitive, so the variable b is distinct from the variable B.
In [14]: distance = 34.
In [15]: time_traveled = 0.59
In [16]: velocity = distance/time_traveled
In [17]: velocity
Out[17]: 57.6271186440678
x="hi"
print (x)

print(x+str(99)) # hi99

# delete variable
x="hi"
print (x)

del(x)
print(x) # Error
xx=input("Press Key")

------------------

# variable
a=3

Page 25 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

print (a)

x= 3+4
print(x)
xx=input("Press Key")
# ends the output with a <space>
print("Welcome to" , end = ' ')
print("Egypt", end = ' ')
Welcome to Egypt PS C:\Users\HP>

# ends the output with a <space>


print("Welcome to" )
print("Egypt", end = ' ')
Welcome to

# ends the output with '@'


print("Python" , end = '@')
print(“Egypt")

Page 26 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example 3: Write a program to add two numbers entered by the user.

# input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8

Page 27 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Note input and output Python functions are:

input( ) enters string

print()

Example:
# To Use Time and date library
from datetime import *
dob=int(input(“Enter your birth date:” ))
today= datetime.today()
year= today.year
age= int(year) – int(dob)
print (“Your age= {age}”)

Exercise Calculate BMI using Python


Formula for BMI:
BMI = (Weight / (Height x Height))
All values must be assigned to the variables.
Hint:
- Assign the value to Height and Weight variable
- Then make a formula and assign it to BMI variable
- There are many ways you can do to calculate BMI
Exercise

1. Display “My Name is Ahmed” as “My**Name**Is**Ahmed” using print( )


function print('My', 'Name', 'Is', ‘Ahmed', sep='**’)
2. What is the output of:
number = 1 + 2*3/4.0
print(number)

3. Write a program that takes the radius of a sphere (a floating-point number)


as input and outputs the sphere’s diameter, and volume.
4. If π/4= 1-1/3+ 1/5- 1/7 + ……

Page 28 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Write a program that allows the user to specify the number of iterations used in
this approximation and displays the resulting value.

5. Write Python code to calculate the circumstance and area of a circle.

6. Write Python code to calculate the circumstance and area of many circles.

7. Write Python code to:

- print a list of choices as:

1- circle 2- square 3- triangle 4- rectangle

- calculate the circumstance and area of the chosen shape.

8. What is the output of:


number = 11%3
print(number)

9. What is the output of:


squared= 7**2
Cubed= 2**3
print(squared)
print(Cubed)
10. A ball is thrown vertically up in the air from a height h0 above the ground at an
initial velocity v0. Its subsequent height h and velocity v are given by the equations
h = h0 + v0t - 1/2 gt2
v=v0 -gt
where g = 9:8 is the acceleration due to gravity in m/s2. Write a program to find
the height h and velocity v at a time t after the ball is thrown. Start by setting h0 =
1:6 (meters) and v0 = 14:2 (m/s) and have your script print out the values of height
and velocity. Then use the script to find the height and velocity after 0.5 seconds.
Then modify your script to find them after 2.0 seconds.

11. Consider the quadratic equation of the form: ax2+bx+c=0 and has two
solutions given with the formula:
−𝑏 ± √𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎
Where a,b and c are inputs, print the numerical value of the two solutions x.

Page 29 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Number Data Type in Python

Python supports integers, floating-point numbers and complex numbers. They are
defined as int, float, and complex classes in Python.

Integers and floating points are separated by the presence or absence of a decimal
point. For instance, 5 is an integer whereas 5.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.

type() function is used to know which class a variable or a value belongs to and
isinstance() function to check if it belongs to a particular class.

a=5

print(type(a))

print(type(5.0))

c = 5 + 3j
print(c + 3)

print(isinstance(c, complex))

output:

<class 'int'>
<class 'float'>
(8+3j)
True

Exercise

Write a program that take as input:


- Name - Age - Height - Weight
-Then, display all the information

Page 30 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Python Data Types:


bool immutable (True/False)
byte array mutable byte series
bytes immutable
complex immutable complex number 3+2.7j
dict mutable dictionary {‘key1’:1.0, 3: False} { }
float immutable 1.41 math.nan math.inf math.pi
frozenset immutable c
int immutable integer 42
list mutable [list of different types values] [4, 2.0, ‘heba’, True] []
NoneType immutable None = there is no value
range immutable range(10) range(1, 10) range(10, -5, -2)
set mutable {4.0, True, ‘heba’} set()
str immutable ‘Hello’ “Hello” “””…….””” For multiLines
tuple immutable (4, 2.0, ‘hi’, True) ()

Notes:

Some Python keywords:


Keyword Function
break Loop go out
continue Skip current count loop, continue for the next count loop
pass No operation (when you need an empty block)
assert ‫أثناء تصحيح األخطاء للتأكد من الشروط التي يجب تطبيقها‬
yield I
import To call a library or module

Type Conversion
print(1 + 2.0) #3.0
print(int(2.3)) #2
print(int(-2.8)) #-2
print(float(5)) #5.0
print(complex('3+5j')) #(3+5j)
print((1.1 + 2.2) == 3.3) #False

Page 31 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example 4: print the square Roots

# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output The square root of 8.000 is 2.828

Example 5: print the square Roots for real or complex

# Find square root of real or complex numbers


# Importing the complex math module
import cmath

num = 1+2j

# To take input from the user


#num = eval(input('Enter a number: '))

num_sqrt = cmath.sqrt(num)
print('The square root of {0}is
{1:0.3f}+{2:0.3f}j'.format(num,num_sqrt.real,num_sqrt.imag))
Output
The square root of (1+2j) is 1.272+0.786j

If we want to take complex number as input directly, like 3+4j, we have to use the
eval() function instead of float().

Notes:

print(bool(4 > 2)) # Returns True as 4 is greater than 2


print(bool(4 < 2)) # Returns False as 4 is not less than 2
print(bool(4 == 4)) # Returns True as 4 is equal to 4
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality
doesn't holds
print(bool(4)) # Returns True as 4 is a non-zero value
print(bool(-4)) # Returns True as -4 is a non-zero value

Page 32 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

print(bool(0)) # Returns False as it is a zero value


print(bool('dskl')) # Returns True as the string is a non-zero value
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
print(bool([])) # Returns False as list is empty and equal to 0
according to truth value testing

>>> print(True)

True

>>> print(True or False)

True

>>> print(True and False)

False

>>>

The assignment operator can be used to increment or change the value of a variable.

In [3]: a = a+1
In [4]: a
Out[4]: 24

The statement, a = a+1 makes no sense in algebra, but in Python (and most computer
languages), it makes perfect sense: it means “add 1 to the current value of a and assign
the result to a.”

In [7]: c
Out[7]: 6
In [8]: c *= 3
In [9]: c
Out[9]: 18
In [10]: d /= -2
Page 33 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

In [11]: d
Out[11]: -3.96
In [12]: d -= 4
In [13]: d
Out[13]: -7.96
Example:
# Calculates time, gallons of gas used, and cost of
# gasoline for a trip
distance = 400. # miles
mpg = 30. # car mileage
speed = 60. # average speed
costPerGallon = 2.85 # price of gas

time = distance/speed
gallons = distance/mpg
cost = gallons*costPerGallon

Example 6: Evaluate triangle area, where

s = (a+b+c)/2 , a,b,c are the triangle sides


area = √(s(s-a)*(s-b)*(s-c))

The code:

# Python Program to find the area of triangle

a = 5
b = 6
c = 7

# OR
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output
Page 34 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

The area of the triangle is 14.70

Example 7: Solve quadratic equation, where

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

The solution is given by:

(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

a = 1
b = 5
c = 6

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))


Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

Example 8: Convert kilometers to miles, 1 kilometer is equal to 0.621371 miles

# Taking kilometers input from the user


kilometers = float(input("Enter value in kilometers: "))

# conversion factor
conv_fac = 0.621371

# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Output

Page 35 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Enter value in kilometers: 3.5


3.50 kilometers is equal to 2.17 miles

Exercise: Modify the example 8 to convert miles to kilometers using the following
formula.

kilometers = miles / conv_fac

Example 9: Generate a random number

# Program to generate a random number between 0 and 9

# importing the random module


import random

print(random.randint(0,9))
Output 5

Example 10:

import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))

Output
3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720

Page 36 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example 11:

import random

print(random.randrange(10, 20))

x = ['a', 'b', 'c', 'd', 'e']

# Get random choice


print(random.choice(x))

# Shuffle x
random.shuffle(x)

# Print the shuffled x


print(x)

# Print random element


print(random.random())
Output
18
e
['c', 'e', 'd', 'b', 'a']
0.5682821194654443

Note:

If u have the 3 variables x,y,z

Expression x+y+z/3
Or

x+y+(z/3)

Or

(x+y+z)/3???

Page 37 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Strings in Python
- Strings is enclosed in quotes and special character are escaped with
backslashes.
- For example: print(“Is it true?‟)
Output: Is it true?
print(“Isn\‟t it true?‟) # it has backslash before the quotes, It means that the quote is a special character.

Output: Isn‟t it true?

Strings can be assigned variable names


a = "My dog's name is"

Page 38 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

b = "Bingo"
c=a+""+b
print(c)
# Out: "My dog's name is Bingo"
d = "927"
e = 927

- Previous example just show how to print the output in one line. How to about to
print an output that has multiple lines?

- Using “\n‟ to print a new line


- For example:
nama = “Muhammad\nAhmad\nBin \nAli‟
print(nama)
- Strings also can do concatenate by using plus symbol
- For example:
First_name = “Muhammad‟
Last_name = “Ali‟
Full_name = First_name +
Last_name
print(Full_name)
So, we can combine two variables of strings. But the result does not have space
between them.
- To include it, just add space between them.
- Example:
Full_name = First_name + “ “ + last_name
- So you want to calculate how many characters in your name?
- Using function named len
- Example:
Length_name =
len(full_name)
- The value length is including space

Page 39 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Exercise
Create variables first name and last name2, then combine it to full name3
Print the name4
Calculate the length of characters for full name, taking input from user
Note:
- Sometimes you need to make a program that need to take an input from the
user.
- For that purpose, you cannot simply assign the value, since it depends on the
user to key in.
- Example of taking an input using python:
Name = input(“Please input your name: ‟)
- We use input function to take the input. You can write any strings between the
bracket and quotes.
- But if you want to take an input integer or float, then we need to casting
(transform) it into integer or float.
- By default, input function will take the input as a String.
- Example:
Height = float(input(„Height: „))
Number_of_car =
int(input(„Number of car: „))
Exercise for Input
- Make a program that taking input for:
- Name
- Age
- Height
- Weight
- Display all the information

-----------------------------------------------------------------------------------------------------

Write a Python program which accepts the radius of a circle from the user and
compute the area.

Page 40 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example:

Get the volume of a sphere with radius 6 V = 4/3 × π × r3

pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V)

Example:

Input an integer n and compute the value of n+ nn + nnn

n = int(input("Input an integer : ")) # 5


n1 = int( "%s" % n )
n2 = int( "%s%s" % (n,n) )
n3 = int( "%s%s%s" % (n,n,n) )
print (n1+n2+n3)

Selection in Python (Control Flow)


Create decisions with different forms of if..else statement.

- Selection is a situation where we need to choose or select something based on


circumstances.

if test expr: # TRUE- statements execute

Statement(s)

test expr #FALSE- statement not execute

Page 41 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example:

TestMe = 6
if TestMe == 6:
print("TestMe does equal 6!")
print("All done!")
Example:

A=3

B=20

If B> A:

Print(“B is greater than A”)

# Remember the identation

Example:

a= 3

b= 20

if b> a:

print(“b “)

Page 42 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

elif b==a:

print(“b=a”)

else:

print(“A”)

Example:

Value = int(input("Type a number between 1 and 10: "))

if (Value > 0) and (Value <= 10):

print("You typed: ", Value)

- For example, grade A will be given to the student IF the student‟s mark get
more than 80%
- Example in Python:
if mark >= 80:
grade = “A‟
elif mark >= 60:
grade = “B‟
elif mark >= 50:
grade = “C‟
else:
grade = “D‟

Page 43 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Page 44 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

if <test expression>:
statements1 (body of if)
else:
statements2 (body of else)

If …..else

Page 45 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

print("1. Red")
print("2. Orange")
print("3. Yellow")
print("4. Green")
print("5. Blue")
print("6. Purple")
Choice = int(input("Select your favorite color: "))
if (Choice == 1):
print("You chose Red!")
elif (Choice == 2):
print("You chose Orange!")
elif (Choice == 3):
print("You chose Yellow!")
elif (Choice == 4):
print("You chose Green!")
elif (Choice == 5):
print("You chose Blue!")
elif (Choice == 6):
print("You chose Purple!")
else:
print("You made an invalid choice!")
Example:
X = int(input("Type a number between 1 and 10: "))
Y = int(input("Type a number between 1 and 10: "))
if (X >= 1) and (X <= 10):
if (Y >= 1) and (Y <= 10):
print("Your secret number is: ", One * Two)
else:
print("Incorrect second value!")
else:
print("Incorrect first value!")

Page 46 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

If …elif..else

Page 47 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Page 48 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

from random import randint


num=randint(1, 10)
guess= eval(input(‘Enter your guess: ‘))
if guess==num:
print(‘You got it….’)
else:
print(‘Sorry, The number is ‘, num)

Exercise:
Guess name

Example:
#This code to enter a number then test if it is positive or negative
num=int(input('Enter a number '))
if num>0:
if num %3==0:
print('The number is positive and divisble by 3 ')
else:
print('The number is positive and Non-divisble by 3 ')
elif num==0:
print('Zero number')
else:
print('negative')

Exercise:
Write a Python code to check if a number is divisible by 3 and 5.

Write a Python code to check if a number is divisible by 3 or 5.

Page 49 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

? operator and if use:


C? x : y → x if c else y

Example:
Mark=int(input(“Enter your mark: “))
if Mark >=60:
print(‘Pass- Good)
Mark=int(input(“Enter your mark: “))
if Mark >=60:
print(‘Pass- Good’)
else:
print(‘Fail- Good Luck next time’)
Mark=int(input(“Enter your mark: “))
if Mark <=100 and Mark >=60:
print(‘Pass- Good’)
else:
print(‘Fail- Good Luck next time’)

Mark=int(input(“Enter your mark: “))


if Mark <=100 and Mark >=90:
print(‘Pass- A’)
elif Mark<90 and Mark>=80:

Page 50 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

print(‘Pass-B’)
elif Mark<80 and Mark>=70:
print(‘Pass-C’)
elif Mark <70 and Mark >=60:
print(‘Pass-D’)
else:
print(‘Fail- Good Luck next time’)

Home work
1- Write python code to check a number, positive or zero or negative. If the
number is positive: check if it is even or not.
Even: divisible by 2
Hint: use nested if statement
2- Write a Python program to check if a given number is even using user defined
function named Is_Even
3- Write Python program to asks the user for his name and greets him with his name
only for the users Alice and Bob .
4- Write a Python program to Write a program that asks the user for a number n and
prints the sum of the numbers 1 to n
5- Ask the user to enter today’s temperature (T). Then print “very hot” if T>30, print
“hot” if 25<T<=30, print “warm” if 20<=T<=25, print “cold” if 10<T<20, print “very
cold” if 0<T<=10, print “ice” if T<=0.
6- Write Python program to ask the user for a number n and prints the sum of the
numbers 1 to n such that only multiplies of three or five are considered in the sum,
e.g. 3,5,6,9,10,12,15 for n=17
7- Write a Python program to check if a given number is prime.

Page 51 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Looping in Python
- Looping is a situation where we need to repeat the same task for specific times
or infinity

- For example, you want to add numbers from 1 to 10

Note: the word for must be in lowercase.

Example:
print “Hi” 10 times

for k in range(10):
print(‘Hi’)

Page 52 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

for fruit in ["Apple", "Banana", "water mellon", "Peach", "Orange", "Durian", "Papaya"]:
print(fruit)

for i in range(5, 9):


print(i)

5
6
7
8

Page 53 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example:
sum = 0
for number in range(1,11):
sum = sum + number
print(sum)

Page 54 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example:
Program to ask the user for 20 numbers and prints their squares using loop,
then prints that the loop is done.
for k in range(20):
num=eval(input(‘Enter number: ‘))
print(‘The square of your number is: ‘, num*num)
print(‘The loop is done’)

What is the output of:

Page 55 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Print 0 …99:
for j in range(100):
print(j)

Python Primitive DS:

Lists:
Examples:
# Python lists
list1=[]
list2=[1, 2, 3.0, True, 'Hi'] #Different types
# Python lists
colors = ['red', 'blue', 'green']
print(colors[0]) # red
print(colors[2]) #green
print(len(colors)) # 3
# sum list elements
s = [1, 4, 9, 16]
sum = 0
for num in s:
sum += num
print(sum) #30
list=[1,2,3]
list.append(4)
print(list) #[1, 2, 3, 4]
a=[]
a.append('H')
a.append('N') #Nothing
B=[]
B.append(1)
B.append(5)
print(B) #[1, 5]

Page 56 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

#List Sclices
list = ['a', 'b', 'c', 'd']
print(list[1:-1]) ## ['b', 'c']
list[0:2] = 'z' ## replace ['a', 'b'] with ['z']
print(list) ## ['z', 'c', 'd']

my_list = ['p', 'r', 'o', 'b', 'e']

# first item
print(my_list[0]) # p

# third item
print(my_list[2]) # o

# fifth item
print(my_list[4]) # e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])
# p
# o
# e
# a

Page 57 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

# Negative indexing in lists


my_list = ['p','r','o','b','e']

# last item
print(my_list[-1])

# fifth last item


print(my_list[-5])
#e
#p
# Example on Python list methods

my_list = [3, 8, 1, 6, 8, 8, 4]

# Add 'a' to the end


my_list.append('a')

# Output: [3, 8, 1, 6, 8, 8, 4, 'a']


print(my_list)

# Index of first occurrence of 8


print(my_list.index(8)) # Output: 1

# Count of 8 in the list


print(my_list.count(8)) # Output: 3

Page 58 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Tuples:
Examples:

mytuple = ("apple", "banana", "cherry")


tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple1 = ("abc", 34, True, 40, "male")

Page 59 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Page 60 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Page 61 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

range( ) function
• generate a sequence of numbers using range() function.
• range(10) will generate numbers from 0 to 9 (10 numbers)
• also define the start, stop and step size as range(start, stop,step_size).
• step_size defaults to 1.
• range(n) the n value determines how many times we will loop.
• range(5) produces a list of 0,1,2,3,4

Page 62 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

• If u want the list start at a value other than zero, specify the starting value.
• range(1,5) produces 1,2,3,4
• If we want 5 to be included put range(1,6) gives 1,2,3,4,5
• range(1,10,2) –third argument- this function gives 1,3,5,7,9.
• range(10) 0,1,2,3,4,5,6,7,8,9
• range(1,10) 1,2,3,4,56,7,8,9
• range(3,7) 3,4,5,6
• range(2,15,3) 2,5,8,11,14
• range(9,2,-1) 9,8,7,6,5,4,3

Example counts down from 5 then prints a message

Page 63 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Example:
Write Python code to add the prime numbers between 1 and 20 in a list.
# prime numbers less 20 in a list
n = 20
primes = []
for i in range(2, n + 1):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)

print(primes)
## out: [2, 3, 5, 7, 11, 13, 17, 19]

Page 64 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

width = "23"
height = "100"
area = width * height
print(area)

# Rectangle
width = 23
height = 17
area = width * height
print("The area is ", area) # 391
circumference = 2 * (width + height)
print("The circumference is ", circumference) # 80

# Circle
r=7
pi = 3.14
print("The area is ", r * r * pi) # 153.86
print("The circumference is ", 2 * r * pi) # 43.96

Page 65 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

import math

r=7
print("The area is ", r * r * math.pi) # 153.9380400258998
print("The circumference is ", 2 * r * math.pi) # 43.982297150257104

length = int(input('Length: '))


width = int(input('Width: '))

if length <= 0:
print("length is not positive")
if width <= 0:
print("width is not positive")

area = length * width


print("The area is ", area)

Page 66 2022-2023
Structure Programming 1 with Python 3 Dr Heba El Hadidi

Exercises:

1- Print the numbers 5 .....100 using if without looping


2- compute binary representation of a decimal number without looping
3- Convert Celsius temperature into equivalent Fahrenheit using the relation F = C * 9/5
+ 32

Page 67 2022-2023

You might also like