0% found this document useful (0 votes)
12 views64 pages

Python 1 2

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data analysis. It features a simple syntax, supports multiple programming paradigms, and allows rapid prototyping. Key concepts include variable creation, data types, operators, and control flow statements.

Uploaded by

danii.niazi007
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)
12 views64 pages

Python 1 2

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data analysis. It features a simple syntax, supports multiple programming paradigms, and allows rapid prototyping. Key concepts include variable creation, data types, operators, and control flow statements.

Uploaded by

danii.niazi007
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

Python

1
What is Python?
• 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.
2
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.

3
First program !
• print("Hello, World!")
• How to install python ???
• ANACONDA ? Or other tools? Choose it.

4
Python Syntax
• The program of [Link] can be executed by using python command
line or other visual base framework. We use Anaconda, Jupyter
notebook to test this program.
• Kindly try it using Jupyter.

5
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.
• if 5 > 2:
• print("Five is greater than two!")

6
• Python will give you an error if you skip the indentation:
• Example
• Syntax Error:
• if 5 > 2:
print("Five is greater than two!") ///error bcz print is start early.

7
• 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!")
if 5 > 2:
print("Five is greater than two!")
• Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

8
Many Statements
• Most Python programs contain many statements.
• The statements are executed one by one, in the same order as they
are written:
• Example
• print("Hello World!")
print("Have a good day.")
print("Learning Python is fun!")

9
Semicolons (Optional, Rarely Used)
• Semicolons are optional in Python. You can write multiple statements
on one line by separating them with ; but this is rarely used because it
makes it hard to read:

• Example
• print("Hello"); print("How are you?"); print("Bye bye!")

10
Print Numbers
• You can also use the print() function to display numbers:
• However, unlike text, we don't put numbers inside double quotes:
• Example
• print(3)
• print(358)
• print(50000)
• print(3 + 3)
print(2 * 5)
• print("I am", 35, "years old.")

11
Creating a Comment
• Comments starts with a #, and Python will ignore them:

• Example
• #This is a comment
print("Hello, World!")

12
Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Example
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.
• Example
• x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)

13
Python - Variable Names
• Variable Names
• A variable can have a short name (like
x and y) or a more descriptive name
(age, carname, total_volume).
myvar = "John" Illegal variable
my_var = "John" names:
_my_var = "John" 2myvar = "John"
myVar = "John"
my-var = "John"
MYVAR = "John"
myvar2 = "John" my var = "John"

14
Python Variables - Assign Multiple Values
• Many Values to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
• Example
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• x = y = z = "Orange"
print(x)
print(y)
print(z) # output?

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

16
Python - Output Variables
• Output Variables
• The print() function is often used to output variables.
• Example:
• x = "Python is awesome" You can also use the + operator
• print(x) to output multiple variables:
• Example Example
• x = "Python" x = "Python "
y = "is" y = "is "
z = "awesome" z = "awesome"
print(x + y + z)
print(x, y, z) ///output?
17
• 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 combine a string and a number with the +
operator, Python will give you an error:
• Example
• x=5
• y = "John"
• print(x + y) /// correct : print(x, y)

18
Python - Global Variables
• 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.
• E.g. Create a variable outside of a function, and use it inside the function
• x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()

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

20
Built-in Data Types
• In programming, data type is an • Boolean Type: bool
important concept. • Binary Types: bytes, bytearray,
• Variables can store data of different memoryview
types, and different types can do • None Type: NoneType
different things.
• Python has the following data types • Getting the Data Type
built-in by default, in these categories: • You can get the data type of any
• Text Type: str object by using the type() function:
• Numeric Types:int, float, complex • ExampleGet your own Python Server
• Sequence Types: list, tuple, range • Print the data type of the variable x:
• Mapping Type: dict • x=5
• Set Types: set, frozenset • print(type(x))

21
Example
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", frozenset
"cherry"})

x = True bool 22
Python Numbers
• There are three numeric types in Python:
• int
• float
• complex
• Variables of numeric types are created when you assign a value to them:

• ExampleGet your own Python Server


• x = 1 # int
• y = 2.8 # float
• z = 1j # complex Integers:
• x=1
y = 356562225
z = -3255522
print(type(x))
print(type(y))
print(type(z))

23
Python Casting
• There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.
• Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals
• Example
• Integers:
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

24
• Floats:
• 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
• Strings:
• x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

25
• Example
• print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"‘)
• Example
• You can use three double quotes:
• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

26
Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a part of the
string.
• Example
• Get the characters from position 2 to position 5 (not included):
• b = "Hello, World!"
print(b[2:5])
• Upper Case
• ExampleGet your own Python Server
• The upper() method returns the string in upper case:
• a = "Hello, World!"
• print([Link]())

27
String Concatenation

• To concatenate, or combine, two strings you can use the + operator.


• ExampleGet your own Python Server
• 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)

28
String Format
• As we learned in the Python Variables chapter, we cannot combine
strings and numbers like this:
• age = 36
#This will produce an error:
txt = "My name is John, I am " + age
print(txt)

29
Escape Character
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character you
want to insert.
• txt = "We are the so-called \"Vikings\" from the north."

30
Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string
count() Returns the number of times a specified value
occurs in a string
encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified


value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and
returns the position of where it was found 31
Boolean Values
• In programming you often need to know if an expression is True or False.

• You can evaluate any expression in Python, and get one of two answers, True or
False.

• When you compare two values, the expression is evaluated and Python returns
the Boolean answer:

• Example
• print(10 > 9) ///True
• print(10 == 9) ?
• print(10 < 9) ?
32
If else statement
• Print a message based on whether the condition is True or False:
• a = 200
• b = 33
• if b > a:
• print("b is greater than a")
• else:
• print("b is not greater than a")
• Evaluate a string and a number:
• print(bool("Hello"))
print(bool(15))
33
Python Operators
• print(10 + 5)
• sum1 = 100 + 50 # 150 (100 + 50)
sum2 = sum1 + 250 # 400 (150 + 250)
sum3 = sum2 + sum2 # 800 (400 + 400)

34
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 35
• Example • Division always returns a float:
• x = 15
y=4 • x = 12
y=5
print(x + y)
print(x - y)
print(x * y) print(x / y)
print(x / y)
print(x % y)
print(x ** y)
print(x // y)

36
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
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
37
:= print(x := 3) x = 3 print(x)
cont.,

• numbers = [1, 2, 3, 4, 5]
count = len(numbers)
if count > 3:
print(f"List has {count}
elements")

if (count := len(numbers)) > 3:


print(f"List has {count}
elements")
38
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
39
Logical Operators
Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements x < 5 or x < 4


is true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

40
• Test if a number is greater than 0 and less than 10:
• x=5
print(x > 0 and x < 10)
test if a number is less than 5 or greater than 10:
• x=5
print(x < 5 or x > 10)
• Example
• Reverse the result with not:
• x=5
print(not(x > 3 and x < 10))

41
Identity Operators

Operator Description Example

is Returns True if both variables are the x is y


same object

is not Returns True if both variables are not the x is not y


same object

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: 42
Example
The is operator returns True if both variables point to the same object:
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z)
print(x is y)
print(x == y)
Example
The is not operator returns True if both variables do not point to the same object:
x = ["apple", "banana"]
y = ["apple", "banana"]
print(x is not y)

43
Is and ==

Difference Between is and ==


•is - Checks if both variables point to the same object in memory
•== - Checks if the values of both variables are equal

Example
x = [1, 2, 3]
y = [1, 2, 3]

print(x == y)
print(x is y)

44
Operator Precedence
Operator precedence describes the order in which operations are
performed.
Example
Parentheses has the highest precedence, meaning that expressions
inside parentheses must be evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefore
multiplications are evaluated before additions:
print(100 + 5 * 3)
45
Python Lists
• mylist = ["apple", "banana", "cherry"]
• List
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
• Example
• Create a List:
• thislist = ["apple", "banana", "cherry"]
• print(thislist)
• thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist) ///duplicate allowed.
46
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
47
print(thislist[2:5])
• Example
• Change the second item:
• thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
• Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

48
Append Items

To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
49
Remove Specified Item
• The remove() method removes the specified item.
• ExampleGet your own Python Server
• Remove "banana":
• thislist = ["apple", "banana", "cherry"]
• [Link]("banana")
• print(thislist)

50
Loop Through a List
• You can loop through the list items by using a for loop:
• Example
• Print all items in the list, one by one:
• thislist = ["apple", "banana", "cherry"]
• for x in thislist:
• print(x)

51
Sort List Alphanumerically
• List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
• ExampleGet your own Python Server
• Sort the list alphabetically:

• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


• [Link]()
• print(thislist)
• Sort the list numerically:
• thislist = [100, 50, 65, 82, 23]
[Link]()
print(thislist)

52
• Sort the list descending:
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link](reverse = True)
print(thislist)
• Sort the list descending:
• thislist = [100, 50, 65, 82, 23]
[Link](reverse = True)
print(thislist)

53
Copy a List
• You cannot copy a list simply by typing list2 = list1, because: list2 will only
be a reference to list1, and changes made in list1 will automatically also be
made in list2.
• Use the copy() method
• You can use the built-in List method copy() to copy a list.
• Example
• Make a copy of a list with the copy() method:
• thislist = ["apple", "banana", "cherry"]
• mylist = [Link]()
• print(mylist)

54
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

55
• Join two list:
• list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

56
Tuple
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities
and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Example
• Create a Tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple)

57
• Print the second item in the tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
• Print the last item of the tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
• Return the third, fourth, and fifth item:
• thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

58
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
• Convert the tuple into a list to be able to change it:
• x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

59
• Iterate through the items and print the values:
• thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
• Print all items by referring to their index number:
• thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

60
• Print all items by referring to their index number:
• thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

61
Set
• myset = {"apple", "banana", "cherry"}
• Sets are used to store multiple items in a single variable.

• Set is one of 4 built-in data types in Python used to store collections


of data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage.
• A set is a collection which is unordered, unchangeable*, and
unindexed.

62
• Create a Set:
• thisset = {"apple", "banana", "cherry"}
print(thisset)
• Example
• Duplicate values will be ignored:
• thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

63
64

You might also like