0% found this document useful (0 votes)
8 views

Lecture_3

Another one

Uploaded by

seifh0307
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture_3

Another one

Uploaded by

seifh0307
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Introduction to Computer and

Programming
Lecture 3

© Fall 2023 – Dr.Alyaa , Dr Abdelgwad Elashry


Table of Contents

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

File "<stdin>", line 1


x = 10
^
Indentation Error: unexpected indent
>>>

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!")

Python will give you an error if you skip the indentation:


Why?
Syntax Error:
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 starts with a #, and Python will ignore them:

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.

File "main.py", line 1


int x = 5
int x=5;
print(x)
^
SyntaxError: invalid syntax

A variable is created the moment you first assign a value to it.


x = 5
y = "John"
Page - 12
print(x)
print(y)
Python Variables

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)

Get the Type

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.

Multi Words Variable Names


Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

Pascal Case Snake Case


Each word starts with a capital letter: Each word is separated by an underscore character:
MyVariableName = "John" my_variable_name = "John"

Page - 18
Python Variables
Variables:
Assign Multiple Values

❖ Many Values to Multiple Variables ❖ One Value to Multiple Variables


Python allows you to assign values to multiple And you can assign the same value to multiple
variables in one line: variables in one line:
Example: Example
x, y, z = "Orange", "Banana", "Cherry" x = y = z = "Orange"
print(x) print(x)
print(y) print(y)
print(z) print(z)

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:

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)
Page - 20
Python Variables
Variables: Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

ExampleG

Create a variable outside of a function, and use


it inside the function

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

Create a variable inside a function, with the


same name as the global variable

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"

def myfunc(): def myfunc():


global x
x = "fantastic" # global x
x = "fantastic"
myfunc() Output Output
myfunc()
print("Python is " + x)
Python is fantastic Python is awesome
print("Python is " + x)
Page - 24
Python Variables
Variables: Output Variables

x = "Python is awesome"
print(x)

Output multiple variables, separated by a comma:


x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:


x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Page - 25
Python Variables
Variables: Output Variables

For numbers, the + character works as a mathematical operator:

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?

message = "Hello World"


message = Hello World"
message = "Hello World'
message = "You weight is 88"
message = You weight is 88
message = "15 + 2"
message = 15 + 2

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

Use + to concatenate first_name = input("Enter your first name")


multiple strings segments. last_name = input("Enter your second name: ")
#use semicolon to put many statements in same line
You can concatenate
print("Your name is"); print(first_name); print(last_name)
string variables or string
values directly. print("Your name is: ", first_name + last_name)

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

print("Thank you ", full_name)


Page - 30
Data Types: Conversion

#unexpected result, without conversion


math_degree = input('provide your degree in math: ')
physics_degree = input('provide your degree in physics: ')
english_degree = input('provide your degree in english: ')
final_degree = math_degree + physics_degree + english_degree
print('your final degree is ', final_degree)

Page - 31
Data Types: Conversion

math_degree = int(input('provide your degree in math: '))


physics_degree = int(input('provide your degree in physics: '))
english_degree = int(input('provide your degree in english: '))
final_degree = math_degree + physics_degree + english_degree
print('your final degree is ', final_degree)

math_degree = float(input('provide your degree in math: '))


physics_degree = float(input('provide your degree in physics: '))
english_degree = float(input('provide your degree in english: '))
final_degree = math_degree + physics_degree + english_degree
print('your final degree is ', final_degree)

Page - 32
Data Types: Conversion

name = input('Enter your full name: ')


age = int(input('Enter your age: '))
weight = float(input('Enter your weight: '))

message = "Dear, " + name + " your age is " + age + " and your weight is " + weight;

print(message)

#error, can only concatenate str


(not "int") to str

Page - 33
Data Types: Conversion

name = input('Enter your full name: ')


age = int(input('Enter your age: '))
weight = float(input('Enter your weight: '))

message = "Dear, " + name + " your age is " + str(age) + " and your weight is " + str(weight)

print(message)

#correction

Page - 34
Data Types: Conversion

degree = float(input('Enter your degree: '))


max_degree = int(input('Enter the max degree: '))

percentage = 100 * (degree/max_degree)


print('Your percentage is ' + str(percentage))

int_percentage = int(percentage) Int: remove the fraction


print('Your percentage is ' + str(int_percentage)) EX: 7.8 → 7, 7.2→7, -8.2→-8, -8.7→-8

Page - 35
Data Types: Conversion with Round/Floor/Ceil

#append to last program

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

floored_percentage = math.floor(percentage) floor: round the fraction down


print('Your percentage is ' + str(floored_percentage)) EX: 7.8 → 7, 7.2→7, -8.2→-9, -8.7→-9

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?

age = 5; print('your age is ' + age)

message = "your degree in math is " + 16; print(message)

x = "5.5"; y = 6; y += x; print(y)

degree += 90; degree = degree + 80; degree = degree + 88; print(degree)

degree = 77; max_degree = 90; percentage = round(100 * degree/max_degree, 1);


print("Your percentage is " + str(percentage) + %)
print("Your percentage is ", str(percentage), "%")

x = "88.6"; x += 15.5; print(x)


Page - 38
x = "88.6"; x += "15.5"; print(x)
Data Types: Complex Numbers

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

x = complex(input("Enter x complex value:"))


y = complex(input("Enter y complex value:"))
a = x + y
b = x - y
c = x * y
d = x / y
print(a, b, c, d)

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

name = input("Enter your name:")


age = int(input("Enter your age:"))
weight = float(input("Enter your weight:"))

print("Hello " + name + " your age is " + str(age) + " and your weight is " +
str(weight))

print("Hello %s your age is %d and your weight is %f"%(name, age, weight))

Page - 44
Formatting output, keep the alignment

x = 5
y = 99
z = 663456
m = 989

print("x = %d, y = %d"%(x, y)) x=5 y=99


print("z = %d, m = %d"%(z, m))

It will be printed with 8 characters X= 5


print("x = %8d, y = %8d"%(x, y))
print("z = %8d, m = %8d"%(z, m))
7spaces then 5
Formatting output, keep the alignment and limit the fraction

import math

x = 2/3 precision of 3
y = 0.0000009 0.667

z = math.pow(99, 15) precision of 2


print("x = %f, y = %f, z = %f"%(x, y, z)) 0.67

precision of 1
0.7
.1 precision of 1 .2 precision of 2

print("x = %.1f, y = %.2f "%(x, y))


print("x = %11.3f, y = %11.3f, z = %11.3e"%(x, y, z))
.3 precision of 3
Formatting output, another way
.format

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:

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Page - 49
None Type: NoneType
Python Data Types
Data Types

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x:


x = 5
print(type(x))

Page - 50
Python Data Types
Data Types

Example Data Type


x = str("Hello World") str Text Type
x = int(20) int Numeric Types
x = float(20.5) float Numeric Types
x = complex(1j) complex Numeric Types
x = list(("apple", "banana", "cherry")) list Sequence Types
x = tuple(("apple", "banana", "cherry")) tuple Sequence Types
x = range(6) range Sequence Types

Page - 51
Python Data Types
Data Types

x = dict(name="John", age=36) dict Mapping Type


x = set(("apple", "banana", "cherry")) set Set Types
x = frozenset(("apple", "banana", "cherry")) frozenset Set Types
x = bool(5) bool Boolean Type
x = bytes(5) bytes Binary Types
x = bytearray(5) bytearray Binary Types
x = memoryview(bytes(5)) memoryview Binary 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

Since strings are arrays, we can loop through the


characters in a string, with a for loop. To get the length of a string, use the len() function.

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)

Output : True Output : Yes, 'free' is present.


Python Data Types (Strings)
Data Types: Python Strings

Check if NOT
Use it in an if statement:

To check if a certain phrase or character is NOT


present in a string, we can use the keyword not in. Example

Example print only if "expensive" is NOT present:

txt = "The best things in life are free!"


Check if "expensive" is NOT present in the following if "expensive" not in txt:
text: print("No, 'expensive' is NOT present.")

txt = "The best things in life are free!"


print("expensive" not in txt)

Output : No, 'expensive' is NOT present.


Output :True
Python Data Types (Strings)
Data Types: Python Strings (Slicing Strings)
Slice From the Start Slice To the End

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

Output: Hello Output: llo, World!


orl

Python Data Types (Strings)


Data Types: Python Strings (Slicing Strings)

Negative Indexing

Use negative indexes to start the slice from


the end of the string:

Example

Get the characters:

From: "o" in "World!" (position -5)


To, but not included: "d" in "World!"
(position -2):

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

Python Data Types (Strings)


Data Types: Python Strings (Slicing Strings)
Please : practice well

orl
orl

Python Data Types (Strings)


Data Types: Python Strings (Modify Strings)
Upper Case Lower Case
Example

The upper() method returns the string in upper


Example
case:
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.upper()) a = "Hello, World!"
print(a.lower())
Out put: HELLO, WORLD!
orl

Python Data Types (Strings)


Data Types: Python Strings (Modify Strings)
Split String
Remove Whitespace Replace String
The split() method returns a list where
the text between the specified separator
becomes the list items.
Whitespace is the space before and/or
after the actual text, and very often you Example
want to remove this space. Example
Example The replace() method replaces a string
with another string: The split() method splits the string into
The strip() method removes any substrings if it finds instances of the
whitespace from the beginning or the end:
a = "Hello, World!" separator:
print(a.replace("H", "J"))
a = "Hello, World!"
a = " Hello, World! " print(a.split(","))
print(a.strip()) # returns "Hello, # returns ['Hello', ' World!']
World!“
What is the output ????????
print(a)
a = "Hello, World!"
b=a.split(",")
Out put: Hello, World! print(b[1])
Hello, World!
orl

Python Data Types (Strings)


Data Types: Python Strings (String Concatenation)

a = "Hello" To add a space between them, add


a " ":
b = "World"
c = a + b
a = "Hello"
print(c)
b = "World"
c = a + " " + b
print(c)

HelloWorld Hello World


orl

Python Data Types (Strings)


Data Types: Python Strings (Format – Strings)

As we learned in the Python Variables chapter, we cannot


combine strings and numbers like this:

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

Output: My name is John, and I am 36


orl

Python Data Types (Strings)


Data Types: Python Strings (Format – Strings)

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

Output: I want to pay 49.95 dollars for 3 pieces of item 567.


orl

Python Data Types (Strings)


Data Types: Python Strings (Escape Characters)

txt = "Hello\nWorld!"
print(txt)

txt = "Hello\tWorld!"
print(txt)

You might also like