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

Meeting3-Block 1-Part 2-Introduction To Python

The document provides an introduction to Python programming. It discusses why Python is a useful programming language as it is object-oriented, free, portable, powerful, and has automatic memory management. It then describes Python's interactive and script modes for programming. Key concepts covered include variables, data types, operators, input/output functions, and conditional statements like if. The document uses examples to demonstrate how to write, run, and document simple Python programs.

Uploaded by

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

Meeting3-Block 1-Part 2-Introduction To Python

The document provides an introduction to Python programming. It discusses why Python is a useful programming language as it is object-oriented, free, portable, powerful, and has automatic memory management. It then describes Python's interactive and script modes for programming. Key concepts covered include variables, data types, operators, input/output functions, and conditional statements like if. The document uses examples to demonstrate how to write, run, and document simple Python programs.

Uploaded by

baraaa abad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

TM112: Introduction to Computing and

Information Technology 2

Meeting #3
Block 1 (Part 2- Intro)
Introduction to Python

Collected by Dr. Ahmad Mikati 1


Why Python?
Python is object-oriented
• Supports concepts such as polymorphism, operation overloading, and multiple inheritance
It's free (open source)
• Downloading and installing Python is free and easy
• Source code is easily accessible
• Free doesn't mean unsupported! Online Python community is huge
It's portable
• Python runs virtually on major platforms used today
• As long as you have a compatible Python interpreter installed, Python programs will run in exactly the
same manner, irrespective of platform
It's powerful
• Dynamic typing
• Built-in types and tools
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, SciPy)
• Automatic memory management
Monday, November 21, 2
2022
Python IDLE

• IDLE: Integrated DeveLopment Environment


• After installing the IDLE, you can start writing your Python
programs.
Monday, November 3
21, 2022
Programming Modes in Python

• Interactive Mode
• gives you immediate feedback
• Not designed to create programs to be saved and run later

• Script Mode
• Write, edit, save, and run (later)
• Save your file using the “.py” extension

Monday, November 21, 4


2022
Create and run programs in Script Mode
1. Go to the File menu.
2. Make a new file.
3. Give a name for the new file such as:
firstProgram.py and then save with .py
extension.
4. You can now start writing your code.
5. To run your code, save it first and then go to the
run menu  choose run Module or press F5.

Monday, November 21, 5


2022
Python print() Function
The print() function prints the specified message to the screen, or other
standard output device.

The message can be a string, or any other object, the object will be
converted into a string before written to the screen.

print("Hello", "how are you?") Hello how are you?

x = ("apple", "banana", "cherry") ('apple', 'banana', 'cherry')


print(x)

6
Your First Python Program

• Python is "case-sensitive":
• print("hello") #correct
• print('hello') #correct
• Print("hello") #error
• PRINT("hello") #error

• "hello" is called a String expression.


• In Python, String is a series(sequence) of characters
enclosed between " " or ' ‘.
• When the computer does not recognize the statement to
beMonday,
executed,
November 21, a syntax error is generated. 7
2022
String Literals

• String literals in python are surrounded by either single


quotation marks, or double quotation marks.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function.
For example: print("hello").
• Like many other popular programming languages,
strings in Python are arrays of bytes representing
unicode characters.
• However, Python does not have a character data type,
a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the
string.

8
String Literals

Example 1: Get the character at position 1 (remember that the first character
has the position 0):

a = "Hello, World!"
e
print(a[1])

Example 2- Substring: Get the characters from position 2 to position 5


(not included):

b ="Hello, World!" llo


print(b[2:5])

9
Program Documentation

• Comment lines provide documentation about


your program.
• Anything after the “#” symbol is a comment
• Ignored by the computer

# First Python Program


# February 5, 2019

Monday, November 21, 10


2022
Variables

• A variable is a name that refers to a value.


• Variables let us store and reuse values in several places.
• But to do this we need to define the variable and then tell it
to refer to a value.
• We do this using an assignment statement.
• Example:
>>> y = 3
>>> y
3

Monday, November 21, 11


2022
Variables

• You can also assign to multiple names at the same time.

• Example1:
>>> x, y = 2, 3
>>> x
2
>>> y
3

• Example2:
>>> x = 5; y = 4; L = [0,1,2]

Monday, November 21, 12


2022
Variables
• Variable names can contain letters, numbers, and the
underscore (the dollar sign is NOT accepted!).
• Variable names cannot contain spaces.
• Variable names cannot start with a number.
• Variable name cannot be a reserved word.
• Case matters: temp and Temp are different variables.
• There are many reserved words such as:

and, assert, break, class, continue,


def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while
Monday, November 21, 13
2022
Data Types in Python
Python supports four different numerical types:
• int (signed integers):  positive or negative whole numbers with no
decimal point.
• long (long integers ): integers of unlimited size, written like integers
and followed by an uppercase or lowercase L.
• float (floating point real values): real numbers and are written with a
decimal point dividing the integer and fractional parts. Floats may also
be in scientific notation, with E or e indicating the power of 10 (2.5e2 =
2.5 x 102 = 250).
• complex (complex numbers): are of the form a + bJ, where a and b are
floats and J (or j) represents the square root of -1 (which is an imaginary
number). The real part of the number is a, and the imaginary part is b.
Complex numbers are not used much in Python programming.
Monday, November 21, 14
2022
15
Reading from the keyboard
• To read from the keyboard:
x=input(“enter your text” )#Hello Ahmad
print (x)
The output: Hello Ahmad

• For reading values (numbers) from the keyboard we


can use “eval” which converts the string to values.
• Example:
>>x =eval(input(“enter your number”)) #5
>>y =eval(input(“enter your number”)) #10
>>x+y
>> 15
Monday, November 21, 16
2022
Reading from the keyboard

Monday, November 21, 17


2022
Casting in Python

• Python converts numbers internally in an expression


containing mixed types to a common type for evaluation.
• Sometimes, you need to explicitly convert a number from one
type to another. This is called casting.
• int(x) to convert x to a plain integer.
• float(x) to convert x to a floating-point number.
• str() to constructs string from a wide variety of data types, including
strings, integer literals and float literals
• complex(x) to convert x to a complex number with real part x and
imaginary part zero.
• complex(x,y) to convert x and y to a complex number with real
part x and imaginary part y. x and y are numeric expressions.
• long(x) to convert x to a long integer.
Monday, November 21, 18
2022
Casting in Python

>>> x = '100'
>>> y = '-90'
>>> print (x + y)
Since they are strings, x and
100-90 y will be concatenated

>>> print (int(x) + int(y))


10
Since they have been casted, values
of x and y will be added

Monday, November 21, 19


2022
Casting in Python
• Casting to integers:
x=int(input(“enter the value”)) #5
y=int(input(“enter the value”)) #10
x+y = 15

• Casting to floats:
x=float(input(“enter the value”)) #5.0
y=float(input(“enter the value”)) #10.0
x+y = 15.0

• Casting to strings:
x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

Monday, November 21, 20


2022
Math Operators

Can be used
also for string
concatenation:
y="hello"
y=y+“ world!"

Monday, Novemb 21
er 21, 2022
If statement


The general form of an if statement is:
If condition:
block
● Example
if grade >=50:
Needs print “pass”
indentation
• The condition is a Boolean expression
• The block is a series of statements
• If the condition evaluates to true the block is executed
Monday, Novemb 22
er 21, 2022
Indentation-No Braces

• Python relies on indentation, using whitespace, to define


scope in the code. Other programming languages often use
curly-brackets for this purpose.
• All lines must be indented the same amount to be part of the
scope (or indented more if part of an inner scope)
• This forces the programmer to use proper indentation since
the indenting is part of the program!

Monday, November 21, 23


2022
Python Conditions and If statements

Python supports the usual logical conditions from mathematics:


•Equals: a == b
•Not Equals: a != b
•Less than: a < b
•Less than or equal to: a <= b
•Greater than: a > b
•Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly
in "if statements" and loops.
Example:
a = 33
b = 200
if b > a: 24
  print("b is greater than a")
The elif Statement
The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".

Example:
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

Output:
a and b are equal

25
The else Statement
The else keyword catches anything which isn't caught by
the preceding conditions.
Example:
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Output:
a is greater than b

Monday, November 21, 26


2022
Conditional Operators

Monday, November 21, 27


2022
Common Mistakes

Monday, November 21, 28


2022
Exercises
1.Write a program that asks the user to enter a length in
centimeters. If the user enters a negative length, the
program should tell the user that the entry is invalid.
Otherwise, the program should convert the length to
inches and print out the result. There are 2.54 centimeters
in an inch.
2.Ask the user for a temperature. Then ask them what
units, Celsius or Fahrenheit, the temperature is in. Your
program should convert the temperature to the other
unit. The conversion Formulas are:
F = 9C/5 + 32 and C = 5 (F -32) /9

Monday, November 21, 29


2022
Solution of Ex 1:
Exercises
length = float(input(“Enter the length in Centimeters:
"))
if length <0:
print("Length should be positive!!")
else:
inch = length/ 2.54
print(length, “Centimeters is: ",inch," Inches")
Output:
Enter the length in Centimeters : 20
20.0 Centimeters is: 7.874015748031496 Inches
>>>
Note:
• You can use the round function to round the result:
print(length, “Centimeters is: ",round(inch,1)," Inches")
• In this case, the output will be rounded into 1 decimal place:
20.0 Centimeters is: 7.9 Inches
Monday, November 21, 30
2022
Exercises
Solution of Ex 2:
temp = float(input(“Enter the temperature: "))
unit = input(“Enter the unit: C/F: ")
if unit == "C":
fah = 9/5 * temp + 32
print(temp," Celsius is ",fah," Fahrenheit")
else:
cel = 5/9*(temp -32)
print(temp," Fahrenheit is ",cel," Celsius")

Output:
Enter the temperature: 50
Enter the unit: C/F: C
50.0 Celsius is 122.0 Fahrenheit
>>>
Monday, November 21, 31
2022
For Loop
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.

• The structure of a for loop is as follows:

for variable name in range(number of times to repeat ):


statements to be repeated

• Example 1 The following program will print Hello ten times:


for i in range(10):
print('Hello')

Monday, November 21, 2022 32


For Loop
• Example 2 The program below asks the user for a number
and prints its square. It does this three times and then prints:
‘The loop is done’.

The output:
No
indentation
here; so it is
outside the
loop

33
Monday, November 21,
2022
For Loop

--output--
A
B
C
D
C
D
C
D
C
D
C
D
E
Monday, November 21, 34
2022
The range function
• To loop through a set of code a specified number of times, we can
use the range() function.
• The range() function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified
number.

• The value we put in the range function determines how many times
we will loop.
• The range function produces a list of numbers from zero (by
default, unless other is specified) to the value minus one.
• For instance, range(5) produces five values:

0, 1, 2, 3, and 4.
Monday, November 21, 35
2022
The range function

--output--
0
1
2
• Prints the numbers from 0 to 99. 3
.
.
.
.
.
.
.
.
99
Monday, November 21, 36
2022
The range function
Example
• Since the loop variable i, gets increased by 1 each time
through the loop, it can be used to keep track of where we
are in the looping process. Consider the example below:

Monday, November 21, 37


2022
The range function
• If we want the list of values to start at a value other than 0, we can do that by specifying
the starting value.
range(1,5) will produce the list 1, 2, 3, 4.

• Another thing we can do is to get the list of values to go up by more than one at a time
To do this, we can specify an optional step as the third argument.
range(1,10,2) steps through the list by twos, producing 1, 3, 5, 7, 9.

• To get the list of values to go backwards, we can use a step of -1.


range(5,1,-1) will produce the values 5, 4, 3, 2 in that order.
Note that the range function stops one short of the ending value 1.

Monday, November 21, 2022 38


The range function

Here are a few more examples:

Output

Monday, November 21, 39


2022
The range function
Example:
for i in range(1,7):
print (i, i**2, i**3, i**4)

----output----
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
>>>
Monday, November 21, 40
2022
The range function
Here is a program that counts down from 5 and then prints a message:

Output:

Note:
• Python’s print() function comes with a parameter called ‘end’.
• By default, the value of this parameter is ‘\n’ (the new line character).
• You can end a print statement with any character or string using this parameter.

Monday, November 21, 41


2022
The while loop

• We have already learned about for loops, which allow us to repeat


things a specified number of times.
• Sometimes, though, we need to repeat something, but we don’t
know ahead of time exactly how many times it has to be repeated.
For instance, a game of Tic-tac-toe keeps going until someone wins
or there are no more moves to be made, so the number of turns
will vary from game to game.
• This is a situation that would call for a while loop.

Monday, November 21, 42


2022
The while loop
While statements have the following basic structure:

while condition:
action

As long as the condition is true, the while statement will execute the action.

Example:
x = 1
while x < 4: # as long as x < 4...
print x**2 # print the square of x
x = x+1 # increment x by +1
--output--
1 # only the squares of 1, 2, and 3 are printed, because
4 # once x = 4, the condition is false
9
Monday, November 21, 43
2022
The while loop
The following while and for loops are equivalent

• (They have the exact same effect):


--output--
0
1
2
3
4
5
6
7
8
Monday, November 21,
2022 9 44
The while loop
Pitfall to avoid:

• While statements are intended to be used with changing


conditions.
• If the condition in a while statement does not change, the
program will be in an infinite loop until the user hits ctrl-C.

Example:
x = 1
while x == 1:
print('Hello world‘)
# so-called Infinite loop! Python will keep printing
# “Hello world” because x does not change

Monday, November 21, 45


2022
The while loop

• The optional else clause runs only if the loop


exits normally (not by break)

x = 1
---output---
while x < 3 :
1
print (x)
2
x = x + 1 hello
else:
print ('hello')

Monday, November 21, 46


2022
The break Statement
With the break statement we can stop the loop even if the
while condition is true:

• Now, consider this case with break


x = 1 --output--
while x < 5 : 1
print (x)
x = x + 1
break
else :
print ('got here')

Monday, November 21, 47


2022
The continue Statement
With the continue statement we can stop the current iteration, and
continue with the next.

Comparison between break and continue


Example:
Exit the loop when i is 3: Continue to the next iteration if i is 3:
break continue
i = 1 i = 0
while i < 6: while i < 6:
  print(i)   i += 1 
  if i == 3:   if i == 3:
    break     continue
  i += 1   print(i)
1 1
2 2
3 4
5 48

6
Functions & Returns

• abs(x) The absolute value of x: the (positive) distance


between x and zero.
• ceil(x) The ceiling of x: the smallest integer not less than x
• cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
• exp(x) The exponential of x: ex
• fabs(x)The absolute value of x after converting x to float if it can
(if it can’t it throws an exception).
• floor(x)The floor of x: the largest integer not greater than x
• log(x)The natural logarithm of x, for x> 0
• log10(x) The base-10 logarithm of x for x> 0
Monday, November 21, 49
2022
Functions & Returns
• max(x1, x2,...) The largest of its arguments: the value closest
to positive infinity
• min(x1, x2,...) The smallest of its arguments: the value closest
to negative infinity
• modf(x) The fractional and integer parts of x in a two-item tuple.
Both parts have the same sign as x. The integer part is returned as a
float.
• pow(x, y) The value of x**y.
• round(x [,n]) x rounded to n digits from the decimal point.
Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and
round(-0.5) is -1.0.
• sqrt(x) The square root of x for x > 0
Monday, November 21, 50
2022
Functions & Returns

• Some of the previous functions are built-in into the language


like pow() and abs().
• consider the following example:
x = -10
--output--
print (abs(x))
10
print (pow(x,2))
100
print (pow(x,3))
y = 2.67 -1000
print (round(y)) 3
print (round(y,1)) 2.7

Monday, November 21, 51


2022
Functions & Returns

• Other function are not built-in and require you to import the
math library.

import math --output--


x = 9 3.0
print(math.sqrt(x)) 7
y = 7.4 8
print(math.floor(y))
print(math.ceil(y))

Monday, November 21, 52


2022

You might also like