Lecture_3
Lecture_3
Programming
Lecture 3
● Python Syntax
● Python comments
● Revision (Python Variables)
● Exercises
● Revision (Python Casting)
● Formatting Output
● Python Data Types
● Python Data Types (Numbers)
● Python Data Types (Strings)
Python Syntax
Python Syntax
Python Indentation : Indentation refers to the spaces at the beginning of a code line.
Example 1:
space We can’t have an indentation in the first
line of the code. That’s why the Python
interpreter throws Indentation Error.
>>> x = 10
print(x)
Page - 4
Python Syntax
Python Indentation : Indentation refers to the spaces at the beginning of a code line.
if 5 > 2:
print("Five is greater than two!")
Page - 5
Python Syntax
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.
Example
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
Example if True:
Example print("true")
space?
print("Hi")
else:
Syntax Error: print("false")
if 5 > 2:
print("Five is greater than two!")
Page - 6 print("Five is greater than two!")
Python Syntax
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.
Example
def foo():
print("Hi")
if True:
print("true")
else:
print("false")
print("Done")
Page - 7
Comments
Comments
Creating a Comment
Comments in Python:
#This is a comment.
print("Hello, World!")
Example
print("Hello, World!") #This is a comment
Example
#print("Hello, World!")
print("Cheers, Mate!")
Page - 9
Comments
Creating a Comment
Multiline Comments: you can add a multiline string (triple quotes) in your code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
OR
To add a multiline comment, you could insert a # for each line:
#This is a comment
#written in
#more than just one line
Page - 10
print("Hello, World!")
Revision (Python Variables)
Python Variables
Variables:
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
Variables:
Variables are containers for storing data values.
Variables do not need to be declared with any particular type and can even change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
Page - 13
print(type(y))
Python Variables
Variables:
Variables are containers for storing data values.
Single or Double Quotes?
String variables can be declared either by using single
or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
Page - 14
#A will not overwrite a
Python Variables
Integers:
Variables: x = int(1) # x will be 1
Variables are containers for storing data values. y = int(2.8) # y will be 2
z = int("3") # z will be 3
Casting
If you want to specify the data type of a Floats:
variable, this can be done with casting. 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
Example w = float("4.2") # w will be 4.2
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0 Strings:
x = str("s1") # x will be 's1'
print(type(x))
y = str(2) # y will be '2'
print(type(y))
z = str(3.0) # z will be '3.0'
print(type(z))
Page - 15
Python Variables
Variables:
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: Legal variable names:
myvar = "John"
•A variable name must start with a letter or the underscore
my_var = "John"
character
_my_var = "John"
•A variable name cannot start with a number
myVar = "John"
•A variable name can only contain alpha-numeric
MYVAR = "John"
characters and underscores (A-z, 0-9, and _ )
myvar2 = "John"
•Variable names are case-sensitive (age, Age and AGE are
three different variables) Illegal variable names:
•A variable name cannot be any of the Python keywords. 2myvar = "John"
my-var = "John"
Page - 16 my var = "John"
Keyword Description
and A logical operator
as To create an alias
Python Variables
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
Variables: elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
Variable Names. False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if there is an exception or
•A variable name cannot be any of for
not
To create a for loop
the Python keywords. from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
Page - 17 while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator
Python Variables
Variables: Variable Names.
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Page - 18
Python Variables
Variables:
Assign Multiple Values
Page - 19
Python Variables
Variables:
Assign Multiple Values
❖ Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Example
Unpack a list:
Global variables can be used by everyone, both inside of functions and outside.
ExampleG
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Page - 21
Python Variables
Variables: Global Variables
If you create a variable with the same name inside a function, this variable will be local,
and can only be used inside the function. The global variable with the same name will
remain as it was, global and with the original value
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x) Output
myfunc()
Python is fantastic
print("Python is " + x) Python is awesome
Python Variables
Variables: Global Variables
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
Page - 23
print("Python is " + x)
Python Variables
Variables:
Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "awesome" x = "awesome"
x = "Python is awesome"
print(x)
Example
x = 5
y = 10
print(x + y)
In the print() function, when you try to The best way to output multiple variables in
combine a string and a number with the print() function is to separate them with commas, which
the + operator, Python will give you an even support different data types:
error:
Example
Example
x = 5
y = "John" Error x = 5
print(x + y) y = "John"
print(x, y)
Exercises
Exercise: Find incorrect strings, why?
Page - 28
Data Types: String
a = "Hello"
print(a)
string
b = 'Ahmed'
print(b)
"Hello" 'Ahmed'
c = a + b String must starts and ends with “ or ‘
print(c)
Page - 29
String Concatenation
You can save print("Your name is: ", first_name + " " + last_name)
concatenated result into
print("Thank you ", first_name + " " + last_name)
another variable or output
it directly. full_name = first_name + " " + last_name
Page - 31
Data Types: Conversion
Page - 32
Data Types: Conversion
message = "Dear, " + name + " your age is " + age + " and your weight is " + weight;
print(message)
Page - 33
Data Types: Conversion
message = "Dear, " + name + " your age is " + str(age) + " and your weight is " + str(weight)
print(message)
#correction
Page - 34
Data Types: Conversion
Page - 35
Data Types: Conversion with Round/Floor/Ceil
rounded_percentage = round(percentage)
round: round the fraction
print('Your percentage is ' + str(rounded_percentage))
EX: 7.8 → 8, 7.2→7, -8.2→-8, -8.7→-9
import math
ceiled_percentage = math.ceil(percentage)
print('Your percentage is ' + str(ceiled_percentage)) ceil: round the fraction up
EX: 7.8 → 8, 7.2→8, -8.2→-8, -8.7→-8
Page - 36
Expressions: Variables update and Self Assignment
final_degree = 0
final_degree = final_degree + int(input('provide your degree in math: '))
final_degree += int(input('provide your degree in physics: '))
final_degree += int(input('provide your degree in english: '))
print('your final degree is ', final_degree)
Page - 37
Exercise: Suggest correction?
x = "5.5"; y = 6; y += x; print(y)
x = 1 + 2j
y = 3 - 4j
a = x + y
b = x - y
c = x * y
d = x / y
print(a, b, c, d)
Page - 39
Data Types: Complex Numbers
Page - 40
Revision (Python Casting)
Python Casting
Casting Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
If you want to specify the data type of a
Floats:
variable, this can be done with casting.
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
Example
w = float("4.2") # w will be 4.2
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0 Strings:
x = str("s1") # x will be 's1'
print(type(x))
y = str(2) # y will be '2'
print(type(y))
z = str(3.0) # z will be '3.0'
print(type(z))
Page - 42
Formatting Output
Formatting output
print("Hello " + name + " your age is " + str(age) + " and your weight is " +
str(weight))
Page - 44
Formatting output, keep the alignment
x = 5
y = 99
z = 663456
m = 989
import math
x = 2/3 precision of 3
y = 0.0000009 0.667
precision of 1
0.7
.1 precision of 1 .2 precision of 2
name = "Ahmed"
age = 28
weight = 76.5
print("Hello {} your age is {} and your weight is {}. ".format(name, age, weight))
print("Hello {2} your age is {1} and your weight is {0}. ".format(age, weight, name))
print("Hello {0} your data:\nName: {0}\nAge: {1}\nWeight: {2}".format(name, age, weight))
Page - 47
Python Data Types
Python Data Types
Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Page - 49
None Type: NoneType
Python Data Types
Data Types
You can get the data type of any object by using the type() function:
Example
Page - 50
Python Data Types
Data Types
Page - 51
Python Data Types
Data Types
Page - 52
Python Data Types (Numbers)
Python Data Types (Python Numbers)
Data Types: Python Numbers
There are three numeric types in Python:
•int
•float
•complex
int float
Float, or "floating point number" is a number, positive or
Int, or integer, is a whole number, positive or negative,
negative, containing one or more decimals.
without decimals, of unlimited length.
Example
Example
Floats:
Integers:
x = 1.10
x = 1
y = 1.0
y = 35656222554887711
z = -35.59
z = -3255522
print(type(x))
print(type(x))
print(type(y))
print(type(y))
print(type(z))
print(type(z))
Python Data Types (Python Numbers)
Data Types: Python Numbers
There are three numeric types in Python:
•int
•float
•complex
Complex
Complex numbers are written
with a "j" as the imaginary part:
Example
x = 1 # int
Example y = 2.8 # float
Complex: z = 1j # complex
x = 3+5j To verify the type of any object in Python, use
y = 5j the type() function:
z = -5j
Example
print(type(x)) print(type(x))
print(type(y)) print(type(y))
print(type(z)) print(type(z))
Python Data Types (Strings)
Python Data Types (Strings)
Data Types: Python Strings
Multiline Strings
Assign String to a Variable
Assign String to a Variable You can assign a multiline string to a variable by
Assigning a string to a using three quotes:
variable is done with the
variable name followed by Example
an equal sign and the
string: You can use three double quotes Or three
single quotes:
Example
a = """Lorem ipsum dolor sit amet,
a = "Hello" consectetur adipiscing elit,
print(a) sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Python Data Types (Strings)
Data Types: Python Strings
Strings are Arrays
Square brackets can be used to access elements of the
string.
Example
Get the character at position 1 (remember that
the first character has the position 0):
a = "Hello, World!"
print(a[1])
Output letter e
Python Data Types (Strings)
Data Types: Python Strings
Looping Through a String String Length
Example Example
Loop through the letters in the word "banana": The len() function returns the length of a string:
for x in "banana":
print(x) a = "Hello, World!"
print(len(a))
b
a : 13
Output n
a
n
a
Python Data Types (Strings)
Data Types: Python Strings
Check String
To check if a certain phrase or character is Use it in an if statement:
present in a string, we can use the
keyword in.
Example
Example
Print only if "free" is present:
Check if "free" is present in the following text: txt = "The best things in life are free!"
if "free" in txt:
txt = "The best things in life are free!" print("Yes, 'free' is present.")
print("free" in txt)
Check if NOT
Use it in an if statement:
By leaving out the start index, the By leaving out the end index, the range will
range will start at the first go to the end:
character: Example
Example Get the characters from position 2, and all
the way to the end:
Get the characters from the start
to position 5 (not included): b = "Hello, World!"
print(b[2:])
b = "Hello, World!"
print(b[:5])
Negative Indexing
Example
b = "Hello, World!"
print(b[-5:-2]) 𝐛[𝟏: 𝟒] is 'ell' -- chars starting at index 1 and
orl
Output: orl extending up to but not including index 4
orl
orl
orl
ExampleGet your own Python Serv Use the format() method to insert
Wrong numbers into strings:
age = 36
txt = "My name is John, I am " + age
age = 36
print(txt) txt = "My name is John, and I am {}"
String integer print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
txt = "Hello\nWorld!"
print(txt)
txt = "Hello\tWorld!"
print(txt)