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

Programming with python

Python is a high-level, interpreted programming language known for its readability and versatility, created by Guido van Rossum in 1991. It is widely used in various fields such as web development, data science, machine learning, and automation, supported by extensive libraries and frameworks. Key features include easy learning, cross-platform compatibility, and the ability to define functions and manage data types effectively.

Uploaded by

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

Programming with python

Python is a high-level, interpreted programming language known for its readability and versatility, created by Guido van Rossum in 1991. It is widely used in various fields such as web development, data science, machine learning, and automation, supported by extensive libraries and frameworks. Key features include easy learning, cross-platform compatibility, and the ability to define functions and manage data types effectively.

Uploaded by

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

Programming with python

Python is a widely used high-level, interpreted programming language


designed for code readability. It was created by Guido van Rossum in 1991
and further developed by the Python Software Foundation. Python
emphasizes code readability and allows programmers to express concepts
in fewer lines of code.

What can we do with Python?


Python is used for:
 Web Development: Frameworks like Django, Flask.
 Data Science and Analysis: Libraries
like Pandas, NumPy, Matplotlib.
 Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
 Automation and Scripting: Automate repetitive tasks.
 Game Development: Libraries like Pygame.
 Web Scraping: Tools like BeautifulSoup, Scrapy.
 Desktop Applications: GUI frameworks like Tkinter, PyQt.
 Scientific Computing: SciPy, SymPy.
 Internet of Things (IoT): MicroPython, Raspberry Pi.
 DevOps and Cloud: Automation scripts and APIs.
 Cybersecurity: Penetration testing and ethical hacking tools.

Key Features of Python


 Easy to Learn and Use: Python’s simple and readable syntax makes it
beginner-friendly.
 Cross-Platform Compatibility: Python runs seamlessly on Windows,
macOS, and Linux.
Extensive Libraries: Includes robust libraries for tasks like web
development, data analysis, and machine learning.
 Versatile: Supports multiple programming paradigms, including object-
oriented, functional, and procedural programming.
 Open Source: Python is free to use, distribute, and modify

Python Variable
Python Variable is containers that store values. Python is not “statically typed”.
An Example of a Variable in Python is a representational name that serves as a
pointer to an object. Once an object is assigned to a variable, it can be referred
to by that name.
Rules for Python variables
 A Python variable name must start with a letter or the underscore
character.
 A Python variable name cannot start with a number.
 A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variable in Python names are case-sensitive (name, Name, and NAME
are three different variables).
Python Data Types
Data types are the classification or categorization of data items. It represents
the kind of value that tells what operations can be performed on a particular
data. Since everything is an object in Python programming, data types are
classes and variables are instances (objects) of these classes.

Example: This code assigns variable ‘x’ different values of various


data types in Python.
Python Input/Output
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, and will print it.
# Python program show input and Output
val = input("Enter your value: ")
print(val)

Python Operators
In Python programming, Operators in general are used to perform operations
on values and variables. These are standard symbols used for the purpose of
logical and arithmetic operations. In this article, we will look into different
types of Python operators.

Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.
Precedence of Arithmetic Operators
The precedence of Arithmetic Operators in Python is as follows:
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the same
precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same precedence)
6. S – Subtraction
Logical Operators
Python Logical operators perform Logical AND , Logical OR , and Logical
NOT operations. It is used to combine conditional statements.

Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.

Python If Else
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. But if we want to do
something else if the condition is false, we can use the else statement with the
if statement to execute a block of code when the if condition is false

Example 1 :

Python For Loop


Python For loop is used for sequential traversal i.e. it is used for iterating over
an iterable like String, Tuple, List, Set, or Dictionary. Here we will see a “for”
loop in conjunction with the range() function to generate a sequence of
numbers starting from 0, up to (but not including) 10, and with a step size of 2.
For each number in the sequence, the loop prints its value using the print()
function.
Example:
for i in range(0, 10, 2):
print(i)

output
0
2
4
6
8

Python While Loop


In this example, the condition for while will be True as long as the counter
variable (count) is less than 3.
Example: # Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output: Hello Geek
Hello Geek

Python Functions
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs, we can do the function calls to reuse code contained in it over and over
again.

Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values

Example
Create and print a dictionary:
thisdict = {"brand": "Ford",
"model": "Mustang",
"year": 1964}
print(thisdict)

Python Modules

A Python module is a file containing Python definitions and statements. A


module can define functions, classes, and variables. A module can also include
runnable code.
Grouping related code into a module makes the code easier to understand and
use. It also makes the code logically organized.
Example:
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

Python Functions
Python Functions is a block of statements that return the specific task. The
idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs, we can do the function calls to reuse code contained in it over and over
again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Types of Functions in Python


Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that are
available to use.
 User-defined function: We can create our own functions based on our
requirements.

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any
type of functionalities and properties to it as we require. By the following
example, we can understand how to write a function in Python. In this way we
can create Python function definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to GFG")

Calling a Function in Python


After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output: Welcome to GFG
Lambda Functions
Python Lambda Functions are anonymous functions means that the
function is without a name. As we already know the def keyword is
used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function
in Python.
In the example, we defined a lambda function(upper) to convert a
string to its upper case using upper().
s1 = 'GeeksforGeeks'
s2 = lambda func: func.upper()
print(s2(s1))

File Handling in Python


File handling refers to the process of performing operations on a file
such as creating, opening, reading, writing and closing it, through a
programming interface. It involves managing the data flow between
the program and the file system on the storage device, ensuring that
data is handled safely and efficiently.

Opening a File in Python


To open a file we can use open() function, which requires file path
and mode as arguments:
# Open the file and read its contents
with open('geeks.txt', 'r') as file:

Simple Project Of Python


Codes to make a calculator # This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

You might also like