0% found this document useful (0 votes)
1 views34 pages

Python

Python is a versatile programming language used for web applications, data handling, and software development across various platforms. It features a simple syntax, supports multiple programming paradigms, and allows for rapid prototyping. Key concepts include variable creation, data types, string manipulation, and the importance of indentation in code structure.

Uploaded by

f7rpdvv9cf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views34 pages

Python

Python is a versatile programming language used for web applications, data handling, and software development across various platforms. It features a simple syntax, supports multiple programming paradigms, and allows for rapid prototyping. Key concepts include variable creation, data types, string manipulation, and the importance of indentation in code structure.

Uploaded by

f7rpdvv9cf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

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

To check the Python version of the editor, we can find it by importing the sys module:

import sys
print(sys.version)
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.

if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:


if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

We have to use the same number of spaces in the same block of code, otherwise Python will give us an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables: In Python, variables are created when we assign a value to it:

x=5
y = "Hello, World!"

print(x)
print(y)

Python has no command for declaring a variable.

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

• 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.
• Comments can be placed at the end of a line, and Python will ignore the rest of the line:
• A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code.
• Python does not really have a syntax for multiline comments. To add a multiline comment we could insert a # for each line:
Variables :Variables are containers for storing data values.
Creating Variables: Python has no command for declaring a variable.

 A variable is created the moment you first assign a value to it.


x=5
y = "Joy”
print(x)
print(y)

 Variables do not need to be declared with any particular type, and can even change type after they have been
set.
x=4 # x is of type int
x = "Sachin“ # x is now of type str

 Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)
Get the Type:

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

x=5
y = "Johnny"
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)
#double quotes are the same as single quotes:
x = 'John'
print(x)

Case-Sensitive:Variable names are case-sensitive.


a=4
A = "Sally"

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


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

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"
Many Values to Multiple Variables: Python allows us to assign values to multiple variables in one line:

x, y, z = "Anil", "Ajay", "Akshay"


a,b,c=100,200,-999

print(x)
print(y)
print(z)
print(a)
print(b)
print(c)

One Value to Multiple Variables: We can assign the same value to multiple variables in one line:

x = y = z = "Sachin Tendulkar"
print(x)
print(y)
print(z)
Output Variables:

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

x="Hello kolkata"
print(x)
Hello kolkata
x=123456789987456321
print(x)
123456789987456321
x=99.9999999999998
print(x)
99.9999999999998
x=x**x
print(x)
9.999999999988848e+199
x=3
x**x
27
x=x**x
print(x)
27
x**2
729
 In the print() function, we output multiple variables, separated by a comma:
a="Python"
b="is"
c="very"
d="easy"
print(a,b,c,d)
Python is very easy

 We can also use the + operator to output multiple variables:


print(a + b+ c +d)
Pythonisveryeasy

 For numbers, the + character works as a mathematical operator.


 In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error:
x="kaushik"
a=13
a+a
26
x+a
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
x+a
TypeError: can only concatenate str (not "int") to str
x+x
'kaushikkaushik‘

The best way to output multiple variables in the print() function is to separate them with commas, which even support different data
types:
print(x,a)
kaushik 13
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 = "easy"
def myfunc():
print("Python is " + x)

myfunc()

 If we 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.

x = "easy"
def f1():
x = "simple"
print("Python is " + x)

f1()
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
x = "legend"

myfunc()
print("Sachin is a " + x)
Python Data Types
Getting the Data Type: We can get the data type of any object by using the type() function:
x=5
y=5.55
z="sachin"
a=3j
b=True
print(type(x), type(y),type(z), type(a),type(b)) # <class 'int'> <class 'float'> <class 'str'> <class 'complex'> <class 'bool'>

Setting the Specific Data Type:

If we want to specify the data type, we can use the


following constructor functions:
Python Numbers: There are three numeric types in Python:

i. int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
ii. float Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
iii. complex Complex numbers are written with a "j" as the imaginary part.

x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z)) x = 1.10 x = 35e3
y = 1.0 y = 12E4
z = -35.59 z = -87.7e100

print(type(x)) print(type(x))
print(type(y)) print(type(y))
print(type(z)) print(type(z))

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Type Conversion: We can convert from one type to another with the int(), float(), and complex() methods:

#convert from int to float:


x = float(1)

#convert from float to int:


y = int(2.8)

#convert from int to complex:


z = complex(1)

print(x)
print(y)
print(z)

print(type(x))
print(type(y))
print(type(z))
Note: We cannot convert complex numbers into another number type.

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

import random
print(random.randrange(1, 100))
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 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

x = float(1)
x = str("s1")
y = float(2.8)
y = str(2)
z = float("3")
z = str(3.0)
w = float("4.2")
print(x) s1
print(x) 1.0
print(y) 2
print(y) 2.8
print(z) 3.0
print(z) 3.0
print(y+z) 23.0
print(w+x+y+z) 11.0
Python Strings
• Strings in python are surrounded by either single quotation marks, or double quotation marks.
• ‘kolkata' is the same as “kolkata".
• We can display a string literal with the print() function:
print("It's alright") It's alright
print("He is called 'Johnny'") He is called 'Johnny'
print('He is called "Johnny"') He is called "Johnny"

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

a = "Hello, World!"
print(a[8])

 Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "kolkata":
print(x)

 To get the length of a string, use the len() function.


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.

txt = "Python is very easy"


print("on" in txt) # True

Use it in an if statement:

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.

txt = "The best things in life are free!"


print("expensive" not in txt)

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
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.

a = "Python is very easy"


print(a[3]) # remember that the first character has the position 0
print(len(a)) # The len() function returns the length of a string.

Looping Through a String: Since strings are arrays, we can loop through the characters in a string, with a for
loop.

for x in "I love my India": I


print(x)
l
o
v
e

m
y

I
n
d
i
a
Slicing: We 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.
Get the characters from position 3 to position 10 (not included):

b = "Python is very easy"


print(b[3:10]) # hon is

Slice From the Start: By leaving out the start index, the range will start at the first character.
b = "PYTHON IS EASY"
print(b[:5]) # PYTHO

Slice To the End: By leaving out the end index, the range will go to the end.
b = "PYTHON IS EASY"
print(b[:5])
print(b[2:])

Negative Indexing :Use negative indexes to start the slice from the end of the string:

b = "sachin tendulkar"
print(b[-5:-1])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.

• The upper() method returns the string in upper case.


• The lower() method returns the string in lower case.
a = "Python Is Easy.."
print(a.upper())
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.
a=" Python is very easy "
print(a.strip())

• Replace String: The replace() method replaces a string with another string
a = "Python is tough"
print(a.replace("tough", "very easy"))

• Split String :The split() method returns a list where the text between the specified separator becomes the list
items.

a = "PYTHON is easy"
b = a.split(" ")
print(b) # ['PYTHON', 'is', 'easy']
String Concatenation: To concatenate, or combine, two strings you can use the + operator.
a = "kaushik"
b = "goswami"
c= " "
c=a+c+b
print(c)

Python - Format – Strings: We cannot combine strings and numbers like this:
age = 36
txt = "My name is Virat, I am " + age
print(txt)
Traceback (most recent call last):
File "C:/Python/Python313/prime2.py", line 33, in <module>
txt = "My name is Virat, I am " + age
TypeError: can only concatenate str (not "int") to str

But we can combine strings and numbers by using f-strings or the format() method!

F-Strings: F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as
placeholders for variables and other operations.
age = 32 price = 100
txt = f"My name is Shubhman, I am {age}" txt = f"The price is {price} Rupees"
print(txt) print(txt)
Placeholders and Modifiers:

• A placeholder can contain variables, operations, functions, and modifiers to format the value.
• A placeholder can include a modifier to format the value.
• A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed
point number with 2 decimals:
price = 103.3037
txt = f"The price is {price:.3f} Rupees" // The price is 103.304 Rupees
print(txt)

• A placeholder can contain Python code, like math operations:


Perform a math operation in the placeholder, and return the result.
txt = f"The price is {20 * 103.375:.1f} Rupees"
print(txt) // The price is 2067.5 Rupees

Escape Character: 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)
Python Booleans: Booleans represent one of two values: True or False.

• Boolean Values: In programming you often need to know if an expression is True or False.
• We can evaluate any expression in Python, and get one of two answers, True or False.
• When we compare two values, the expression is evaluated and Python returns the Boolean answer:

print(10 > 9) True


print(10 == 9) False
print(10 < 9) False
print(10 == 10) True

• Print a message based on whether the condition is True or False:

a = 200
b = 300
if a < b:
print("b is greater than a")
else:
print("a is greater than b")
Evaluate Values and Variables: The bool() function allows you to evaluate any value, and give you True or False
in return,
print(bool("Hello")) True
print(bool(15)) True
print(bool(-1)) True
print(bool(0)) False

x = "Hello"
y = 15
z=0
print(bool(x)) True
print(bool(y)) True
print(bool(z)) False

Most Values are True: Almost any value is evaluated to True if it has some sort of content.

• Any string is True, except empty strings.


• Any number is True, except 0.
• Any list, tuple, set, and dictionary are True, except empty ones.
Some Values are False:

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0,
and the value None. And of course the value False evaluates to False.

print(bool(False)) False
print(bool(None)) False
print(bool(0)) False
print(bool("")) False
print(bool(())) False
print(bool([])) False
print(bool({})) False

Functions can Return a Boolean: We can create functions that returns a Boolean Value:

def Func1() : def Func1() :


return 1 return False
if Func1(): if Func1():
print("YES!") print("YES!")
else: else:
print("NO!") print("NO!")
Python Conditions and If statements:

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

a = 33
b = 200

if b > a:
print("b is greater than a")
Indentation: Python relies on indentation (whitespace at the beginning of a line) to define scope in
the code. Other programming languages often use curly-brackets for this purpose.

a = 33
b = 200

if b > a:
print("b is greater than a")
Elif: The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else: The else keyword catches anything which isn't caught by the preceding conditions.

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".

We can also have an else without the elif:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If :If you have only one statement to execute, you can put it on the same line as the if
statement.

if a > b: print("a is greater than b")

Short Hand If ... Else :If we have only one statement to execute, one for if, and one for else, we can
put it all on the same line:
a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.


We can also have multiple else statements on the same line:
Example: One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And: The and keyword is a logical operator, and is used to combine conditional statements:
Example: Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or: The or keyword is a logical operator, and is used to combine conditional statements:
Example: Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not: The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example:Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

Nested If: We can have if statements inside if statements, this is called nested if statements.

x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
if x > 30:
print("and also above 30!!")
else:
print("but not above 20.")
Python Loops: Python has two primitive loop commands:

I. while loops
II. for loops

The while Loop: With the while loop we can execute a set of statements as long as a condition is true.
Note: remember to increment i, or else the loop will continue forever.
i=1
while i < 10:
The while loop requires relevant variables to be ready, in this example we need to define
print(i)
an indexing variable, i, which we set to 1.
i += 1

The break Statement: With the break statement we can stop the loop even if the while condition is
true:

Example: Exit the loop when i is 5:

i=1
while i < 10:
print(i)
if i == 5:
break
i += 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy