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

ComputerSysAndProgramming_4

Uploaded by

raniaalfiky
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

ComputerSysAndProgramming_4

Uploaded by

raniaalfiky
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Cairo University

Faculty of Graduate Studies for Statistical Research


Department of Computer and Information Sciences

Computer Sys. And Programming


Lec. 4 outline: You’ll find all the information you need here on
Overview of Programming, Basic Program Elements, What Are
Computer and Computing?, An Algorithm Is, Automation, What Is a
Program?, Why Python?, Developing Python Programs, Basic
Elements: Data, ….and

Tarek Aly
01126182476
http://41.32.221.109:8080/DrTarekAly.htm
E-mail: tarekmmmmt@{pg.cu.edu.eg; egyptpost.org; gmail.com; yahoo.com}
Contents
 Overview of Programming
 Basic Program Elements  Library Functions
 What Are Computer and  Library Variables
Computing?
 Variables and
 An Algorithm Is Assignment
 Automation  The docstring
 What Is a Program?  import Statements
 Why Python?  Evaluating Expressions
 Developing Python Programs  Type Conversion
 Basic Elements: Data Functions
 Basic Operations: Arithmetic  Composing Expressions
 Built-In Functions  Getting Help on a
Function

10/2/2023 Computer Sys. And Programming


What Are Computer and
Computing?
 The study of computers (concrete artifacts)
and their uses

 The study of computing (abstract


processes)

 The study of what can be computed


(automated solutions to problems or
Computer Science)
An Algorithm Is . . .
 A description of a series of steps that
leads to the solution of a problem

 Examples:
 Make a pizza from scratch
 Give directions to the soccer field
 Change a flat tire on an automobile
Example: Make Pancakes
1. Beat two eggs
2. Add 2 Tb. brown sugar
3. Add 1/2 cup of milk
4. Add 1 Tb. melted butter
5. Add 1 cup self-rising flour
6. Pour batter onto griddle and cook
until done
Automation
 If we can design an algorithm to
solve a problem . . .

 . . . then we can (in principle) build a


real computer to automate the
solution
What Is a Program?

A program is like an algorithm, but describes


a process that is ready or can be made ready
to run on a real computer

2023-11-09 Computer Sys. And Programming 7/112


Why Python?
Real-world advantages Pedagogical advantages
Relating to the methods and theory of teaching

 Systems programming  Very simple syntax


 Graphical user  Highly interactive
interfaces  Easy to learn and use
 Internet scripting  Extensive libraries of
 Component integration high-level resources
 Database programming  Completely portable,
 Rapid prototyping free, and open source
 Widespread user
(programmer)
community

2023-11-09 Computer Sys. And Programming 8/112


Obtaining Python
 Python was invented by Guido van
Rossum in 1992

 Python comes with most Unix-based


computer systems

 Python for Windows or any other


operating system can be downloaded
from http://www.python.org/

2023-11-09 Computer Sys. And Programming 9/112


Developing Python Programs
 Can experiment with small pieces
interactively in shell mode

 Can compose longer segments with


an editor and run them in script mode

2023-11-09 Computer Sys. And Programming 10/112


Evaluating Python Expressions
in Shell Mode

Read an expression Evaluate it Print the result

2023-11-09 Computer Sys. And Programming 11/112


Basic Elements: Data
 Numbers
 Integers: 3, 77
 Floats: 3.14, .22

 Strings: ‘Hi there!’, “Hi there!”, ‘\n’

 Truth values (Booleans): True, False

2023-11-09 Computer Sys. And Programming 12/112


Basic Operations: Arithmetic
Symbol Meaning Example
+ Addition or concatenation x+y
- Subtraction x-y
* Multiplication x*y
/ or // Division x / y or x // y
% Remainder x%y
** Exponentiation x ** y
2023-11-09 Computer Sys. And Programming 13/112
Built-In Functions
 A function is an operation that expects
zero or more data values (arguments)
from its user and computes and returns
a single data value

 Examples:

abs(-5)

max(33, 66)

2023-11-09 Computer Sys. And Programming 14/112


Library Functions
 A library is a collection of resources, including
functions, that can be imported for use in a
program

 Example:

import math

math.sqrt(2)

2023-11-09 Computer Sys. And Programming 15/112


Variables and Assignment
 Variables are used to name data and other resources

 Instead of typing 3.14 for π, define a variable named pi


to mean 3.14

 Assignment (=) is used to set (or reset) a variable to a


value

pi = 3.14

34 * 34 * pi

 Variables make programs more readable and


maintainable
2023-11-09 Computer Sys. And Programming 16/112
Library Variables
 Typically define standard constants, such as pi and e

 Example:

import math

3 * math.pi

 Or:

from math import pi

3 * pi

2023-11-09 Computer Sys. And Programming 17/112


Script Mode
 Longer programs can be edited and saved to a file and
then run as scripts (synonymous with programs)

 IDLE is a script-mode development environment that can


be used on any computer system

2023-11-09 Computer Sys. And Programming 18/112


Developing a Python Script

IDLE editor
Python source code

Python compiler
Byte code

Inputs from user Python Virtual Machine (PVM)

Outputs to user

2023-11-09 Computer Sys. And Programming 19/112


Terminal-Based Programs
 A terminal allows a user to
 run a program
 view output as text on a screen or in a
window
 enter input as text from the keyboard

 Early computer systems were entirely


terminal-based, modern systems
have added a GUI (graphical user
interface)
2023-11-09 Computer Sys. And Programming 20/112
Structure of Terminal-Based
Programs

Inputs Computations Outputs

docstring

import statements

input statements

computation statements

output statements

Program code goes in a file with a .py extension.


2023-11-09 Computer Sys. And Programming 21/112
The docstring
"""
Author: Ken Lambert
This program does nothing
yet, but just you wait!
"""

Not evaluated, but used to document Python


programs for other programmers

Should appear at the beginning of each file


Just as important as the evaluated code!!!

2023-11-09 Computer Sys. And Programming 22/112


import Statements
import math

print(math.pi)
print(math.sqrt(2))

Imports usually occur before the beginning of


the executable program code

They make available resources from other


Python modules

A module is just a file of Python code

2023-11-09 Computer Sys. And Programming 23/112


import Statements
from math import pi

print(pi)

Alternatively, one can import particular


resources from a given module and then omit
the module qualifier from the reference

2023-11-09 Computer Sys. And Programming 24/112


import Statements
from math import *

print(pi)
print(sqrt(2))

Or, one can import all the particular resources


from a given module and then omit the module
qualifier from all the references

2023-11-09 Computer Sys. And Programming 25/112


Input of Text
input('Enter your name: ')

The input function prints its string argument


and waits for user input.

The function then returns the string of


characters entered at the keyboard.

2023-11-09 Computer Sys. And Programming 26/112


Input of Numbers
int(input('Enter your age: '))

When an integer is expected, you must convert


the input string to an int.

float(input('Enter your hourly wage: '))

When a real number (with a decimal point) is


expected, you must convert the input string to a
float.

2023-11-09 Computer Sys. And Programming 27/112


Simple Assignment Statements
name = input('Enter your name: ')

income = float(input('Enter your income: '))

The = operator evaluates the expression to its


right and sets the variable to its left to the
resulting value.

We use variables to retain data for further use.

Note: = does not mean equals in Python!


2023-11-09 Computer Sys. And Programming 28/112
Syntax Template for
Simple Assignment
<variable> = <expression>

A syntax template expresses a grammar rule in


a language.

The angle brackets enclose the names of


phrases or terms that are defined by other rules.

area = math.pi * radius ** 2


century = 100
squarerootof2 = math.sqrt(2)
2023-11-09 Computer Sys. And Programming 29/112
More on Variables
firstname = input('Enter your first name: ')

Any variable can name any thing.

Variables must begin with a letter or the _ character.

They can contain any number of letters, digits, or _.

Variables cannot contain spaces.

Python is case-sensitive. Use lowercase letters for now.


2023-11-09 Computer Sys. And Programming 30/112
Variable References
x = 10 # x begins as 10
x = x + 1 # x is reset to 11
y = y + x # Error! Can't find value of y

When Python sees a variable in an expression, it must


be able to look up its value.

If a variable has no established value, the program


halts with an error message.

Variables are given values by assignment statements


2023-11-09 Computer Sys. And Programming 31/112
End of Line Comments
x = 10 # x begins as 10
x = x + 1 # x is reset to 11
y = y + x # Error! Can't find value of y

# begins an end of line comment - Python ignores text


from # to the end of line

2023-11-09 Computer Sys. And Programming 32/112


Evaluating Expressions
print(totalincome - deduction * rate)

print((totalincome - deduction) * rate)

print(10 + x * y ** 2)

Expressions are evaluated left to right, unless operator


precedence overrides this order.

Use parentheses to override standard precedence when


necessary.
2023-11-09 Computer Sys. And Programming 33/112
Mixed-Mode Arithmetic
print(5 * 100) # Prints 500

print(5 * 100.0) # Prints 500.0

The value of an expression depends on the types of its


operands.

In general, two ints produce an int, whereas at least


one float produces a float.

Exception: x / y always produces a float.


2023-11-09 Computer Sys. And Programming 34/112
Type Conversion Functions
str(3.72) # Returns'3.72'

float('3.72') # Returns 3.72

int(3.72) # Returns 3

float(3) # Returns 3.0

Each data type has a function to convert values of


some other types to values of that type.

int truncates a float by removing the fractional part.


2023-11-09 Computer Sys. And Programming 35/112
Rounding and Precision
round(3.72) # Returns 4

round(3.72, 1) # Returns 3.7

round(3.729, 2) # Returns 3.73

round’s optional second argument specifies the


number of digits of precision in the fractional part

2023-11-09 Computer Sys. And Programming 36/112


Using Functions
round(3.72) # Returns 4

abs(-5) # Returns 5

math.sqrt(2) # Returns 1.4142135623730951

<function name>(<any arguments>)

A function can have one or more required arguments


and/or some optional arguments

Arguments must be of the appropriate types


2023-11-09 Computer Sys. And Programming 37/112
Composing Expressions
squareofa = a ** 2
squareofb = b ** 2
sumofsquares = squareofa + squareofb
c = math.sqrt(sumofsquares)
print('The hypotenuse is', c)

Use assignment to name the results of computations

2023-11-09 Computer Sys. And Programming 38/112


Composing Expressions
squareofa = a ** 2
squareofb = b ** 2
sumofsquares = squareofa + squareofb
c = math.sqrt(sumofsquares)
print('The hypotenuse is', c)

Use assignment to name the results of computations

c = math.sqrt(a ** 2 + b ** 2)
print('The hypotenuse is', c)

Or just compose the expression and pass it as an


argument to the function
2023-11-09 Computer Sys. And Programming 39/112
Getting the Directory of a Module

>>> import math

>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin',
'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees',
'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp',
'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi',
'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan',
'tanh']

>>>
The dir function returns a list of all of the named
components in a module
2023-11-09 Computer Sys. And Programming 40/112
Getting Help on a Function
>>> import math

>>> dir(math)
['__doc__', '__file__', '__name__', 'acos',
'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf',
'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt',
'tan', 'tanh']

>>> help(math.sqrt)
sqrt(x)

Return the square root of x.


2023-11-09 Computer Sys. And Programming 41/112
Output
print(3, 4) # displays 3 4

print(str(3) + str(4)) # displays 34

print('Hello there\nKen!') # displays two lines

print('Hello there ', end = '') # displays one line


print('Ken')

print always ends output with a newline, unless its


last argument is end = ''

2023-11-09 Computer Sys. And Programming 42/112


Thank You

Let's get started!

2023-11-09 Computer Sys. And Programming 43/112

You might also like