What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
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 can be treated in a procedural way, an object-oriented way or a
functional way.
Variables
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Syntax Rule for Variable
Start with lowercase letter or uppercase letter or underscore(_).
It is case sensitive.
A variable name cannot start with a number.
Must be single word without any space.
Data type specification not required.
Keywords are not allowed as a variable name.
Example
S_roll = 5
S_name = "John"
print(S_roll)
print(S_name)
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
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)
Global Variables
Variables that are created outside of a function are known as global
variables.
Global variables can be used by everyone, both inside of functions and
outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
output: Python is awesome
Create a variable inside a function, with the same name as the global
variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
output: Python is fantastic
Python is awesome
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()
print("Python is " + x)
output: Python is fantastic
Python print() Function
The print() function prints the specified message to the screen, or other
standard output device.
The message can be a string, or any other object, the object will be
converted into a string before written to the screen.
Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Values
Parameter Description
object(s) Any object, and as many as you like. Will be
converted to string before printed
sep='separator Optional. Specify how to separate the objects, if
' there is more than one. Default is ' '
end='end' Optional. Specify what to print at the end. Default is
'\n' (line feed)
file Optional. An object with a write method. Default is
[Link]
flush Optional. A Boolean, specifying if the output is
flushed (True) or buffered (False). Default is False
Python input() Function
It is a built in function in Python to take input from user.
Syntax
input(prompt)
Prompt: A String, representing a default message before the input.
(optional)
Example
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)
User input always taken as a string.
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y [it take only the floor value of the
result. Ex. 13//2 result=6]
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Python Comparison Operators
Comparison operators are used to compare two values:
Operator Name Example Try it
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal x >= y
to
<= Less than or equal to x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements x < 5 and x <
are true 10
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x
False if the result is true < 10)
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location:
Operator Description Example Try it
is Returns True if both variables x is y
are the same object
is not Returns True if both variables x is not y
are not the same object
Python Membership Operators
Membership operators are used to test if a sequence is presented in an
object:
Operator Description Example Try
it
in Returns True if a sequence with x in y
the specified value is present in
the object
not in Returns True if a sequence with x not in y
the specified value is not present
in the object
Decision Making Statement in Python
if statement
if – else statement
if-elif-else statemrnt
nested if-else statement
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
if-elif-else statement:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.
Example
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional
Expressions.
Nested If-else
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The Python Match Statement
Instead of writing many if..else statements, you can use
the match statement.
The match statement selects one of many code blocks to be executed.
Syntax
match expression:
case x:
code block
case y:
code block
case z:
code block
This is how it works:
The match expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The example below uses the weekday number to print the weekday name:
Example
day = 4
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
Default Value
Use the underscore character _ as the last case value if you want a code
block to execute when there are not other matches:
Example
day = 4
match day:
case 6:
print("Today is Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to the Weekend")
The value _ will always match, so it is important to place it as the last case to
make it behave as a default case.
Combine Values
Use the pipe character | as or operator in the case evaluation to check for
more than one value match in one case:
Example
day = 4
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a weekday")
case 6 | 7:
print("I love weekends!")
If Statements as Guards
You can add if statements in the case evaluation as an extra condition-
check:
Example
month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")
Python Loops
Python has two primitive loop commands:
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
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:
Example: 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:
Example: 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:
Example: 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")
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through
all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
With the continue statement we can stop the current iteration of the loop,
and continue with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible
to specify the starting value by adding a parameter: range(2, 6), which
means values from 2 to 6 (but not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is
possible to specify the increment value by adding a third
parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when
the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by
a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with
no content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Track your progress - it's free!