What Is Python Introduction
What Is Python Introduction
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
It is used for:
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.
Python Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
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!")
Multiline Comments
Python does not really have a syntax for multiline comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
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:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
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
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.
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 statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example
x = "awesome"
print ( "Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print (z)
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print (x + y)
If you try to combine a string and a number, Python will give you
anerror :Example
x=5
y = "John"
print (x + y)
Syntax of Print()
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print ("Python is " + x)
myfunc()
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)
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 escape and newline characters
The backslash (\) has a very special meaning when used inside strings ‒ this is called the
escape character.
The word escape should be understood specifically ‒ it means that the series of
characters in the string escapes for the moment (a very short moment) to introduce a
special inclusion.
In other words, the backslash doesn't mean anything in itself, but is only a kind of
announcement, that the next character after the backslash has a different meaning too.
The letter n placed after the backslash comes from the word newline.
Both the backslash and the n form a special symbol named a newline character, which
urges the console to start a new output line.
Escape Characters
To insert characters that are illegal in a string, use an escape character.
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
print Examples:
What is the output of below lines?
1.
print("\"I'm\"\n\"\"learning\"\"\n\"\"\"Python\"\"\"")
2.
print()
3.
print(“\”)
print(“\\”)
Python 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:
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))
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))
Float can also be scientific numbers with an "e" to indicate the power of
10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print (type (x))
print (type (y))
print (type (z))
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 one type to another:
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))
Note: You cannot convert complex numbers into another number type.
Python Casting
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 rounding down to the previous whole number), 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
Example
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
Example
Strings:
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
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:
Example
print ("Hello" )
print ('Hello' )
Example
a = "Hello"
print (a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
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)
Example
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
Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.However, Python does
not have a character data type, a single character is simply a
string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character
has the position 0):
a = "Hello, World!"
print (a[1])
String Length
To get the length of a string, use the len( ) function.
Example
The len( ) function returns the length of a string:
a = "Hello, World!"
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:
txt = "The best things in life are free!"
print ("free" in txt)
Use it in an if statement:
Example
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
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not in .
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print ("expensive" not in txt)
Use it in an if statement:
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print ("Yes, 'expensive' is NOT present." )
Python - Slicing Strings
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 ])
Note: The first character has index 0.
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print (b[-5 :-2 ])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
The upper( ) method returns the string in upper case:
a = "Hello, World!"
print (a.upper())
Lower Case
Example
The lower( ) method returns the string in lower case:
a = "Hello, World!"
print (a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.
Example
The strip( ) method removes any whitespace from the beginning or the
end:
a = " Hello, World! "
print (a.strip()) # returns "Hello, World!"
Replace String
Example
The replace( ) method replaces a string with another string:
a = "Hello, World!"
print (a.replace("H" , "J" ))
Split String
The split( ) method returns a list where the text between the
specified separator becomes the list items.
Example
The split( ) method splits the string into substrings if it finds
instances of the separator:
a = "Hello, World!"
print (a.split("," )) # returns ['Hello', ' World!']
Python - String Concatenation
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c :
a = "Hello"
b = "World"
c = a + b
print (c)
Example
To add a space between them, add a " " :
a = "Hello"
b = "World"
c = a + " " + b
print (c)
Python - Format - Strings
String Format
As we learned in the Python Variables chapter, we cannot combine
strings and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print (txt)
But we can combine strings and numbers by using the format( )
method!
The format( ) method takes the passed arguments, formats them, and
places them in the string where the placeholders { } are:
Example
Use the format( ) method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print (txt.format (age))
The format() method takes unlimited number of arguments, and are
placed into the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print (myorder.format (quantity, itemno, price))
You can use index numbers {0 } to be sure the arguments are placed
in the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print (myorder.format (quantity, itemno, price))
name = 'Om'
age = 22
print(f"Hello, My name is {name} and I'm {age} years old.")
How to take input in Python using input() function:-
input (): This function first takes the input from the user and converts it into a
string. The type of the returned object always will be <class ‘str’>. It does not
evaluate the expression it just returns the complete statement as String. For
example, Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for
the user’s input. When the user presses enter, the program resumes and returns
what the user typed.
Syntax:
inp = input('STATEMENT')
Example:
1. >>> name = input('What is your name?\n') # \n ---> newline --->
It causes a line break
>>> What is your name?
Ram
>>> print(name)
Ram
Output:
output:-
today = date.today()
print("Today's date:", today)