Intro to python
Python is used in :
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Python can do:
• Python can be used on a server to create web applications.
• 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.
Why Python?
• Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can
be very quick.
Python Syntax compared to other
programming languages
• Python was designed for readability, and has some similarities
to the English language with influence from mathematics.
• 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.
Comments:
• Use the # symbol.
• # This is a comment
print("Hello") # This prints Hello
• Docstrings (special comments):
Used to explain functions, classes, or files.
def add(a, b):
""" This function adds
two numbers
and returns the result """
return a + b
Python
variables
Variables:
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any particular type, and can even
change type after they have been set.
• A variable is a name that stores a value in memory so we can use it later.
Global Variables :
• Variables that are created outside of a function
• Global variables can be used by everyone, both inside of functions and outside.
• x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Variables names:
01 02 03 04 05
A variable name must A variable name A variable name can Variable names are A variable name
start with a letter or cannot start with a only contain alpha- case-sensitive (age, cannot be any of
the underscore number numeric characters Age and AGE are the Python keywords.
character and underscores (A- three different
z, 0-9, and _ ) variables)
Casting:
x = str(3) y = int(3)
z = float(3)
# x will be '3’ # y will be 3
# z will be 3.0
Data types:
Data types:
• How to check the type of a certain variable:
x=10
print(type(x))
• We can not mix two data types in an operation together:
print(10 + "5") # ❌ Error
print(10 + int("5")) # ✅
Strings
Strings
• Strings in python are surrounded by either single quotation marks, or double
quotation marks.
• print("Hello")
print('Hello’)
• You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
• print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny“’)
• You can assign a multiline string to a variable by using three quotes
Strings
• Strings are arrays
• Square brackets can be used to access elements of the string.
• a = "Hello, World!"
print(a[1])
• To loop through a string:
• for x in "banana":
print(x)
• The len() function returns the length of a string:
• a = "Hello, World!"
print(len(a)) #13
Strings
• To check if a certain phrase or character is present in a string, we can use the
keyword in.
• Check if "free" is present in the following text:
• txt = "The best things in life are free!"
print("free" in txt)
• txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Slicing Strings
• You can return a range of characters by using the slice syntax.
• Get the characters from position 2 to position 5 (not included):
• b = "Hello, World!"
print(b[2:5])
• Get the characters from the start to position 5 (not included):
• b = "Hello, World!"
print(b[:5])
• Get the characters from position 2, and all the way to the end:
• b = "Hello, World!"
print(b[2:])
• Use negative indexes to start the slice from the end of the string:
• b = "Hello, World!"
print(b[-5:-2]) #orl
Modify Strings
1 2 3 4 5 6 7 8 9
Python has a The upper() a = "Hello, The lower() a = "Hello, The strip() m a = " Hello, The replace( a = "Hello,
set of built-in method World!" method World!" ethod World! " ) method World!"
methods that returns the print([Link] returns the print([Link]( removes any print([Link]() replaces a print([Link]
you can use string in ()) string in )) whitespace ) # returns string with e("H", "J"))
on strings. upper case: lower case: from the "Hello, another
beginning or World!“ string:
the end:
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
• Merge variable a with variable b into variable c:
• a = "Hello"
b = "World"
c=a+b
print(c)
• To add a space between them, add a " ":
• a = "Hello"
b = "World"
c=a+""+b
print(c)
String Format
• To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.
• age = 36
txt = f"My name is John, I am {age}"
print(txt)
• A placeholder can contain variables, operations, functions, and modifiers to format the value.
• price = 59
txt = f"The price is {price} dollars"
print(txt)
• A modifier is included by adding a colon : followed by a legal formatting type, like .2f which
means fixed point number with 2 decimals:
• price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
If statement
Python Conditions and If statements
• 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
Python Conditions and If statements
• a = 33
b = 200
if b > a:
print("b is greater than a")
• The if statement evaluates a condition (an expression that results
in True or False). If the condition is true, the code block inside the if statement is
executed. If the condition is false, the code block is skipped.
• number = 15
if number > 0:
print("The number is positive")
• is_logged_in = True
if is_logged_in:
print("Welcome back!")
Python Conditions and If statements
• The Elif Keyword
• The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
• a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Short Hand If
• If you have only one statement to execute, you can put it on the same line as
the if statement.
• a=5
b=2
if a > b: print("a is greater than b")
• If you have one statement for if and one for else, you can put them on the same
line using a conditional expression:
• a=2
b = 330
print("A") if a > b else print("B")
When to use Short Hand If:
Shorthand if statements and ternary operators should be used when:
• The condition and actions are simple
• It improves code readability
• You want to make a quick assignment based on a condition
Loops in
python
While loop
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
• Print i as long as i is less than 6:
• i=1
while i < 6:
print(i)
i += 1
The break statement
With the break statement we can stop the loop even if the while condition is true:
• Exit the loop when i is 3:
• i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue statement
With the continue statement we can stop the current iteration, and continue with the
next:
• Continue to the next iteration if i is 3:
• i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else statement
With the else statement we can run a block of code once when the condition no
longer is true:
• Print a message once the condition is false:
• i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
for loop
For loop:
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
• Print each fruit in a fruit list:
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
For loop
Looping Through a String: The break Statement The continue Statement
• Even strings are iterable • With the break statement we • With the continue statement we
objects, they contain a can stop the loop before it has can stop the current iteration of
sequence of characters: looped through all the the loop, and continue with the
• Loop through the letters in the items: next:
word "banana": • Exit the loop when x is • Do not print banana:
• for x in "banana": "banana": • fruits =
print(x) • fruits = ["apple", "banana", "cherry"]
["apple", "banana", "cherry"] for x in fruits:
for x in fruits: if x == "banana":
print(x) continue
if x == "banana": print(x)
break
The range() function
The range() function defaults to 0
The range() function returns a as a starting value, however it is The range() function defaults to
To loop through a set of code a sequence of numbers, starting possible to specify the starting increment the sequence by 1,
specified number of times, we can from 0 by default, and increments value by adding a however it is possible to specify
use the range() function, by 1 (by default), and ends at a parameter: range(2, 6), which the increment value by adding a
specified number. means values from 2 to 6 (but not third parameter: range(2, 30, 3):
including 6):
for x in range(6): for x in range(2, 6): for x in range(2, 30, 3):
print(x) print(x) print(x)
Nested for loop:
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop":
• adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
• Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry