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

Chapter 1

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)
16 views45 pages

Chapter 1

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 Intro

Chapter 1
What is Python?

• Python is a high-level, general-purpose, and very popular programming language.


Python programming language (latest Python 3) is being used in web development,
and Machine Learning applications, along with all cutting-edge technology in
Software Industry. Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.

• There are two ways you can execute your Python program:

1. First, we write a program in a file and run it one time.

2. Second, run a code line by line.


What can Python do?
1. Python can be used on a server to create web
applications.
2. Python can be used alongside software to create
workflows.
3. Python can connect to database systems. It can also
read and modify files.
4. Python can be used to handle big data and perform
complex mathematics.
5. 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, or an object-oriented way or a functional way.

• It is possible to write Python in an Integrated Development Environment, such as Thonny,


Pycharm, Netbeans or Eclipse which are particularly useful when managing larger
collections of Python files.
Python with Different Applications:
• Python is a versatile and widely-used programming language with a vast ecosystem. Here
are some areas where Python is commonly used:

1. Web Development: Python is used to build web applications using frameworks like
Django, Flask, and Pyramid. These frameworks provide tools and libraries for handling
web requests, managing databases, and more.

2. Data Science and Machine Learning: Python is popular in data science and machine
learning due to libraries like NumPy, pandas, Matplotlib, and scikit-learn. These
libraries provide tools for data manipulation, analysis, visualization, and machine
learning algorithms.

3. Artificial Intelligence and Natural Language Processing: Python is widely used in AI


and NLP applications. Libraries like TensorFlow, Keras, PyTorch, and NLTK provide
tools for building and training neural networks, processing natural language, and more.
4. Game Development: Python can be used for game development using libraries like
Pygame and Panda3D. These libraries provide tools for creating 2D and 3D games,
handling graphics, and more.

5. Desktop Applications: Python can be used to build desktop applications using libraries
like Tkinter, PyQt, and wxPython. These libraries provide tools for creating graphical user
interfaces (GUIs), handling user input, and more.

6. Scripting and Automation: Python is commonly used for scripting and automation tasks
due to its simplicity and readability. It can be used to automate repetitive tasks, manage
files and directories, and more.
7. Web Scraping and Crawling: Python is widely used for web scraping and crawling using libraries like Beautiful Soup
and Scrapy. These libraries provide tools for extracting data from websites, parsing HTML and XML, and more.

8. Education and Research: Python is commonly used in education and research due to its simplicity and readability.
Many universities and research institutions use Python for teaching programming and conducting research in various
fields.

9. Community and Ecosystem: Python has a large and active community, which contributes to its ecosystem. There are
many third-party libraries and frameworks available for various purposes, making Python a versatile language for
many applications.

10. Cross-Platform: Python is a cross-platform language, which means that Python code can run on different operating
systems without modification. This makes it easy to develop and deploy Python applications on different platforms.
Python
• Python syntax can be executed by writing directly in the
Command Line
• print("Hello, World!")
• x = "Python"
• y = "is"
• z = "awesome"
• print(x, y, z)

• Or by creating a python file on the server, using the .py file


extension, and running it in the Command Line:

• C:\Users\Your Name>python myfile.py


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!")

• Python will give you an error if you skip the indentation:

Example:

if 5 > 2:

print("Five is greater than two!")


Python Indentation

• 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!")
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.

• Python will ignore anything starts with #


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

• Comments can be placed at the end of a line, and Python will ignore the rest of the line:

• Example

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

• A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:

• Example

#print("Hello, World!")
print("Cheers, Mate!")
Python Comments
• Multiline Comments

• You can add a multiline string (triple quotes) in


your code, and place your comment inside it:

• Example

• """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
• Variables are containers for storing data values.
• 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)
Python • Variables do not need to be • Casting

declared with any particular • If you want to specify the data


Variables type of a variable, this can be
type and can even change type done with casting.
after they have been set.
• Example:
• Example: x = str(3) # x will be '3'
x = 4 # x is of type int
y = int(3) # y will be 3
z = float(3) # z will be
x = "Sally" # x is now of type 3.0
str print(x)
print(x) print(y)
print(z)
Python Variables
• Get the Type
• You can get the data type of a variable with the type()
function.

• Example
x=5
y = "John"
print(type(x))
print(type(y))
Python Variables

• Single or Double Quotes?


• String variables can be declared either by using single or
double quotes:

• Example
x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)
Python Variables

• Case-Sensitive
• Variable names are case-sensitive.

• Example
• This will create two variables:

a=4
A = "Sally"
#A will not overwrite a
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). 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.


Python - Variable Names

• Example
• Legal variable names:
• myvar = "John" • print(myvar)
• my_var = "John" • print(my_var)
• _my_var = "John" • print(_my_var)
• myVar = "John" • print(myVar)
• MYVAR = "John" • print(MYVAR)
• myvar2 = "John" • print(myvar2)
Python - Variable Names

• Example

• illegal variable names:

2myvar = "John"
my-var = "John"
my var = "John”

• #This example will produce an error in the result


Python - Variable Names

• Multi Words Variable Names

• Variable names with more than one word can be difficult to read.

• There are several techniques you can use to make them more readable:

• Camel Case
• Each word, except the first, starts with a capital letter:

• myVariableName = "John"
Python - Variable Names

• 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

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

• Note: Make sure the number of variables matches the number of values, or else
you will get an error.
One Value to Multiple Variables

• And you can assign the same value to multiple


variables in one line:

• Example
x = y = z = "Orange"
print(x)

print(y)

print(z)
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)
Python - Output Variables

• Output Variables

• The Python print() function is often used to output variables.

• Example:
x = "Python is awesome"

print(x)
Python - Output Variables

• You can also use the + operator to output multiple variables:

• Example:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Output: Python is awesome

• Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
• For numbers, the + character works as a mathematical
operator:

• Example:

x=5
y = 10
Python - Output print(x + y)

Variables • 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)
• The best way to output multiple variables in
the print() function is to separate them with
commas, which even support different data types:

Python - Output
Example:
Variables
x=5

y = "John"

print(x, y)
Python - 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.

• Function: is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain
actions, and they are important for reusing code: Define the code once and use it many times.

• Example:
• Create a variable outside of a function and use it inside the function.

x = "awesome”

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

myfunc()
Python - Global Variables
• 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.

• Example 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)
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)
The global Keyword
• Also, use the global keyword if you want to change a global variable
inside a function.

• Example:

• To change the value of a global variable inside a function, refer to the


variable by using the global keyword:

x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python Data Types
Data Types

• Built-in Data Types

• In programming, data type is an important concept.

• Variables can store data of different types, and different types can do different things.

• As shown in the following figure, Python has different data types.


Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float

Setting the Data x = 1j complex


x = ["apple", "banana", "cherry"] list
Type 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
In Python, the data type is set x = True bool
when you assign a value to a
variable. x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
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:
• Example

x = 1 # int
y = 2.8 # float
z = 1j # complex
Data Type: Int
• Int, or integer, is a whole number, positive or
negative, without decimals, of unlimited length.

• Example Integers:

x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Data Type: Float

• Float, or "floating point number" is a number,


positive or negative, containing one or more
decimals.
• Example Floats:

x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Data Type: Complex

• Complex numbers are written with a "j" as


the imaginary part:

• Example Complex:

x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion

• You can convert from one type to another with the int(), float(), and complex() methods:

Example #convert from int to


Convert from one type to another: complex:
c = complex(x)
x = 1 # int
y = 2.8 # float print(a)
z = 1j # complex print(b)
print(c)
#convert from int to float:
a = float(x) print(type(a))
#convert from float to int: print(type(b))
b = int(y) print(type(c))
Random Number
• Python does not have a random()
function to make a random number, but
Python has a built-in module called
random that can be used to make random
numbers:
• Example:
• Import the random module, and display a
random number between 1 and 9:

import random
print(random.randrange(1, 10))
End of Chapter 1

You might also like