SlideShare a Scribd company logo
Introduction to Python
January 2023
Jouda M. Qamar.
Computer Science - Cairo University
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and
modify files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.
Jouda M.Qamar - 2023 2
What is Python?
• Python is a popular programming language.
• It was created by Guido van Rossum, and released in 1991.
Jouda M.Qamar - 2023
The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
______________________________________________
In this tutorial Python will be written in a text editor.
TOOLS:
- python install (https://www.python.org/).
- anaconda (https://www.anaconda.com/).
3
Python Syntax
Python Syntax compared to other programming languages!
• Python was designed for readability.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such
as the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose.
Jouda M.Qamar - 2023 4
Compare between C++ & Python
C++
#include <iostream>
using namespace std;
int main ()
{
int x,y,z;
cin >> x >> y;
z=x+y;
cout << z;
Return0;
} output : value z
Jouda M.Qamar - 2023
Python
x=2
y=3
print(x+y)
output :5
5
Jouda M.Qamar - 2023
Chapter One
Python syntax and Python Variables
6
Python syntax
Writing the first line in Python
print("coding academy!")
_______________________________________________
What is output :
print("Hello, World!")
Output : ------------------
print (“jouda”)
Output : ------------------
print ("23")
Output : ------------------
Build your first program in Python
• Using the Python programming language, draw a triangle shape
print (" /|")
print (" / |")
print (" / |")
print ("/__|")
Output:
Jouda M.Qamar - 2023 8
print (" ________")
print ("| |")
print ("| |")
print ("|________|")
Output:
Python - Variables
• variables are containers for storing data values.
• Creating Variables:
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Jouda M.Qamar - 2023 9
x = 27
y = "jouda"
print(x)
print(y)
Variables do not need to be declared with any particular type,
and can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Python - Variables Cont.
• Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
• Get the Type
You can get the data type of a variable with the type() function:
Jouda M.Qamar - 2023 10
x = 5
y = "John"
print(type(x))
print(type(y))
Python - Variables Cont.
Single or Double Quotes?
String variables can be declared either by using single or
double quotes:
x = "Jouda"
# is the same as
x = 'Jouda'
Case-Sensitive
a = 4
A = "Sally"
#A will not overwrite a
Jouda M.Qamar - 2023 11
Python - Variable Names
Variable Names:
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
• Rules for Python variables:A variable name must start with a letter or
the underscore character.
• A variable name can not start with a number.
• Variable names are case-sensitive (age, Age and AGE are three
different variables).
Jouda M.Qamar - 2023 12
Python - Variable Names Cont.
Example
Legal variable names:
myvar = "Jouda"
my_var = "Jouda"
_my_var = "Jouda"
myVar = "Jouda"
MYVAR = "Jouda"
myvar2 = "Jouda"
Jouda M.Qamar - 2023 13
Example
Illegal variable names:
2myvar = "Jouda"
my-var = "Jouda"
my var = "Jouda"
Multi Words Variable Names
• Variable names with more than one word can be difficult to read.
MyVariableName = "Jouda"
myVariableName = "Jouda"
my_variable_name = "Jouda"
Jouda M.Qamar - 2023 14
Python Variables - Assign Multiple Values
1- x, y, z = "Ahmed", "Ali", "Mohamed"
print(x)
print(y)
print(z)
2- x = y = z = "Orange"
print(x)
print(y)
print(z)
Jouda M.Qamar - 2023 15
Python - Output Variables
Output Variables:
The Python print() function is often used to output variables.
x = "jouda mohamed"
print(x)
Output : jouda mohamed
x = "Jouda"
y = "Mohamed"
z = "Qamar"
print(x, y, z)
Output : Jouda Mohamed Qamar
Jouda M.Qamar - 2023 16
x = "Jouda"
y = "Mohamed"
z = "Qamar"
print(x + y + z)
Output : Jouda Mohamed Qamar
x = 5
y = 10
print(x + y)
Output : 15
Simple Questions
Jouda M.Qamar - 2023 17
A- using python writing the programs :
1- Create a variable named carname and assign the value lada to it.
2- Create a variable named x and assign the value 200.5 to it.
3- Display the sum of 200 + 1000, using two variables: x and y.
4- Create a variable called z, assign x + y to it, and display the result.
B- What is error correction:
I. 2my-first_name = "mohamed"
II. x="2”
y= 3.5
print (“x+y")
Summary
• Anything inside double quotation marks is printed as is.
• Print () To output text, a number, or anything I want.
• Creating variables and knowing how to create more than one value
inside a variable, as well as the rules for creating variables.
• Knowing the types of variables and how to change between them and
doing Costing.
• Determine the type of the variable through the command type().
Jouda M.Qamar - 2023 18
Jouda M.Qamar - 2023
Chapter Two
Python Data Types and Python Operators and input
19
Jouda M.Qamar - 2023 20
Python Data Types
In programming, data type is an
important concept.
Variables can store data of
different types, and different types
can do different things.
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview
None NoneType
Jouda M.Qamar - 2023 21
Python Numeric Data type.
In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall under Python numbers category.
They are defined as int, float and complex classes in Python.
int - holds signed integers of non-limited length.
float - holds floating decimal points and it's accurate up to 15 decimal places.
complex - holds complex numbers.
We can use the type() function to know which class a variable or a value belongs to.
Jouda M.Qamar - 2023 22
Example
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
Output
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
Jouda M.Qamar - 2023 23
Python List Data Type.
List is an ordered collection of similar or different types of items separated by commas and
enclosed within brackets [ ].
For example
languages = ["c++", "R", "Python"]
Access List Items
To access items from a list, we use the index
number (0, 1, 2 ...)
languages = ["c++", “R", "Python"]
# access element at index 0
print(languages[0]) # Swift
# access element at index 2
print(languages[2]) # Python
Jouda M.Qamar - 2023 24
Python Tuple Data Type
• Tuple is an ordered sequence of items same as a list.
• The only difference is that tuples are immutable.
• Tuples once created cannot be modified.
product = ('Xbox', 499.99)
Access Tuple Items
# create a tuple
product = ('Microsoft', 'Xbox', 499.99)
# access element at index 0
print(product[0]) # Microsoft
# access element at index 1
print(product[1]) # Xbox
Jouda M.Qamar - 2023 25
Python String Data Type
String is a sequence of characters represented by either single or double quotes.
For example
name = 'Python'
print(name)
message = 'Python for beginners'
print(message)
Output
Python
Python for beginners
Jouda M.Qamar - 2023 26
Python Set Data Type
Set is an unordered collection of unique items. Set is defined by values separated by
commas inside braces { }
# create a set named student_id
student_id = {112, 114, 116, 118, 115}
# display student_id elements
print(student_id)
# display type of student_id
print(type(student_id))
Output
{112, 114, 115, 116, 118}
<class 'set'>
Jouda M.Qamar - 2023 27
Python Booleans
Booleans represent one of two values: True or False.
Boolean Values
• In programming you often need to know if an expression is True or False.
• You can evaluate any expression in Python, and get one of two answers, True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
Jouda M.Qamar - 2023 28
Python Operators
Operators are used to perform operations on variables and values.
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Type Conversion
Jouda M.Qamar - 2023 29
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Python Casting
- Specify a Variable Type
• There may be times when you want to specify a type on to a variable. This can be
done with casting. Python is an object-orientated language, and as such it uses
classes to define data types, including its primitive types.
• Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
Jouda M.Qamar - 2023 30
#int
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Jouda M.Qamar - 2023 31
#float
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
#string
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Jouda M.Qamar - 2023 32
input in Python
input in Python
input (): This function first takes the input from the user and converts it
into a string.
val = input("Enter your value: ")
print(val)
# Python program showing
# a use of input()
Jouda M.Qamar - 2023 33
Simple program using input,define to var.
name and input for your name by n.
name = input('What is your name?n')
# n ---> newline ---> It causes a line break
print(name)
Jouda M.Qamar - 2023 34
input in Python cont.
Note: input() function takes all the input as a string only.
• There are various function that are used to take as desired input few
of them are :
int(input())
float(input())
Jouda M.Qamar - 2023 35
Multiple inputs from user in Python
• using split() method :
This function helps in getting multiple inputs from users. It breaks the
given input by the specified separator. If a separator is not provided
then any white space is a separator. Generally, users use a split()
method to split a Python string but one can use it in taking multiple
inputs.
Jouda M.Qamar - 2023 36
Syntax :
input().split(separator, maxsplit)
Multiple inputs from user in Python
Jouda M.Qamar - 2023 37
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print()
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
print()
Programs by python
• using Python, create a simple program to calculate the sum of two
numbers.
Jouda M.Qamar - 2023 38
Programs by python
• using Python, create a simple program to calculate area of rectangle
height = float (input ("Enter Height :"))
width = float (input ("Enter width :"))
print ("The result is :",height*width)
Jouda M.Qamar - 2023 39
Programs by python
• If the computer
programming course
has a final score of
100, please create a
program to read the
students’name and
code, and then know
the grade of each
student.
Jouda M.Qamar - 2023 40
student_name = str (input ("Enter Student Name : "))
student_id = int (input ("Enter Student id : "))
degree = float (input ("Enter Student degree : "))
if degree >= 80 :
print ("A")
elif degree >= 70 :
print ("B")
elif degree >= 60 :
print ("C")
elif degree >= 50 :
print ("D")
else :
print ("F")
Chapter Three
Python Conditions and If statements and
LOOPs (Control Flow in Python).
Jouda M.Qamar - 2023 41
Python If ... Else
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.
Jouda M.Qamar - 2023 42
Jouda M.Qamar - 2023 43
if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block.
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Flowchart of Python if statement
Example: Python if Statement
Jouda M.Qamar - 2023 44
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
if-else
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Jouda M.Qamar - 2023 45
FlowChart of Python if-else statement
Example : Python if-else statement
Jouda M.Qamar - 2023 46
# python program to illustrate If else statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
if-elif-else ladder
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Jouda M.Qamar - 2023 47
FlowChart of Python if else elif statements
Example: Python if else elif statements
Jouda M.Qamar - 2023 48
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output: i is 20
Chaining comparison operators in Python
">" | "<" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in"
Jouda M.Qamar - 2023 49
Chaining in Comparison Operators:
1.Comparisons yield boolean values: True or False.
2.Comparisons can be chained arbitrarily.
For example:
# Python code to illustrate
# chaining comparison operators
x = 5
print(1 < x < 10)
print(10 < x < 20 )
print(x < 10 < x*10 < 100)
print(10 > x <= 9)
print(5 == x > 4)
Output
True
False
True
True
True
Another Example:
# Python code to illustrate
# chaining comparison operators
a, b, c, d, e, f = 0, 5, 12, 0, 15, 15
exp1 = a <= b < c > d is not e is f
exp2 = a is d > f is not c
print(exp1)
print(exp2)
Output
True
False
And
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Jouda M.Qamar - 2023 50
a > b and c > a
Or
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Jouda M.Qamar - 2023 51
a > b or a > c
Not
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Jouda M.Qamar - 2023 52
not a > b
For Loops
Jouda M.Qamar - 2023 53
Python For Loops
For Loops Syntax
for var in iterable:
# statements
Jouda M.Qamar - 2023 54
Flowchart of for loop
Examples of For Loops in Python
• Example 1: Using For Loops in Python List:
Jouda M.Qamar - 2023 55
# Python program to illustrate
# Iterating over a list
l = ["coding", "academy", "for programming"]
for i in l:
print(i)
Output :
coding
academy
for programming
Continue Statement in Python
# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Jouda M.Qamar - 2023 56
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement in Python
for letter in 'geeksforgeeks':
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Jouda M.Qamar - 2023 57
Output:
Current Letter : e
Pass Statement in Python
# An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Jouda M.Qamar - 2023 58
Output: Last Letter : s
range () function in Python
Jouda M.Qamar - 2023 59
# Python Program to
# show range() basics
# printing a number
for i in range(10):
print(i, end=" ")
# performing sum of first 10 numbers
sum = 0
for i in range(1, 10):
sum = sum + i
print("nSum of first 10 numbers :", sum)
Output:
0 1 2 3 4 5 6 7 8 9
Sum of first 10 numbers : 45
For loop in Python with else
# for-else loop
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Breakn")
Jouda M.Qamar - 2023 60
Output:
1
2
3
No Break
Python While Loop
Jouda M.Qamar - 2023 61
While Loop
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Jouda M.Qamar - 2023 62
Output
Hello Geek
Hello Geek
Hello Geek
While Loop
# Single statement while block
count = 0
while (count < 5): count += 1; print("Hello Geek")
Jouda M.Qamar - 2023 63
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
Jouda M.Qamar - 2023 64
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Simple Questions
What is output :
1. p, q, r = 10, 20 ,30
print(p, q, r)
2.
a = 3
b = 5
if a>b : print ("TRUE")
else : print ("False")
Jouda M.Qamar - 2023 65
Simple Questions
3.
a = 50
b = 10
if a>b:
print("Hello World")
Write a program python :
1. Print "Yes" if a is equal to b, otherwise print "No".
2. Print "1" if a is equal to b, print "2" if a is greater than b, otherwise
print "3".
3. Print "Hello" if a is equal to b, or if c is equal to d.
Jouda M.Qamar - 2023 66
Simple Questions
The format function, when applied on a string returns :
- List - int - bool - str
What is output:
Jouda M.Qamar - 2023 67
Chapter four
Python Arrays and function.
Jouda M.Qamar - 2023 68
Python Arrays
Jouda M.Qamar - 2023 69
Jouda M.Qamar - 2023 70
an array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together.
Python Arrays
Jouda M.Qamar - 2023 71
Creating a Array
Array in Python can be created by importing array module.
array(data_type, value_list)
is used to create an array with data type and value list specified in its
arguments.
Jouda M.Qamar - 2023 72
# Python program to demonstrate
# Creation of Array
# importing "array" for array creations
import array as arr
# creating an array with integer type
a = arr.array('i', [1, 2, 3])
# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()
# creating an array with double type
b = arr.array('d', [2.5, 3.2, 3.3])
# printing original array
print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")
The new created array is : 1 2 3
The new created array is : 2.5 3.2 3.3
Array & List Methods
Python has a set of built-in methods that you can use on lists/arrays.
Jouda M.Qamar - 2023 73
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value.
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Functions
Jouda M.Qamar - 2023 74
Python Functions
Functions is a block of statements that return the specific task.
Syntax: Python Functions
Jouda M.Qamar - 2023 75
Creating a Python Function
Jouda M.Qamar - 2023 76
We can create a Python function using the def keyword.
# A simple Python function
def fun():
print("Welcome Func ")
Calling a Python Function
After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular
function.
def fun():
print("jouda")
# Driver code to call a function
fun()
Jouda M.Qamar - 2023 77

More Related Content

Similar to Introduction to Python - Jouda M Qamar.pdf

Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
Saraswathi Murugan
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
Saraswathi Murugan
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
HarishParthasarathy4
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
Module 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptxModule 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptx
GaneshRaghu4
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
Python basics
Python basicsPython basics
Python basics
Manisha Gholve
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
Tanwir Zaman
 
V design and implementation of network security using genetic algorithm
V design and implementation of network security using genetic algorithmV design and implementation of network security using genetic algorithm
V design and implementation of network security using genetic algorithm
eSAT Journals
 
Design and implementation of network security using genetic algorithm
Design and implementation of network security using genetic algorithmDesign and implementation of network security using genetic algorithm
Design and implementation of network security using genetic algorithm
eSAT Publishing House
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
sriram2110
 
1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx
KUSHSHARMA630049
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in Python
PranavSB
 
Introduction to the Stat-JR software package
Introduction to the Stat-JR software packageIntroduction to the Stat-JR software package
Introduction to the Stat-JR software package
University of Southampton
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
Abdullah khawar
 

Similar to Introduction to Python - Jouda M Qamar.pdf (20)

Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
Module 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptxModule 1 - Programming Fundamentals.pptx
Module 1 - Programming Fundamentals.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
Python basics
Python basicsPython basics
Python basics
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
V design and implementation of network security using genetic algorithm
V design and implementation of network security using genetic algorithmV design and implementation of network security using genetic algorithm
V design and implementation of network security using genetic algorithm
 
Design and implementation of network security using genetic algorithm
Design and implementation of network security using genetic algorithmDesign and implementation of network security using genetic algorithm
Design and implementation of network security using genetic algorithm
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
 
1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in Python
 
Introduction to the Stat-JR software package
Introduction to the Stat-JR software packageIntroduction to the Stat-JR software package
Introduction to the Stat-JR software package
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
 

Recently uploaded

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 

Recently uploaded (20)

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 

Introduction to Python - Jouda M Qamar.pdf

  • 1. Introduction to Python January 2023 Jouda M. Qamar. Computer Science - Cairo University
  • 2. What can Python do? • Python can be used on a server to create web applications. • Python can be used alongside software to create workflows. • Python can connect to database systems. It can also read and modify files. • Python can be used to handle big data and perform complex mathematics. • Python can be used for rapid prototyping, or for production-ready software development. Jouda M.Qamar - 2023 2
  • 3. What is Python? • Python is a popular programming language. • It was created by Guido van Rossum, and released in 1991. Jouda M.Qamar - 2023 The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular. ______________________________________________ In this tutorial Python will be written in a text editor. TOOLS: - python install (https://www.python.org/). - anaconda (https://www.anaconda.com/). 3
  • 4. Python Syntax Python Syntax compared to other programming languages! • Python was designed for readability. • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. Jouda M.Qamar - 2023 4
  • 5. Compare between C++ & Python C++ #include <iostream> using namespace std; int main () { int x,y,z; cin >> x >> y; z=x+y; cout << z; Return0; } output : value z Jouda M.Qamar - 2023 Python x=2 y=3 print(x+y) output :5 5
  • 6. Jouda M.Qamar - 2023 Chapter One Python syntax and Python Variables 6
  • 7. Python syntax Writing the first line in Python print("coding academy!") _______________________________________________ What is output : print("Hello, World!") Output : ------------------ print (“jouda”) Output : ------------------ print ("23") Output : ------------------
  • 8. Build your first program in Python • Using the Python programming language, draw a triangle shape print (" /|") print (" / |") print (" / |") print ("/__|") Output: Jouda M.Qamar - 2023 8 print (" ________") print ("| |") print ("| |") print ("|________|") Output:
  • 9. Python - Variables • variables are containers for storing data values. • Creating Variables: Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Jouda M.Qamar - 2023 9 x = 27 y = "jouda" print(x) print(y) Variables do not need to be declared with any particular type, and can even change type after they have been set. x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
  • 10. Python - Variables Cont. • Casting If you want to specify the data type of a variable, this can be done with casting. x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 • Get the Type You can get the data type of a variable with the type() function: Jouda M.Qamar - 2023 10 x = 5 y = "John" print(type(x)) print(type(y))
  • 11. Python - Variables Cont. Single or Double Quotes? String variables can be declared either by using single or double quotes: x = "Jouda" # is the same as x = 'Jouda' Case-Sensitive a = 4 A = "Sally" #A will not overwrite a Jouda M.Qamar - 2023 11
  • 12. Python - Variable Names Variable Names: • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). • Rules for Python variables:A variable name must start with a letter or the underscore character. • A variable name can not start with a number. • Variable names are case-sensitive (age, Age and AGE are three different variables). Jouda M.Qamar - 2023 12
  • 13. Python - Variable Names Cont. Example Legal variable names: myvar = "Jouda" my_var = "Jouda" _my_var = "Jouda" myVar = "Jouda" MYVAR = "Jouda" myvar2 = "Jouda" Jouda M.Qamar - 2023 13 Example Illegal variable names: 2myvar = "Jouda" my-var = "Jouda" my var = "Jouda"
  • 14. Multi Words Variable Names • Variable names with more than one word can be difficult to read. MyVariableName = "Jouda" myVariableName = "Jouda" my_variable_name = "Jouda" Jouda M.Qamar - 2023 14
  • 15. Python Variables - Assign Multiple Values 1- x, y, z = "Ahmed", "Ali", "Mohamed" print(x) print(y) print(z) 2- x = y = z = "Orange" print(x) print(y) print(z) Jouda M.Qamar - 2023 15
  • 16. Python - Output Variables Output Variables: The Python print() function is often used to output variables. x = "jouda mohamed" print(x) Output : jouda mohamed x = "Jouda" y = "Mohamed" z = "Qamar" print(x, y, z) Output : Jouda Mohamed Qamar Jouda M.Qamar - 2023 16 x = "Jouda" y = "Mohamed" z = "Qamar" print(x + y + z) Output : Jouda Mohamed Qamar x = 5 y = 10 print(x + y) Output : 15
  • 17. Simple Questions Jouda M.Qamar - 2023 17 A- using python writing the programs : 1- Create a variable named carname and assign the value lada to it. 2- Create a variable named x and assign the value 200.5 to it. 3- Display the sum of 200 + 1000, using two variables: x and y. 4- Create a variable called z, assign x + y to it, and display the result. B- What is error correction: I. 2my-first_name = "mohamed" II. x="2” y= 3.5 print (“x+y")
  • 18. Summary • Anything inside double quotation marks is printed as is. • Print () To output text, a number, or anything I want. • Creating variables and knowing how to create more than one value inside a variable, as well as the rules for creating variables. • Knowing the types of variables and how to change between them and doing Costing. • Determine the type of the variable through the command type(). Jouda M.Qamar - 2023 18
  • 19. Jouda M.Qamar - 2023 Chapter Two Python Data Types and Python Operators and input 19
  • 20. Jouda M.Qamar - 2023 20 Python Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Text str Numeric int, float, complex Sequence list, tuple, range Mapping dict Set set, frozenset Boolean bool Binary bytes, bytearray, memoryview None NoneType
  • 21. Jouda M.Qamar - 2023 21 Python Numeric Data type. In Python, numeric data type is used to hold numeric values. Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python. int - holds signed integers of non-limited length. float - holds floating decimal points and it's accurate up to 15 decimal places. complex - holds complex numbers. We can use the type() function to know which class a variable or a value belongs to.
  • 22. Jouda M.Qamar - 2023 22 Example num1 = 5 print(num1, 'is of type', type(num1)) num2 = 2.0 print(num2, 'is of type', type(num2)) num3 = 1+2j print(num3, 'is of type', type(num3)) Output 5 is of type <class 'int'> 2.0 is of type <class 'float'> (1+2j) is of type <class 'complex'>
  • 23. Jouda M.Qamar - 2023 23 Python List Data Type. List is an ordered collection of similar or different types of items separated by commas and enclosed within brackets [ ]. For example languages = ["c++", "R", "Python"] Access List Items To access items from a list, we use the index number (0, 1, 2 ...) languages = ["c++", “R", "Python"] # access element at index 0 print(languages[0]) # Swift # access element at index 2 print(languages[2]) # Python
  • 24. Jouda M.Qamar - 2023 24 Python Tuple Data Type • Tuple is an ordered sequence of items same as a list. • The only difference is that tuples are immutable. • Tuples once created cannot be modified. product = ('Xbox', 499.99) Access Tuple Items # create a tuple product = ('Microsoft', 'Xbox', 499.99) # access element at index 0 print(product[0]) # Microsoft # access element at index 1 print(product[1]) # Xbox
  • 25. Jouda M.Qamar - 2023 25 Python String Data Type String is a sequence of characters represented by either single or double quotes. For example name = 'Python' print(name) message = 'Python for beginners' print(message) Output Python Python for beginners
  • 26. Jouda M.Qamar - 2023 26 Python Set Data Type Set is an unordered collection of unique items. Set is defined by values separated by commas inside braces { } # create a set named student_id student_id = {112, 114, 116, 118, 115} # display student_id elements print(student_id) # display type of student_id print(type(student_id)) Output {112, 114, 115, 116, 118} <class 'set'>
  • 27. Jouda M.Qamar - 2023 27 Python Booleans Booleans represent one of two values: True or False. Boolean Values • In programming you often need to know if an expression is True or False. • You can evaluate any expression in Python, and get one of two answers, True or False. print(10 > 9) print(10 == 9) print(10 < 9)
  • 28. Jouda M.Qamar - 2023 28 Python Operators Operators are used to perform operations on variables and values. Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 29. Type Conversion Jouda M.Qamar - 2023 29 x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
  • 30. Python Casting - Specify a Variable Type • There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. • Casting in python is therefore done using constructor functions: • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals Jouda M.Qamar - 2023 30
  • 31. #int x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3 Jouda M.Qamar - 2023 31 #float x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 #string x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'
  • 32. Jouda M.Qamar - 2023 32 input in Python
  • 33. input in Python input (): This function first takes the input from the user and converts it into a string. val = input("Enter your value: ") print(val) # Python program showing # a use of input() Jouda M.Qamar - 2023 33
  • 34. Simple program using input,define to var. name and input for your name by n. name = input('What is your name?n') # n ---> newline ---> It causes a line break print(name) Jouda M.Qamar - 2023 34
  • 35. input in Python cont. Note: input() function takes all the input as a string only. • There are various function that are used to take as desired input few of them are : int(input()) float(input()) Jouda M.Qamar - 2023 35
  • 36. Multiple inputs from user in Python • using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs. Jouda M.Qamar - 2023 36 Syntax : input().split(separator, maxsplit)
  • 37. Multiple inputs from user in Python Jouda M.Qamar - 2023 37 # taking two inputs at a time x, y = input("Enter two values: ").split() print("Number of boys: ", x) print("Number of girls: ", y) print() # taking three inputs at a time x, y, z = input("Enter three values: ").split() print("Total number of students: ", x) print("Number of boys is : ", y) print("Number of girls is : ", z) print()
  • 38. Programs by python • using Python, create a simple program to calculate the sum of two numbers. Jouda M.Qamar - 2023 38
  • 39. Programs by python • using Python, create a simple program to calculate area of rectangle height = float (input ("Enter Height :")) width = float (input ("Enter width :")) print ("The result is :",height*width) Jouda M.Qamar - 2023 39
  • 40. Programs by python • If the computer programming course has a final score of 100, please create a program to read the students’name and code, and then know the grade of each student. Jouda M.Qamar - 2023 40 student_name = str (input ("Enter Student Name : ")) student_id = int (input ("Enter Student id : ")) degree = float (input ("Enter Student degree : ")) if degree >= 80 : print ("A") elif degree >= 70 : print ("B") elif degree >= 60 : print ("C") elif degree >= 50 : print ("D") else : print ("F")
  • 41. Chapter Three Python Conditions and If statements and LOOPs (Control Flow in Python). Jouda M.Qamar - 2023 41
  • 42. Python If ... Else 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. Jouda M.Qamar - 2023 42
  • 43. Jouda M.Qamar - 2023 43 if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. if condition: statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. Flowchart of Python if statement
  • 44. Example: Python if Statement Jouda M.Qamar - 2023 44 # python program to illustrate If statement i = 10 if (i > 15): print("10 is less than 15") print("I am Not in if") Output: I am Not in if
  • 45. if-else Syntax: if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false Jouda M.Qamar - 2023 45 FlowChart of Python if-else statement
  • 46. Example : Python if-else statement Jouda M.Qamar - 2023 46 # python program to illustrate If else statement i = 20 if (i < 15): print("i is smaller than 15") print("i'm in if Block") else: print("i is greater than 15") print("i'm in else Block") print("i'm not in if and not in else Block") Output: i is greater than 15 i'm in else Block i'm not in if and not in else Block
  • 47. if-elif-else ladder Syntax: if (condition): statement elif (condition): statement . . else: statement Jouda M.Qamar - 2023 47 FlowChart of Python if else elif statements
  • 48. Example: Python if else elif statements Jouda M.Qamar - 2023 48 # Python program to illustrate if-elif-else ladder i = 20 if (i == 10): print("i is 10") elif (i == 15): print("i is 15") elif (i == 20): print("i is 20") else: print("i is not present") Output: i is 20
  • 49. Chaining comparison operators in Python ">" | "<" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in" Jouda M.Qamar - 2023 49 Chaining in Comparison Operators: 1.Comparisons yield boolean values: True or False. 2.Comparisons can be chained arbitrarily. For example: # Python code to illustrate # chaining comparison operators x = 5 print(1 < x < 10) print(10 < x < 20 ) print(x < 10 < x*10 < 100) print(10 > x <= 9) print(5 == x > 4) Output True False True True True Another Example: # Python code to illustrate # chaining comparison operators a, b, c, d, e, f = 0, 5, 12, 0, 15, 15 exp1 = a <= b < c > d is not e is f exp2 = a is d > f is not c print(exp1) print(exp2) Output True False
  • 50. And a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Jouda M.Qamar - 2023 50 a > b and c > a
  • 51. Or a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") Jouda M.Qamar - 2023 51 a > b or a > c
  • 52. Not a = 33 b = 200 if not a > b: print("a is NOT greater than b") Jouda M.Qamar - 2023 52 not a > b
  • 54. Python For Loops For Loops Syntax for var in iterable: # statements Jouda M.Qamar - 2023 54 Flowchart of for loop
  • 55. Examples of For Loops in Python • Example 1: Using For Loops in Python List: Jouda M.Qamar - 2023 55 # Python program to illustrate # Iterating over a list l = ["coding", "academy", "for programming"] for i in l: print(i) Output : coding academy for programming
  • 56. Continue Statement in Python # Prints all letters except 'e' and 's' for letter in 'geeksforgeeks': if letter == 'e' or letter == 's': continue print('Current Letter :', letter) Jouda M.Qamar - 2023 56 Output: Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k
  • 57. Break Statement in Python for letter in 'geeksforgeeks': # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print('Current Letter :', letter) Jouda M.Qamar - 2023 57 Output: Current Letter : e
  • 58. Pass Statement in Python # An empty loop for letter in 'geeksforgeeks': pass print('Last Letter :', letter) Jouda M.Qamar - 2023 58 Output: Last Letter : s
  • 59. range () function in Python Jouda M.Qamar - 2023 59 # Python Program to # show range() basics # printing a number for i in range(10): print(i, end=" ") # performing sum of first 10 numbers sum = 0 for i in range(1, 10): sum = sum + i print("nSum of first 10 numbers :", sum) Output: 0 1 2 3 4 5 6 7 8 9 Sum of first 10 numbers : 45
  • 60. For loop in Python with else # for-else loop for i in range(1, 4): print(i) else: # Executed because no break in for print("No Breakn") Jouda M.Qamar - 2023 60 Output: 1 2 3 No Break
  • 61. Python While Loop Jouda M.Qamar - 2023 61
  • 62. While Loop # while loop count = 0 while (count < 3): count = count + 1 print("Hello Geek") Jouda M.Qamar - 2023 62 Output Hello Geek Hello Geek Hello Geek
  • 63. While Loop # Single statement while block count = 0 while (count < 5): count += 1; print("Hello Geek") Jouda M.Qamar - 2023 63 Output: Hello Geek Hello Geek Hello Geek Hello Geek Hello Geek
  • 64. The else Statement With the else statement we can run a block of code once when the condition no longer is true: Jouda M.Qamar - 2023 64 i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")
  • 65. Simple Questions What is output : 1. p, q, r = 10, 20 ,30 print(p, q, r) 2. a = 3 b = 5 if a>b : print ("TRUE") else : print ("False") Jouda M.Qamar - 2023 65
  • 66. Simple Questions 3. a = 50 b = 10 if a>b: print("Hello World") Write a program python : 1. Print "Yes" if a is equal to b, otherwise print "No". 2. Print "1" if a is equal to b, print "2" if a is greater than b, otherwise print "3". 3. Print "Hello" if a is equal to b, or if c is equal to d. Jouda M.Qamar - 2023 66
  • 67. Simple Questions The format function, when applied on a string returns : - List - int - bool - str What is output: Jouda M.Qamar - 2023 67
  • 68. Chapter four Python Arrays and function. Jouda M.Qamar - 2023 68
  • 70. Jouda M.Qamar - 2023 70 an array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Python Arrays
  • 71. Jouda M.Qamar - 2023 71 Creating a Array Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.
  • 72. Jouda M.Qamar - 2023 72 # Python program to demonstrate # Creation of Array # importing "array" for array creations import array as arr # creating an array with integer type a = arr.array('i', [1, 2, 3]) # printing original array print ("The new created array is : ", end =" ") for i in range (0, 3): print (a[i], end =" ") print() # creating an array with double type b = arr.array('d', [2.5, 3.2, 3.3]) # printing original array print ("The new created array is : ", end =" ") for i in range (0, 3): print (b[i], end =" ") The new created array is : 1 2 3 The new created array is : 2.5 3.2 3.3
  • 73. Array & List Methods Python has a set of built-in methods that you can use on lists/arrays. Jouda M.Qamar - 2023 73 Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value. extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list
  • 75. Python Functions Functions is a block of statements that return the specific task. Syntax: Python Functions Jouda M.Qamar - 2023 75
  • 76. Creating a Python Function Jouda M.Qamar - 2023 76 We can create a Python function using the def keyword. # A simple Python function def fun(): print("Welcome Func ")
  • 77. Calling a Python Function After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function. def fun(): print("jouda") # Driver code to call a function fun() Jouda M.Qamar - 2023 77