Chapter1(Introduction)
Chapter1(Introduction)
Python is an Open-source language that can be implemented using several Open-source editors:
✓ Anaconda (Jupyter Notebook, Spider, VS code, PyCharm, etc.)
✓ Google Collaboratory
After you have selected the option that you will follow to program Python, now you must know
the Roadmap that includes the topics that you will learn in this course:
Python Indentation
Python uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
i=3
Print(""Hello"")
*********************************
Data Types:
variable = expression
The equal sign (=) is known as the assignment operator. In the general format, variable is the
name of a variable and expression is a value, or any piece of code that results in a value.
Here is an example of an assignment statement:
age = 25
➢ Variable Reassignment
Variables are called “variable” because they can reference different values while a program is
running. When you assign a value to a variable, the variable will reference that value until you
assign it a different value.
Note: when you change the value of the variable, the data type of the variable will be changed
based on the new value.
x = y = z = 10 10
print(x)
print(y) 10
print(z)
10
you can use the built-in type function to get the data type of a value/variable.
*********************************
Python Casting
Casting
Implicit Explicit
x = float(3) x = str(3)
print(x) #3.0 print(x) #”3.0”
x = float(8.9) x = str(8.9)
print(x) #8.9 print(x) #”8.9”
x = float("66") x = str("66")
print(x) #”66”
print(x) #66.0
x = "Hi"
x = 50 x = str(x)
x = float(x) print(x) #”Hi”
print(x) #50.0
x = float("5.6")
print(x) #5.6
All type here are float. All type here are string.
x = 50.5
x = int(x) 50
print(x) <class 'int'>
print(type(x))
y = 50.5
x = int(y)
print(x) 50
print(type(x)) <class 'int'>
print(y) 50.5
print(type(y)) <class 'float'>
Note: Each of the statements displays a string and then prints a newline character.
Output:
Ex4: Output statement
print("Hi1", end =" ")
Hi1 99 2.3
print(99, end =" ")
print(2.3)
Output:
Ex5: Output statement
a, b, c = 2, 5, 7 2 5 7$$2 5 7
print(a,b,c,end = "$$")
print(a,b,c) 2 5 72 5 7
print(a,b,c,end= "")
print(a,b,c)
print(item1, ithem2, ….) print(item1, ithem2, …., sep= " ",end ="\n")
The sep parameter of the print() function is used to specify the separator between the strings. If
you do not want a space printed between the items, you can pass the argument sep=" "to the print
function, as shown here:
x, y, z = 10, 15, 20
print(x,y,z, sep = "Hi", end = "$") 10Hi15Hi20$10 15 20
print(x,y,z, sep = " ")
print(x,y,z, end = "***")
10 15 20***10----15----20
print(x,y,z, sep = "----")
➢ Escape Characters
An escape character is a special character that is preceded with a backslash (\), appearing inside
a string literal. When a string literal that contains escape characters is printed, the escape characters
are treated as special commands that are embedded in the string.
Python recognizes several escape characters, some of which are listed in the following table.
Output:
One
print("One\nTwo\nThree")
print("One\\Two\\Three") Two
Three
One\Two\Three
*********************************
Input Statement
Programs commonly need to read input typed by the user on the keyboard.
We use Python’s built-in input function to read input from the keyboard. The input function reads
a piece of data that has been entered at the keyboard and returns that piece of data, as a string,
back to the program
Output:
Ex1: Input string values
name = input("Please enter your name: ") Please enter your name: Enas
age = input("Please enter your age: ")
income = input("Please enter your income: ") Please enter your age: 40
g_state = input("Please enter your graduate state: ")
print("Done!") Please enter your income: 500.20
Please enter your graduate state: true
Done!
*********************************
Math Expression: performs a calculation and gives a value, it contains operands(numbers) and
math operators (+, -, *, /, //, **, %).
Math expression can be categorized into three types: Integer Expressions, Floating Expressions,
and Mixed-Type Expressions.
Integer Expressions: an operation is performed on two or more int values then the result will be
an int.
Float Expressions: an operation is performed on two or more float values then result will be a
float.
Mixed-Type Expressions: an operation is performed on different data types (int and a float), the
int value will be temporarily converted to a float and the result of the operation will be a float, then
the result will be float.
Python has two different division operators. The / operator performs floating-point division, and
the // operator performs integer division. Both operators divide one number by another. The
difference between them is that the / operator gives the result as a floating-point value, and the //
operator gives the result as an integer value.
➢ Operators Precedence
The precedence of the math operators, from highest to lowest, are:
1. Between Brackets ()
2. Exponentiation: **
3. Multiplication, division, and remainder: * / // %
4. Addition and subtraction: + −
5. Relational Operators: == != <= >= < >
6. Logical Operators: not and or
If the precedence is, the execution is from left to right.
The following figure shows the execution of an expression.
(and, or, not) operators allow you to connect multiple boolean expressions to create a compound
expression.
The followings tables show the truth table for (and, or, not) operators respectively.
The truth table for and operator
Program1: average.py
Output Sample:
Enter 3 numbers: 3
5
3
Average = 3.6666666666666665
Code:
n1,n2,n3=float(input("Enter 3numbers:")),float(input()),float(input())
average=(n1+n2+n3)/3
print("average=",average)
Program2: Exponent.py
Write a Python program that reads the basic salary of an employee, calculates his tax(6% of his
basic salary and calculates the Netsalary by the following equation:
Note: Net Salary = Basic Salary –TaxSolution:
Code:
basicSalary = float(input("Please,enter the basic salary: "))
tax = 0.06 * basicSalary
NetSalary = basicSalary-tax
print("NetSalary= ",NetSalary)
*********************************
if (condition):
statement
statement
etc.
Ex1: if statement
sales = int(input("Please enter your sales:"))
if(sales > 500):
bonus = 30
print("The bonus is:", bonus)
print("Done!")
In Python, we use the if-else statement to write the dual alternative decision structure, which
has two possible paths of execution—one path is taken if a condition is true, and the other path is
taken if the condition is false.
The general format of the if-else statement:
if (condition):
statement
statement
etc.
else:
statement
statement
etc.
print("Done!")
if (condition1):
statement
statement
etc.
elif (condition2):
statement
statement
etc.
else: #optional (executed when all previous conditions are false)
statement
statement
etc.
x, y = 5, 6
if(x<y): #if the condition is false, all the following if will not execute
print("x is greater than y")
print("here, is if(1)")
if(x == 5): #if the condition is false, the following if will not execute
print("here, is if(2)")
if(y == 6):
print("here, is if(3)")
print("Finished")
x, y = 5, 6
if(x<y): #if the condition is false, all the following if will not execute
print("x is greater than y")
print("here, is if(1)")
if(x == 5): #this if is independent of the following if
print("here, is if(2)")
if(y == 6):
print("here, is if(3)")
print("Finished")
Note: Please try all possible conditions in the previous two examples to understand the difference
between them correctly.
The program should ask the user to input two integer operands and an operation (+, -, *, /, //,
**), your program should print the result of performing the required operation on the input
operands.
Output Sample:
Please enter the first operand:100
Please enter the second operand:22
Please enter the operation:/
The result of 100 / 22 is: 4.54545
Code:
firstOperand = int(input("Please enter the first operand (number): "))
secondOperand = int(input("Please enter the second operand (number): "))
operation = input("Please enter the operation: ")
if (operation == "+"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand + secondOperand)
elif (operation == "-"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand - secondOperand)
elif (operation == "*"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand * secondOperand)
elif (operation == "/"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand / secondOperand)
elif (operation == "//"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand // secondOperand)
elif (operation == "**"):
print("The result of ", firstOperand, operation, secondOperand, "is:",
firstOperand ** secondOperand)
else:
print("OHH, your input is incorrect!!")
Example2:
Write a Python program that reads two integers and divides the first over the second. Make sure
that the second integer is not zero, otherwise, give an error message.
Output Sample:
Enter two integers: 10
3
The result is: 3.3333333333333335
Example3:
Write a Python program that reads an integer and decides wither it is divisible of 3 or not.
Output Sample:
Enter an integer: 5
5 is not divisible by 3
Code:
num=int(input("Enter an integer: "))
if (num%3==0):
print(num,"is divisible by 3")
else:
print(num,"is not divisible by 3")
Example4:
Write a Python program that reads a day in a week from the user, and prints the following:
Working day: if the user enters (Sunday, Monday, Tuesday, Wednesday or Thursday)
Weekend: if the user enters (Friday or Saturday)
Output Sample:
Please, enter a weekday: Monday
Working day
Please, enter a weekday: Friday
Weekend
Code:
day=input("Please, enter a weekday: ")
if (day=="Sunday") or (day=="Monday") or (day=="Tuesday") or
(day=="Wednesday") or (day=="Thursday"):
print("Working day")
elif (day=="Friday") or (day=="Saturday"):
print("Weekend")
else:
print("Wrong day name or wrong spelling")
Output Sample:
Enter an integer: 5
R= 25
Code:
Example1:
x= int(input("Enter an integer: "))
if (x>0):
pass
else:
print("x is less than zero")
*********************************
while (condition):
statement
statement #it can be a counter-update statement
etc.
print("Finished!")
Output:
1 2 3 Finished! 1 Hi 2 Hi 3 Hi Finished!
Ex4:
Write a Python program that receives positive values then prints them, the loop will stop if the
user enters negative value.
Solutions:
flag = True
while(flag):
number = int(input("Please enter a positive num: "))
if(number >= 0):
print(number)
else:
flag = False
while(True):
number = int(input("Please enter a positive num: "))
if(number >= 0):
print(number)
else:
break
Examples: Output:
range(0, 5, 1) #[0, 1, 2, 3, 4] #(start, stop, step)
range(0, 5) #[0, 1, 2, 3, 4] #(start, stop)
range(5) #[0, 1, 2, 3, 4] #(stop)
Note: when step is positive, the start must be less than stop (start < stop)
range(0, 11, 2) #[0, 2, 4, 6, 8, 10]
range(1, 10, 2) #[1, 3, 5, 7, 9]
Note: when step is negative, the start must be greater than stop (start > stop)
range(10, 0, -1) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
range(10, 0, -2) #[10, 8, 6, 4, 2]
range(9, 0, -2) #[9, 7, 5, 3, 1]
Examples:
Ex1:
Ex2:
print("Even Numbers from 0 to 10")
for num in range(0, 10, 2):
print("The number is: ", num)
Ex3:
print("Odd Numbers from 0 to 10")
for num in range(1, 10, 2):
print("The number is: ", num)
Ex4:
print("All Numbers from 10 to 1")
for num in range(10, 0, -1):
print("The number is: ", num)
Ex6:
Ex7:
Ex8:
Ex9:
Output Sample:
Number Square
------------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Code:
print ("Number\tSquare")
print ("------------")
#Print the numbers 1 through 10 and their squares.
for number in range (1, 11):
square = number ** 2
print (number, "\t\t", square)
Example2:
Write a python program that prints the following sequence:
5 9 13 17 21
Code:
for i in range(5, 22, 4):
print(i, end= " ")
Example3:
Write a Python program reads an integer from the user and prints its factorial.
Output Sample:
Please, Enter an integer: 5
5! = 120
Example4:
Write a Python program that reads a sequence of positive integers and sums them. A negative
integer should stop the input.
Output Sample:
Enter a positive value: 5
Enter a positive value: 4
Enter a positive value: -3
Summation = 9
Code:
sum = 0
num= int(input ("Enter a positive value: "))
while (num>=0):
sum += num
num= int(input ("Enter a positive value: "))
print ("Summation = ", sum)
Example5:
Write a Python program that reads integer numbers and finds their product, each time keep asking
the user to continue or not.
Output Sample:
Please, enter an integer: 11
Do you want to continue? (Y/N): y
Please, enter an integer: 5
Do you want to continue? (Y/N): n
Result = 55
Code:
prod = 1
finished = False
while (not finished):
num = int(input("Please, enter an integer: "))
prod *= num
respond = input ("Do you want to continue? (Y/N): ")
➢ Nested Loop
There are many forms for nested loop: (for-for, while-while, for-while, while-for), you can
choose any one. Try to solve these problems:
Code:
for row in range (1, 6):
for star in range(row):
print("*", end = "")
print(" ")
Code:
sum = 0
for i in range(6):
for j in range(11):
sum += (i + 2 * j)
print("The sum is: ", sum)
Ex1: break_statement
for i in range(6):
if(i == 3):
break
print(i)
print("Done!!")
Continue Statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.
Ex1: continue_statement
for i in range(6):
if(i == 3):
continue
print(i)
print("Done!!")
Code:
prod = 1
while (True):
num= int(input("Please, enter an integer: "))
prod *= num
respond = input ("Do you want to continue? (Y/N): ")
if respond == "n" or respond == "N":
break
print("Result = ", prod)
Re-write the code in the previous example, but by ignoring the negative numbers.
Hint: you can use break and continue commands.
Code:
prod = 1
while (True):
num= int(input ("Please, enter an integer: "))
if (num<0):
print("Negative integers are ignored, try again")
continue
prod *= num
respond = input ("Do you want to continue? (Y/N): ")
if respond == "n" or respond == "N":
break
print ("Result = ", prod)
*********************************