python basic Example
python basic Example
BASIC PRACTIES
)
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.
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!")
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
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)
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:
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)
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
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.
x = "awesome"
Python is awesome
def myfunc():
print("Python is " + x)
myfunc()
x = "awesome"
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)
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:
x=5
<class 'int'>
print(type(x))
Example Data Type
x = range(6) range
x = {"name" : "John", "age" : 36} dict
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 = range(6) range
x = dict(name="John", age=36) dict
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 = "Hello, World! “ e
print(a[1])
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)
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])
b = "Hello, World!"
print(b[:5])
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):