0% found this document useful (0 votes)
4 views

python basic Example

This document provides a comprehensive overview of basic Python programming concepts, including syntax, variables, data types, and string manipulation. It covers topics such as indentation, variable naming conventions, casting, and the use of comments. Additionally, it explains how to work with strings, including slicing and checking for substrings.

Uploaded by

cccppp00006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python basic Example

This document provides a comprehensive overview of basic Python programming concepts, including syntax, variables, data types, and string manipulation. It covers topics such as indentation, variable naming conventions, casting, and the use of comments. Additionally, it explains how to work with strings, including slicing and checking for substrings.

Uploaded by

cccppp00006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

PYTHON

BASIC PRACTIES
)

1.#!/bin/python3 Hello, World


print("Hello, World!")

2.Python Version
import sys 3.8.2 (default, Mar 13 2020,
10:14:16)
print(sys.version [GCC 9.3.0]

3 Python Indentation
. Python Indentation Python uses
indentation to indicate a block of
code.

a,.Five is greater than two!


a. if 5 > 2:
print("Five is greater than two!") b. File "demo_indentation_test.py", line 2
print("Five is greater than two!")
b. if 5 > 2: ^
print("Five is greater than two!") IndentationError: expected an indented block
c. if 5 > 2:
print("Five is greater than two!") c.Five is greater than two!
Five is greater than two!
if 5 > 2:
print("Five is greater than two!")
d. File "demo_indentation2_error.py", line 3
d. if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
^
print("Five is greater than two!")
IndentationError: unexpected indent

Python Variables
In Python, variables are created when you
assign a value to it:

x=5
5
y = "Hello, World!"
Hello, World!
print(x)
print(y)
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
#This is a comment.
print("Hello, World!") Hello, World!

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

#print("Hello, World!")
print("Cheers, Mate!") Cheers, Mate

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

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a
value to it. 5
x=5 John
y = "John"
print(x)
print(y)

x=4 Sally
x = "Sally"
print(x)
Casting
If you want to specify the data type of a variable,
this can be done with casting.
3
x = str(3) # x will be '3' 3
y = int(3) # y will be 3 3.0
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable
with the type() function.

x=5 <class 'int'>


y = "John" <class 'str'>
print(type(x))
print(type(y))
Single or Double Quotes
String variables can be declared either by using
single or double quotes:
x = "John"
print(x) John
#double quotes are the same as single quotes: John
x = 'John'
print(x)

Case-Sensitive
Variable names are case-sensitive.
This will create two variables:
4
a=4 Sally
A = "Sally"
#A will not overwrite a
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:
1.A variable name must start with a letter or the underscore character
2.A variable name cannot start with a number
3.A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
4.Variable names are case-sensitive (age, Age and AGE are three different
variables)
5.A variable name cannot be any of the Python keywords.
myvar = "John" John
my_var = "John" John
_my_var = "John" John
myVar = "John" John
MYVAR = "John" John
myvar2 = "John" John
Illegal variable names:
my var = "John"2myvar = "John
2myvar = "John"
" ^ SyntaxError: invalid syntax
my-var = "John"
my var = "John"
Snake Case
Each word is separated by an underscore
character:
my_variable_name = "John"

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

Camel Case
Each word, except the first, starts
with a capital letter:
myVariableName = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one
line:
x, y, z = "Orange", "Banana", "Cherry" Orange
print(x) Banana
print(y) Cherry
print(z)

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:

x = y = z = "Orange" Orange
print(x) Orange
print(y) Orange
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.

Unpack a list:

fruits = ["apple", "banana", "cherry"] apple


x, y, z = fruits banana
print(x) cherry
print(y)
print(z)

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

x = "Python is awesome"
print(x) Python is awesom
In the print() function, you output
multiple variables, separated by a
comma:

x = "Python"
y = "is"
z = "awesome" Python is awesome
print(x, y, z)

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

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python is awesome
For numbers, the + character works as a mathematical operator:
Example
x = 5
y = 10 15
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:

x = 5 TypeError: unsupported operand type(s) for +:


y = "John" 'int' and 'str'
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:

x = 5
y = "John" 5 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"
Python is awesome
def myfunc():
print("Python is " + x)

myfunc()
x = "awesome"

def myfunc(): Python is fantastic


x = "fantastic" Python is awesome
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.

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

myfunc()

print("Python is " + x)

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"
Python is fantastic
myfunc()

print("Python is " + x)
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:

ext Type: str


Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set, frozenset
Boolean Type: bool

Binary Types: bytes, bytearray, memoryview


None Type: NoneType
Getting the Data Type
You can get the data type of any object by using the type() function:

x=5
<class 'int'>
print(type(x))
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
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor
functions:
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 Casting
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

STRING :
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

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

a = "Hello"
print(a)
Multiline Strings
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)
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! “ e
print(a[1])

Looping Through a String


for x in "banana":
print(x)

String Length
a = "Hello, World!“ 13
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
1.txt = "The best things in life are free!"
print("free" in txt)

2.Print only if "free" is present:


txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Check if NOT
1.txt = "The best things in life are free!"
print("expensive" not in txt)
2.print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Slicing
b = "Hello, World!"
print(b[2:5])

Slice From the Start


#Get the characters from the start to
position 5 (not included):

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

Slice To the End


#Get the characters from position 2, and all the
way to the end:

b = "Hello, World!"
print(b[2:])
Negative Indexing
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -
2):

b = "Hello, World!“ ORL


print(b[-5:-2])

You might also like