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

Basic Session1

The document provides an overview of the Python programming language, including what it is, what it can be used for, why it is popular, how to install it and set it up, basic syntax like variables, data types, operators, and examples of common operations.

Uploaded by

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

Basic Session1

The document provides an overview of the Python programming language, including what it is, what it can be used for, why it is popular, how to install it and set it up, basic syntax like variables, data types, operators, and examples of common operations.

Uploaded by

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

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.

print("Hello, World!")
Python Install
• python –version

The Python Command Line


python helloworld.py
Python Indentation
• if 5 > 2:
print("Five is greater than two!")

• if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Comments
• Comments start with a #, and Python will render the rest of the line
as a comment:

#This is a comment.
print("Hello, World!")
Multi Line Comments
#This is a comment
#written in
#more than just one line
print("Hello, World!")

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
• In Python, variables are created when you assign a value to it:
• Python has no command for declaring a variable.
x=5
y = "Hello, World!“
Print(x)
Creating Variables
•x=5
y = "John"
print(x)
print(y)

• Variables do not need to be declared with any particular type, and can
even change type after they have been set.
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
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
Print(z)
Get the Type
• You can get the data type of a variable with the type() function
•x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:

x = "John"
# is the same as
x = 'John'
Case-Sensitive
• Variable names are case-sensitive.
a=4
A = "Sally"
#A will not overwrite a
A=4
a=4
Print(a)
Variable Names
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Multi Words Variable Names
• Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

• Pascal Case
Each word starts with a capital letter:
MyVariableName = "John“

• Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Python Variables - Assign Multiple Values
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables
• x = “Good"
print("Python is " + x)

• x = "Python is "
y = “good"
z= x+y
print(z)

•x=5
y = 10
print(x + y)
Global Variables
• x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
The global Keyword
• def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
• x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)
• x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
Python Data Types
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
Getting the Data Type
•x=5
print(type(x))
Setting the Data Type
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range
x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset


x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set


x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = ["apple", "banana", "cherry"]

#display x:
print(x)

#display the data type of x:


print(type(x))
Python 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
w = float("4.2") # w will be 4.2

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Strings
• Strings in python are surrounded by either single quotation marks, or double quotation marks.
print("Hello")
print('Hello')

Multiline Strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays


a = "Hello, World!"
print(a[1])
• Looping Through a String
for x in "banana":
print(x)

• String Length
a = "Hello, World!“
print(len(a))

• Check String
a = "The best things in life are free!"
print("free" in a) // true

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


if "free" in txt: // true or false
print("Yes, 'free' is present.")
• Check if NOT
txt = "The best things in life are free!"
print("expensive" not in txt) //true

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


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
• Slicing
You can return a range of characters by using the slice syntax.
b = "Hello, World!"
print(b[2:5])

• Slice From the Start


b = "Hello, World!"
print(b[:5])

• Slice To the End


b = "Hello, World!"
print(b[2:])

• Negative Indexing
b = "Hello, World!"
print(b[-5:-2])
Python - Modify Strings
• Upper Case
a = "Hello, World!"
print(a.upper())

• Lower Case
a = "Hello, World!"
print(a.lower())

• Remove Whitespace
a = “ Hello, World! "
print(a.strip()) # returns "Hello, World!“

• Replace String
a = "Hello, World!"
print(a.replace("H", "J"))
• Split String
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

• String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c) //HelloWorld

a = "Hello"
b = "World"
c = a + " " + b //)
print(c) //Hello World
• insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
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))

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))
• Python Booleans
a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a“)
x = "Hello"
y = 15

print(bool(x))
print(bool(y))
Python Operators
• Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise 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
Python Assignment Operators
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
&= x &= 3 x=x&3
Python Comparison Operators
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Python Logical Operators
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Identity Operators


Operator Description Example
is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same object x is not y
Python Membership Operators
Operator Description Example
in Returns True if a sequence with the specified value is present in the x in y
object

not in Returns True if a sequence with the specified value is not present in the x not in y
object

x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost
bits fall off

x=2
print(x<<1)

You might also like