Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

What Is Python Introduction

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

What Is Python Introduction

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

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

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.

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

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:

 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.
Example
Legal variable names:

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"

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"

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

print(*objects, sep=' ', end='\n', file=None, flush=False)

Print objects to the text stream file, separated by sep and


followed by end. sep, end, file, and flush, if present, must be
given as keyword arguments.
All non-keyword arguments are converted to strings
like str() does and written to the stream, separated by sep and
followed by end. Both sep and end must be strings; they can also
be None, which means to use the default values. If no objects are
given, print() will just write end.
The file argument must be an object with a write(string) method;
if it is not present or None, sys.stdout will be used. Since printed
arguments are converted to text strings, print() cannot be used
with binary mode file objects. For these,
use file.write(...) instead.
Python - Global Variables
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()
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.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded


by double quotes:

txt = "We are the so-called "Vikings" from the north."


Print(txt)
txt = "We are the so-called \"Vikings\" from the north."
Escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value


Escape Example
Function Result
character Code

\n The new line character helps the txt = HI


programmer to insert a new line before or “HI\n99!”
99
after a string. print(txt)

\\ This escape sequence allows the txt = HI\99!


programmer to insert a backslash into the “HI\\99!”
Python output. print(txt)

\xhh Use a backslash followed by a hexadecimal txt = HI99!


number. “\x48\x49”
This is done by printing in backslash with +"99!"
the hexadecimal equivalent in double
print(txt)
quotes.

\ooo To get the integer value of an octal value, txt = HI99!


provide a backslash followed by ooo or ‘\110\111’+
octal number in double-quotes. “99!”
It is done by printing in a backslash with print(txt)
three octal equivalents in double quotes.

\b This escape sequence provides backspace txt = HI 99!


to the Python string. It is inserted by “HI\b99!”
adding a backslash followed by “b”. print(txt)
“b” here represents backslash.

\f It helps in the interpolation of literal txt = HI99!


strings “HI\f99!”
print(txt)
Escape Example
Function Result
character Code

\r It helps you to create a raw string txt = HI


“HI\r99!”
99!
print(txt)

\’ It helps you to add a single quotation to txt = HI’99!


string “HI\’99!”
print(txt)

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:

Getting the Data Type


You can get the data type of any object by using the type( )
function:
Example
Print the data type of the variable x:
x = 5
print (type (x))
Setting the Data Type
In Python, the data type is set when you assign a value to a
variable:
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
To verify the type of any object in Python, use the type( )
function:
Example
print (type (x))
print (type (y))
print (type (z))

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

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:

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)

Or three single quotes:

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

Looping Through a String


Since strings are arrays, we can loop through the characters in a
string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana" :
print (x)

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

Learn more about If statements in our Python If...Else chapter.

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.

Slice From the Start


By leaving out the start index, the range will start at the first
character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print (b[:5])

Slice To the End


By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print (b[2 :])
Negative Indexing
Use negative indexes to start the slice from the end of the string:

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

Print Variables using f-string in Python


In the below example, we have used the f-string inside a print() method
to print a string. We use curly braces to use a variable value inside
f-strings, so we define a variable ‘val’ with ‘Geeks’ and use this inside
as seen in the code below ‘val’ with ‘Geeks’. Similarly, we use
the ‘name’ and the variable inside a second print statement.
# Python program introducing f-string
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")

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

# ---> comment in python

# Python program showing a use of input()

val = input("Enter your value: ")


print(val)

Output:

Enter your value: 123


123

Taking String as an input:


name = input('What is your name?\n')
# \n ---> newline ---> It causes a line break
print(name)
Output:
What is your name?
Ram
Ram
How the input function works in Python :
 When input() function executes program flow will be stopped until the user has
given input.
 The text or message displayed on the output screen to ask a user to enter an
input value is optional i.e. the prompt, which will be printed on the screen is
optional.
 Whatever you enter as input, the input function converts it into a string. if you
enter an integer value still input() function converts it into a string. You need to
explicitly convert it into an integer in your code using typecasting .

 # Program to check input type in Python

 num = input ("Enter number :")
 print(num)
 name1 = input("Enter name : ")
 print(name1)

 # Printing type of input value
 print ("type of number", type(num))
 print ("type of name", type(name1))

output:-

Note:input() function takes all the input as a string only


There are various function that are used to take as desired input few of them are :
 int(input())
 float(input())
 num = int(input("Enter a number: "))
 print(num, " ", type(num))


 floatNum = float(input("Enter a decimal number: "))
 print(floatNum, " ", type(floatNum))
How to input time in Python?
You can use the input() function to accept a string input representing time. You
can then parse and manipulate this string using datetime functions if needed.
import datetime

# Input time as string


time_str = input("Enter a time (HH:MM:SS): ")
# Convert string to datetime object
time_obj = datetime.datetime.strptime(time_str, "%H:%M:%S")

from datetime import date

today = date.today()
print("Today's date:", today)

You might also like