0% found this document useful (0 votes)
18 views14 pages

MNPython

Uploaded by

sujji276
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
18 views14 pages

MNPython

Uploaded by

sujji276
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

Python

What is python?
Python is a high-level, interpreted, and general-purpose dynamic
programming language known for its readability and versatility. It was
created in 1989 by Guido Van Rossum and has become one of the
most popular languages globally.

Syntax: the set of rules that define how a Python program should be
written and interpreted.

Variables:
Variables in Python are containers that store data values. Here are
the key points about variables in Python:

1. Definition: Variables are fundamental entities in Python that hold


data values. They provide a way to store and manipulate data
throughout a program[1][2][3][4].

2. Assigning Values: Variables are created when a value is assigned to


them using the assignment operator (=). Python allows assigning
values of different data types to variables[1][2][3][4].

3. Data Types: Python variables can hold various data types,


including:
- Numeric Types: int (integers), float (floating-point numbers),
complex (complex numbers)[1][2][3]
- Sequence Types: str (strings), list, tuple, range[1][2][4]
- Mapping Type: dict (dictionaries)[1][2][4]
- Set Types: set, frozenset[1][2]
- Boolean Type: bool[1][2][3]
- Binary Types: bytes, bytearray, memoryview[1][2]
- None Type: NoneType[2]

4. Naming Conventions:
- Variable names must start with a letter or an underscore (_)[1][2]
[4].
- Variable names can only contain letters, digits, and underscores[1]
[2][4].
- Variable names are case-sensitive[1][2][4].
- It is recommended to use lowercase letters and underscores to
separate words (snake_case)[2][4].

5. Printing Variables: You can display the value of a variable using the
print() function[5].

6. Deleting Variables: The del statement is used to delete a


variable[5].

7. Multiple Assignment: Python allows assigning multiple variables in


a single statement with the same or different values[5].
Data types:
Python has several built-in data types that are used to define the
type of a variable. The main data types in Python are:
*Numeric Types: int, float, complex
-int represents integers (whole numbers)
-float represents floating-point numbers (numbers with decimal
points)
-complex represents complex numbers
*Sequence Types: str, list, tuple, range
-str represents strings (sequences of characters)
-list represents mutable ordered sequences of values
-tuple represents immutable ordered sequences of values
-range represents a sequence of numbers
*Mapping Type: dict
-dict represents unordered key-value pairs
*Set Types: set, frozenset
-set represents unordered collections of unique elements
-frozenset represents immutable versions of sets
*Boolean Type: bool
-bool represents logical values True or False
*Binary Types: bytes, bytearray, memoryview
-bytes represents immutable sequences of 8-bit bytes
-bytearray represents mutable sequences of 8-bit bytes
-memoryview provides a way to access the internal data of an object
that supports the buffer protocol
*None Type: NoneType
None represents the absence of a value

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.

Good to know
 The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
 In this tutorial Python will be written in a text editor. 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 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!")

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.

Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:


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

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, 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!")

Variables
Variables are containers for storing data values.

Example:
x = 5
y = "John"
print(x)
print(y)

Casting
If you want to specify the data type of a variable, this can be done with
casting.

Example: x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

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.

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)

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)

In the print() function, you output multiple variables, separated by a


comma:

Example: x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:

print(x + y + z)

Global Variables
Variables that are created outside of a function (as in all of the examples
above) 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()

Pthon 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.

Python has the following data types built-in by default, in these categories:

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


None Type: NoneType

You can get the data type of any object by using the type() function:

x = 5
print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

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

x = None NoneType

ADVERTISEMENT

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor
functions:

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

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

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

Example: convert from one type to another type

x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)
print(a)
print(b)
print(c)

print(type(a))
print(type(b))
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))

Specify a Variable Type


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

integers: x = int(1) # x will be 1


y = int(2.8) # y will be 2
z = int("3") # z will be 3

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'

Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

You might also like