Python Basics

Python Basics

Python is a high-level programming language that can be used in various applications. For example, it can be used in web development, desktop app development and it can be even used in machine learning.


Why to learn Python?

  1. Easy syntax

  2. Can be used in different applications

  3. Large and active community


Print function

print("Hello, world!")

The print function is used to display a message on the screen. The message can be a text, a number or it can be any other element. The code above prints the sentence Hello, world!

Variables

We can think about variables as boxes that can store objects. Variables can be used to store values.

In the code below, we assigned the value (Reem) to the variable (name). In other words, the variable (name) stores the value (Reem).

name = "Reem"

In this code, we stored the value (21) to the variable (age).

age = 21

You can notice that texts should be inserted into quotation marks:

name = "Reem"   #This is correct
name = 'Reem'   #This is correct too
name = Reem     #This is incorrect

How to name a variable?

  • It must start with an alphabetical letter or an underscore (_)

  • It can include numbers, letters and underscores

  • Reserved words are unallowed

Reserved words are words that already exist in the programming language.

Examples of reserved words:

if

elif

else

while

for

break

continue

def

class

and much more.

Important notes:

  • When you name a variable, make sure that the name is understandable to help your code become more readable and easy to understand.

  • Variables in Python are case-sensitive. the variable name is different from the variable Name or nAme.

Input function

This function helps your program become more interactive by taking input from the user.

The code below asks the user to enter their name.

name = input("What's your name?")

To use this function you can set a prompt to make your program more understandable. The prompt in this code is "What's your name?".

Comments

Comments can help you document your code and make it more readable. Comments start with a hash mark (#).

#A program that prints "Hello, world!"
print("Hello, world!")

Data types

Data can take different forms. Examples of data types:

Numerical data types:

  • Integer: is a number without a decimal point. examples: 1, 2000, -123

  • Float: is a number with a decimal point. examples: 1.25, -2.3456

String: text. examples: "Hello, world!", "Reem"

boolean: it only contains 2 values: True, False

There are other data types and we will mention them later on.

Mathematical operations

SignExplanationExampleResult
+Addition3 + 25
-Subtraction4 - 13
*Multiplication3 * 515
/Float division: return the whole division result20 / 63.3333333333333335
//Integer division: return the integer part of the division result20 // 63
%Division remainder20 % 62
sum = 3 + 2                 # result: 5
minus = 4 - 1               # result: 3
mult = 3 * 5                # result: 15
float_div = 20 / 6          # result: 3.3333333333333335
int_div = 20 // 6           # result: 3
remainder = 20 % 6          # result: 2

Comparison operators

You can use these operators to compare between values

signexplanationexampleresult
\>greater than5 > 3True
<less than6 < 2False
\>=greater than or equal to8 >= 8True
<=less than or equal to9 <= 7False
\==equal to4 == 4True
!=not equal to1 != 3True
result = 5 > 3    #result: True
print(result)

Logical operators

These operators can be used to combine multiple statements or conditions. These operators return boolean values. Logical operators in Python, are and, or and not.

We can understand these operators using truth tables.

Let A and B be statements:

And operator:

This operator checks if all statements are true or not. This operator returns true if all statements are true.

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
a = (3 > 2)                  #return True
b = (5 <= 6)                 #return True
print(a and b)               #return True

Or operator:

This operator checks if there is at least one true statement or not. This operator returns true if at least one statement is true.

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
a = (3 > 2)                  #return True
b = (5 <= 1)                 #return False
print(a or b)                #return True

Not operator:

This operator accepts only one statement and it's used to negate a statement.

Anot A
TrueFalse
FalseTrue
a = 3 > 2        #return True
print(not a)     #return False

Conditional statements:

Do you want to execute some pieces of code according to certain conditions? If yes, you will need to use conditional statements.

There are 3 forms of conditional statements:

  • if statement

  • if-else statement

  • elif statement

if statement:

In this statement the instructions in the "if" block will be executed if the conditions are satisfied. Otherwise, nothing in the block will be executed.

How to write an if statement?

if (condition):
    #statement 1
    #statement 2
    #etc

Indentations are important because they are used to represent that the statements belong to a block of code (in this case, the "if" block).

example:

num = 5
if num > 2:
    print("The condition is true")

The code above will print The condition is true because 5 is greater than 2. This flowchart can visualize the code above

You can also use multiple conditions as we can see in the code below:

num = 10
if num > 2 and num < 8:
    print("The condition is true")

In this code, nothing in the block will be executed because 10 is not less than 8.

if-else statement:

The if-else statement can be used to handle both true and false conditions.

if condition:
    #some statements
else:
    #other statements
  • If the condition is true, the statements in the "if" block will be executed.

  • If the condition is false, the statements in the "else" block will be executed.

Example:

num = 10
if num > 2 and num < 8:
    print("The condition is true")
    print("10 is greater than 2 and less than 8")
else:
    print("The condition is false")
    print("10 is not greater than 2 and less than 8")

This code will print The condition is false and 10 is greater than 2 and 8

elif statement:

elif is an abbreviation for else if. You can use it if a condition is not satisfied and you need to check if another condition is true or not.

if condition1:
    #statement(s)
elif condition2:
    #statement(s)
else:
    #statement(s)

Example:

num = 12
if num >= 0 and num < 5:
    print("1st condition is satisfied")
elif num >= 5 and num < 10:
    print("2nd condition is satisfied")
elif num >= 10 and num < 15:
    print("3rd condition is satisfied")
else:
    print("all conditions are not satisfied")
  1. we created a variable with a value of 12

  2. check if the number is between 0 and 4

  3. check if the number is between 5 and 9

  4. check if the number is between 10 and 14

  5. if all conditions are false, print all conditions are not satisfied

Loops

Do you want to repeat your code for multiple times? Look no further, loops can help you run your code repeatedly.

There are 2 types of loops in Python:

  • For loop

  • While loop

For loop

This loop can be used to iterate over sequences such as strings and lists. In addition, it can be used to iterate in a fixed number of times.

for i in sequence:
    #statement 1
    #statement 2
    #etc

Examples:

Suppose you want to print the numbers from 0 to 99. You can use the range function to store a sequence of numbers. After that, you can use a for loop to print the numbers.

There are 3 ways to use the range function:

  • range(start_point, end_point, steps)

  • range(start_point, end_point) : is the same as range(start_point, end_point, 1)

  • range(end_point): is the same as range(0, end_point, 1)

In this code, we printed the numbers from 0 to 99 by defining only the end_point in the range function.

for i in range(100):
    print(i)

In the code below, we printed the numbers from 1 to 100 by defining the start_point and end_point in the range function.

for i in range(1, 101):
    print(i)

In this code, we printed the even numbers between 0 and 10 by defining the start_point, end_point and steps in the range function.

for i in range(0, 11, 2):
    print(i)

While loop

This loop checks the condition before executing the statements in the block. If the condition is satisfied, the statements will be executed. Otherwise, the loop will stop.

while condition:
    #statement 1
    #statement 2
    #etc

Example:

We want to write a program that prints the numbers from 1 to 10

  1. in the beginning, we will create a variable that stores numbers. The initial value for this variable will be 1

  2. check if the condition is true or not (is the current number less than 11?)

  3. if the condition is true, the current number will be printed and incremented by 1.

  4. As long as the condition is satisfied, the block will be executed. Otherwise, the loop will stop

num = 1
while num < 11:
    print(num)
    num += 1    #same as num = num + 1