0% found this document useful (0 votes)
3 views45 pages

Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features a simple syntax that emphasizes readability, supports multiple programming paradigms, and allows for rapid prototyping. Key concepts include variables, data types, control structures, and loops, which are fundamental for writing effective Python code.
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)
3 views45 pages

Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features a simple syntax that emphasizes readability, supports multiple programming paradigms, and allows for rapid prototyping. Key concepts include variables, data types, control structures, and loops, which are fundamental for writing effective Python code.
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/ 45

Python

Trainer Name: Farha Fathima S A


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.
What can Python do?

• Python can be used on a server to create web


applications.
• Python can be used alongside software to create
workflows.
• 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 can be treated in a procedural way, an object-
oriented way or a functional way.
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.
Python Indentation
Indentation refers to the spaces at the beginning of a
code line.
Where in other programming languages the indentation
in code is for readability only, the indentation in Python
is very important.
• Python uses indentation to indicate a block of code.
Example:
if 5 > 2:
print("Five is greater than two!")
Syntax Error
if 5 > 2:
print("Five is greater than two!")
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• Comments starts with #
• Example:
• #This is a comment
print("Hello, World!")
• print("Hello, World!") #This is a comment
• Multiline string comment
• """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python 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.
•x = 5
y = “Akash“
• Casting
• If you want to specify the data type of a variable, this can be done
with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type

• You can get the type of a variable with the type() function
•x = 5
y = "John"
print(type(x))
print(type(y))
• Case-Sensitive
• Variable names are case-sensitive.
• a = 4
A = "Sally"
#A will not overwrite a
• Single or double quotes
• x = "John"
# is the same as
x = ’John’
Python - 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:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
• Legal names:
• myvar = “Akash"
my_var = “Akash"
_my_var = “Akash"
myVar = “Akash"
MYVAR = “Akash"
myvar2 = “Akash“
• Illegal names:
• 2myvar = “Akash"
my-var = “Akash"
my var = “Akash"
Python Variables - Assign Multiple Values

• x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)
• x = y = z = "Orange"
print(x)
print(y)
print(z)
• fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variable
• print() function is used to output variables
• x = "Python is awesome"
print(x)
• x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
• x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
• x = 5
y = 10
print(x + y)
• x = 5
y = "John"
print(x + y)
• x = 5
y = "John“
print(x, y)
Global Variables
Variables that are created outside of a function (as in all of the examples in the previous pages) are known
as global variables.
• Global variables can be used by everyone, both inside of functions and outside.
• x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
• 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)
myfunc()
print("Python is " + x)
The global Keyword
• To create a global variable inside a function, you
can use the global keyword
• def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
Python Data Types
Text Type: str
Numeric Types: int, float, complex

Sequence list, tuple, range


Types:
Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Python Numbers

• There are 3 numeric types in Python


• Int float complexx = 1
•x = 1 # int
y = 2.8 # float
z = 1j # complex
Python Operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operator
Assignment Operator
Comparision Operator
Logical Operator
Identity Operator
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:
Membership operator
Bitwise Operator
Python If ... Else

• Python Conditions
• 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
Elif

• 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")
Else
• The else keyword catches anything which isn't caught
by the preceding conditions.
• 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")
Nested If
You can have if statements inside if statements, this is called nested if statements.

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Short Hand If

• If you have only one statement to execute, you can put


it on the same line as the if statement.
• 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:
•a = 2
b = 330
print("A") if a > b else print("B")
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
pass
Python While 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.
•i = 1
while i < 6:
print(i)
i += 1
• Note: remember to increment i, or else the loop will
continue forever.
The break Statement

• With the break statement we can stop the loop even if


the while condition is true:
•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:
•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:
•i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
• Print a message once the condition is false:
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).
This is less like the for keyword in other programming
languages, and works more like an iterator method as found
in other object-orientated programming languages.
• With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
• The for loop does not require an indexing variable to set
beforehand.
Looping Through a String

• Even strings are iterable objects, they contain a


sequence of characters:
• 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:
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The continue Statement

With the continue statement we can stop the current


iteration of the loop, and continue with the next:
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.
• for x in range(6):
print(x)
• for x in range(2, 6):
print(x)
• 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.
• for x in range(6):
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"
• 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.
• for x in [0, 1, 2]:
pass

You might also like