You are on page 1of 56

Computer Programming B(CS101)

“Python”
Python
• Python is a clear and powerful object-oriented programming OOP language, comparable
to Perl, Ruby, Scheme, or Java.
• Python is a general-purpose programming language that is often applied in scripting roles.
Reasons for using python:
✓ Less application development time: Python code is usually 2–10 times shorter than comparable
code written in languages like C/C++ and Java, which means that you spend less time writing your
application and more time using it.

✓ Ease of reading: A programming language is like any other language — you need to be able to read
it to understand what it does

✓ Reduced learning time: The creators of Python wanted to make a programming language with
fewer odd rules that make the language hard to learn

• Books:
• Object-Oriented Programing With Python
• Beginning Programming with Python® For Dummies by John Wiley & Sons, Inc
Downloading & Install Python
• Python itself may be fetched from the downloads page on the website,
http://www.python.org/download. Choose the version according to
platform (windows – linux – mac - ..)
Install with Windows
• The name of this file varies, but normally it appears as python-
3.3.4.msi for 32-bit systems and python-3.3.4.amd64.msi
• Double click on the file the next to finish
Accessing Python
A Windows installation creates a new folder in the Start menu that contains
Python installation. You can access it by choosing Start➪All
Programs➪Python 3.10.0 ➪ IDLE(Python 3.10.0).
The Prompt
>>>
waits for your commands
❑ Print
• Print (‘Hassan ‘s book’) error
• Print (“Hassan ‘s book”) true
• Print (‘ this book titled “python” ’) true
String type str
>>> a = “Book”
>>>Print(a) Book

>>> s = “bo”+”ok” s=“2”+”3”


>>>Print (s) book 23
>>>Type(s) str str
String type
Ask the user to enter string
>>> x=input(“enter your name”)
>>> Print (“hello”, x)
Hello Hassan

Ask the user to enter a value and calculate x+y


>>>x= eval(input(“enter the first number”))
>>>y= eval(input(“enter the scond number”))
Print (x+y)
Labs
First Program: Write a program to print the sum of two numbers

Open python shell


Start -> all programs->python3.8>IDLE
File -> new file
Write the following code in that file
x= eval(input(“enter the first number”))
y= eval(input(“enter the second number”))
print(“sum = “, x+y)

Save the file


Press f5 to run the program
Program: Write a program to calculate average of two numbers

x= eval(input(“enter the first number”))


y= eval(input(“enter the second number”))
print(“ave= “, (x+y)/2)

Quiz: Write a program to calculate area of triangle


L= [10,3.5,”ali”] # define a list
Print(L[0]) 10
Print (L[-1]) ali
Print (L[1]) 3.5
>>> x = [1, 2]
>>> x[0]
1
>>> x[1]
2

>>> a = [1, 2, 3]
>>> b = [4, 5]
>>> a + b
[1, 2, 3, 4, 5]
>>> b * 3
[4, 5, 4, 5, 4, 5]

We can use list slicing to get part of a list.


>>> x = [1, 2, 3, 4]
>>> x[0:2] //display two numbers
[1, 2]
>>> x[1:4]
[2, 3, 4]
>>>List = [1,20,2]
>>>Print(“x= “, max(List)) 20
>>>len(List) 3
>>>List[0] 1
>>>List[:1] [1,20]
>>>List.append(4) [1,20,2,4] # index from 0
>>>List.pop(1) delete the value indexed 1 20
>>>List.sort() [1,2,4,20]
>>>List.remove(4) [1,2,20] delete the value 4
>>>del(List) delete the list

Sorting Lists
The sort method sorts a list in place.
>>> a = [2, 10, 4, 3, 7]
>>> a.sort()
>>> a
[2, 3, 4, 7 10]
List as a matrix
>>>L=[[2,3],[4,5],[6,7]]
>>>L[1] [4,5]
>>>L[1][1] 5
L[0][1] 3
Dictionaries
• Mapping Operations :When written as literals, dictionaries are coded in curly braces and
consist of a series of “key: value” pairs. Dictionaries are useful anytime we need to
associate a set of values
• with keys—to describe the properties of something, for instance. As an example,
consider the following three-item dictionary (with keys “food,” “quantity,” and “color”):
>>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}
>>>D = {‘name': ‘ali', ‘age': 41, ‘work': ‘Lec'}
>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'}
,'job': ['dev', 'mgr'], 'age': 40.5}
>>> print(D['name']) ali
>>>D[‘name’].append(‘ahmed’)
D[‘age’].append(‘30’)
d[‘work’].append(‘eng’)
Tuples
• like a list that cannot be changed
>>>T = (1, 2, 3, 4)
>>>len(T) 4
>>>T[0] 1

• Why Tuples?
• So, why have a type that is like a list, but supports fewer operations?
Frankly, tuples are not generally used as often as lists in practice, but their
immutability is the whole point. If you pass a collection of objects around
your program as a list, it can be changed anywhere; if you use a tuple, it
cannot. That is, tuples provide a sort of integrity constraint that is
convenient in programs larger than those we’ll write here
numbers
+, -, /,*, %, **
>>>print(2**3) 8
>>>print(3%2) 1
== equal , !=not equal , >=, <=

>>> 7 + 2
9
>>> 7 - 2
5
>>> 7 * 2
14
>>> 7 / 2
3
>>> 7 ** 2 7**3??
49
>>> 7 % 2
1
>>>import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871

>>> import random


>>> random.random()
0.59268735266273953
>>> import math
>>> math.pi, math.e # Common constants
(3.1415926535897931, 2.7182818284590451)
>>> math.sin(60) # Sine, tangent, cosine
0.034899496702500969
>>> math.sqrt(144), math.sqrt(2) # Square root
(12.0, 1.4142135623730951)
>>> pow(2, 4), math.pow(2,4) # Exponentiation (power)
(16, 16)
>>> abs(-42.0), sum((1, 2, 3, 4)) # Absolute value, summation
(42.0, 10)
>>> min(3, 1, 2, 4), max(3, 1, 2, 4) # Minimum, maximum
(1, 4)
Exercise
• Swapping values of 2 variables
• Calculate the sum of three values a+b+c
• A=eval(input(“enter n1”))
• Print (“sum=“, a+b+c)
• Calculate the average of three numbers
• What will be the output of the following program
x, y = 2, 6
x, y = y, x + 2
print x, y
Making Simple Decisions
Using the if Statement
• The if statement is used to execute a piece of code only when a
Boolean expression is true.
>>> x = 42
>>> if x % 2 == 0 : print ('even‘)
else: print ('odd’)
>>> x = 42
>>> if x < 10 :
print ('one digit number‘)
elif x < 100 :
print ('two digit number‘)
else:
print(‘big number’)
Program using and with if
>>>x= eval(input(“enter a number between 1 and 10: "))
>>>if (x> 0) and (x<= 10):
print("You typed: ", x)
>>>else:
print("The value you typed is incorrect!")
Write a program for your grade
>>>grade = eval(input('Enter your score: '))
>>>if grade>=90:
>>>print('A')
>>>elif grade>=80:
>>>print('B')
>>>elif grade>=70:
>>>print('C'):
>>>elif grade>=60:
>>>print('D'):
>>>else:
>>>print('F')
• print("1. Red")
• print("2. Orange")
• print("3. Yellow")
• print("4. Green")
• 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!")
• else:
• print("You made an invalid choice!")
>>>if grade>=80 and grade<90:
print('Your grade is a B.')
>>>if score>1000 or time>20:
print('Game over.')
>>>if not (score>1000 or time>20):
print('Game continues.')
Range Function
• The following program will print Hello ten times:
>>>for i in range(10):
>>>print('Hello') # print hello 10 times in different lines
The value we put in the range function determines how many times we
will loop.
range(10) 0,1,2,3,4,5,6,7,8,9
range(1,10) 1,2,3,4,5,6,7,8,9
range(3,7) 3,4,5,6
range(9,2,-1) 9,8,7,6,5,4,3
LOOP
For Loop
>>>for i in range(4):
>>>print('*'*6)

The output:
******
******
******
******
This program that will ask the user for 10
numbers and then computes their average.
>>>s = 0
>>>for i in range(10):
>>>num = eval(input('Enter a number: '))
>>>s = s + num
>>>print('The average is', s/10)
This program will add up the numbers from 1
to 100
>>>s = 0
>>>for i in range(1,101):
>>>s = s + i
>>>print('The sum is', s)
Write a program to square some numbers
>>> s = []
>>> for x in [1, 2, 3, 4, 5]: # This is what a list comprehension does
s.append(x ** 2) # Both run the iteration protocol internally
>>> print(s) #print the list

OUTPUT
[1, 4, 9, 16, 25]
examples
>>>for x in range(2, 30, 3):
>>>print(x)

for x in range(6):
print(x)
else:
print("Finally finished!")
>>>for x in range(6):
>>>print(x)
Output:
0
1
2
3
4
5
While eample
>>>i = 1
>>>while i < 6:
>>> print(i)
>>> i += 1

1
2
3
4
5
while
>>> x = 4
>>> while x > 0:
print('spam!' * x)
x -= 1

OUTPUT
spam!spam!spam!spam!
spam!spam!spam!
spam!spam!
spam!
>>>thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
>>>print(thislist[2:5])
Output:
[cherry", "orange", "kiwi“]

• #This will return the items from position 2 to 5.

• #Remember that the first item is position 0,


• #and note that the item in position 5 is NOT included
Insert an item as the second position:
>>>thislist = ["apple", "banana", "cherry"]
>>>thislist.insert(1, "orange")
>>>print(thislist)

>>>fruits = ['apple', 'banana', 'cherry']


>>>fruits.reverse()
>>>print(fruits)
Write a program to repeat to read a value and
print another value
>>>temp = 0
>>>while temp!=-1000:
>>>temp = eval(input('Enter a temperature (-1000 to quit): '))
>>>print('In Fahrenheit that is', 9/5*temp+32)
Function
• The return statement is used to send the result of a function’s
calculations back to the caller

Example 3 A function can return multiple values as a list.


Say we want to write a function that solves the system of equations ax + b y = e and c x + d y = f .
It turns out that if there is a unique solution, then it is given by x = (de - b f ) / (ad -bc) and
y = (a f - ce) / (ad - bc). We need our function to return both the x and y solutions.

You might also like