0% found this document useful (0 votes)
75 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 free, open source, portable, powerful and supports object-oriented programming. It describes the Python IDLE integrated development environment and the interactive and script modes for programming in Python. It also covers basic Python concepts like variables, data types, operators, input/output functions, casting and comments. Examples are provided throughout to demonstrate key Python syntax and features.

Uploaded by

Husam Naser
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 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 free, open source, portable, powerful and supports object-oriented programming. It describes the Python IDLE integrated development environment and the interactive and script modes for programming in Python. It also covers basic Python concepts like variables, data types, operators, input/output functions, casting and comments. Examples are provided throughout to demonstrate key Python syntax and features.

Uploaded by

Husam Naser
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

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
Wednesday, July 07, 202 2
1
Python IDLE

• IDLE: Integrated DeveLopment Environment


• After installing the IDLE, you can start writing your Python
programs.
Wednesday, July 07, 3
2021
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

Wednesday, July 07, 202 4


1
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.

Wednesday, July 07, 202 5


1
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 be
executed, a syntax error is generated.
Wednesday, July 07, 202 7
1
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-1


(character in position 5 is 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


# September 30, 2019

Wednesday, July 07, 202 10


1
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

Wednesday, July 07, 202 11


1
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]

Wednesday, July 07, 202 12


1
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
Wednesday, July 07, 202 13
1
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.
Wednesday, July 07, 202 14
1
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
Wednesday, July 07, 202 15
1
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 construct 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.
Wednesday, July 07, 202 16
1
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

Wednesday, July 07, 202 17


1
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'

Wednesday, July 07, 202 18


1
Math Operators
Name Meaning Example Result
+ Addition 34 + 1 35
Can be used
also for string - Subtraction 34.0 - 0.1 33.9
concatenation:
y="hello" * Multiplication 300 * 30 9000
y=y+“ world!"
/ Float Division 1/2 0.5

// Integer Division 1 // 2 0

** Exponentiation 4 ** 0.5 2.0

% Remainder 20 % 3 2
Wednesday, July 19
07, 2021
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
Wednesday, July 07, 20
2021
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!

Wednesday, July 07, 202 21


1
Python Conditions and If statements

Python supports the usual logical conditions from mathematics:


•Equals: a == b
•Not Equal: 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: 22
  print("b is greater than a")
The elif Statement
The elif keyword is a python’s 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

23
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

Wednesday, July 07, 202 24


1
Conditional Operators

Wednesday, July 07, 202 25


1
Common Mistakes

Wednesday, July 07, 202 26


1
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

Wednesday, July 07, 202 27


1
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
Wednesday, July 07, 202 28
1
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
>>>
Wednesday, July 07, 202 29
1
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')

Wednesday, July 07, 2021 30


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

31
Wednesday, July 07, 202
1
For Loop

--output--
A
B
C
D
C
D
C
D
C
D
C
D
E
Wednesday, July 07, 202 32
1
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.
Wednesday, July 07, 202 33
1
The range function

--output--
0
1
2
• Prints the numbers from 0 to 99. 3
.
.
.
.
.
.
.
.
99
Wednesday, July 07, 202 34
1
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:

Wednesday, July 07, 202 35


1
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.

Wednesday, July 07, 2021 36


The range function

Here are a few more examples:

Output

Wednesday, July 07, 202 37


1
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
>>>
Wednesday, July 07, 202 38
1
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.

Wednesday, July 07, 202 39


1
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.

Wednesday, July 07, 202 40


1
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
Wednesday, July 07, 202 41
1
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
Wednesday, July 07, 202
9 42
1
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

Wednesday, July 07, 202 43


1
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')

Wednesday, July 07, 202 44


1
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')

Wednesday, July 07, 202 45


1
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 46

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
Wednesday, July 07, 202 47
1
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
Wednesday, July 07, 202 48
1
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

Wednesday, July 07, 202 49


1
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))

Wednesday, July 07, 202 50


1

You might also like