4. Table of Contents:
1. Introduction of Python
2. Basic of python programming
3. Control flow statements
4. functions
5. strings
6. list ,tuples,dictionaries
7. Conclusion
5. INTERNSHIP REPORT ON PROBLEM SOLVING AND PYTHON
PROGRAMMING
1.INTRODUCTION OF PYTHON
Python is a popular high-level programming language known for its simplicity and readability. Created by Guido van
Rossum and first released in 1991, Python has gained widespread adoption and is now widely used in various domains,
including web development, data analysis, artificial intelligence, scientific computing, and more.
Python's design philosophy emphasizes code readability, encouraging developers to write clear and concise code. Its syntax
uses indentation and whitespace to define code blocks, making it more readable compared to languages that use braces or
keywords.
Python is an interpreted language, which means that programs written in Python are executed by an interpreter rather than
being compiled into machine code. This allows for rapid development and prototyping since you can write code and run it
immediately without the need for a separate compilation step.
One of the key strengths of Python is its extensive standard library, which provides a wide range of modules and functions
that can be readily used in your programs. Additionally, Python has a vast ecosystem of third-party libraries and frameworks
that further extend its capabilities, such as NumPy for numerical computing, Pandas for data analysis, Flask and Django
for web development, TensorFlow and PyTorch for machine learning, and many more.
6. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It
offers dynamic typing, which means you don't have to explicitly declare variable types. Python also includes automatic
memory management through garbage collection, relieving developers from manual memory management tasks.
To start programming in Python, you'll need to install the Python interpreter on your computer, which is available for major
operating systems. You can write Python code in a text editor or use integrated development environments (IDEs) such as
PyCharm, Visual Studio Code, or Jupyter Notebook to enhance your coding experience.
Python is beginner-friendly, making it an excellent choice for those new to programming. Its simple syntax and vast
resources for learning, such as online tutorials, documentation, and a supportive community, make it accessible for people
of all skill levels.
Overall, Python's versatility, readability, and extensive ecosystem have contributed to its popularity and made it one of the
most widely used programming languages today. Whether you're interested in web development, data analysis, machine
learning, or any other domain, Python provi
des a powerful and flexible platform to build your p
7. 2. BASCICS OF PYTHON PROGRAMMING
Python is a popular and versatile programming language known for its simplicity
and readability. It is widely used for web development, data analysis, machine
learning, and automation. Here are some basics of Python:
1. Installation: To get started, you need to install Python on your computer. Visit
the official Python website (python.org) and download the appropriate version
for your operating system. Follow the installation instructions to complete the
setup.
2. Syntax and Indentation: Python uses a clean and readable syntax. Indentation
is significant in Python, as it determines the structure of the code. Use four spaces
(or a tab) for each level of indentation.
3. Variables: Variables are used to store data in Python. You can assign a value
to a variable using the equal sign (=). Python is dynamically typed, so you don't
need to specify the variable type explicitly.
```python
# Example
name = "John"
8. age = 25
```
4. Data Types: Python has several built-in data types, including:
- Numeric types: int, float, complex
- Sequence types: list, tuple, range
- Text type: str
- Mapping type: dict
- Set types: set, frozenset
- Boolean type: bool
5. Basic Operations: Python supports common mathematical and logical
operation.In Python, operators are symbols or special characters that perform
operations on one or more operands (values or variables). Python supports
various types of operators, which can be classified into different categories based
on the type of operations they perform. Here are the commonly used operators in
Python:
1. Arithmetic Operators:
- Addition: `+`
- Subtraction: `-`
9. - Multiplication: `*`
- Division: `/`
- Floor Division: `//` (returns the quotient after dividing, discarding the
remainder)
- Modulo: `%` (returns the remainder after dividing)
- Exponentiation: `**` (raises a number to a power)
11. 3. Comparison Operators:
- Equal to: `==`
- Not equal to: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
# Comparison operator examples
# Equal to
print(5 == 5) # True
print(5 == 10) # False
# Not equal to
print(5 != 10) # True
print(5 != 5) # False
# Greater than
print(10 > 5) # True
print(5 > 10) # False
# Less than
print(5 < 10) # True
print(10 < 5) # False
12. # Greater than or equal to
print(10 >= 5) # True
print(10 >= 10) # True
print(5 >= 10) # False
# Less than or equal to
print(5 <= 10) # True
print(10 <= 10) # True
print(10 <= 5) # False
4. Logical Operators:
- Logical AND: `and`
- Logical OR: `or`
- Logical NOT: `not`
# Python program to demonstrate
# logical and operator
a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
13. print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")
5. Bitwise Operators:
- Bitwise AND: `&`
- Bitwise OR: `|`
- Bitwise XOR: `^`
- Bitwise NOT: `~`
- Left shift: `<<`
- Right shift: `>>`
6. Membership Operators:
- `in` operator: returns `True` if a value is found in a sequence
- `not in` operator: returns `True` if a value is not found in a sequence
7. Identity Operators:
- `is` operator: returns `True` if two variables refer to the same object
- `is not` operator: returns `True` if two variables do not refer to the same object
These are the basic operators in Python. Additionally, Python also supports other
specialized operators, such as the ternary operator (`a if condition else b`) and the
attribute access operator (`.`) for accessing object attributes or methods.
It's important to note that operator precedence determines the order in which operators
14. are evaluated in an expression. Parentheses can be used to enforce a specific order of
evaluation.
CONTROL FLOW STATEMENTS:
Control flow statements are used in programming languages to control the flow of
execution within a program. They determine the order in which statements are
executed based on certain conditions. Common control flow statements include:
1. Conditional Statements:
- If statement: Executes a block of code if a specified condition is true.
- If-else statement: Executes one block of code if a specified condition is true, and
another block if the condition is false.
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
- Nested if-else statement: Allows multiple conditions to be tested in a hierarcal
manner.
15. x = 5
y = 10
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
if x == y:
print("x is equal to y")
else:
print("Something went wrong!")
2. Looping Statements:
- For loop: Repeats a block of code a fixed number of times, iterating over a sequence
(such as a range of numbers).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- While loop: Repeats a block of code as long as a specified condition is true.
count = 0
while count < 5:
16. print("Count:", count)
count += 1
- Do-while loop: Similar to the while loop, but it executes the block of code at least
once before checking the condition.
3. Jump Statements:
- Break statement: Terminates the execution of a loop or a switch statement.
- Continue statement: Skips the rest of the current iteration of a loop and proceeds
to the next iteration.
- Return statement: Terminates the execution of a function and returns a value.
These control flow statements allow programmers to create more flexible and dynamic
programs by controlling the order and repetition of statements based on different
conditions.
# Break statement
for i in range(1, 10):
if i == 5:
break
print(i)
# Continue statement
for i in range(1, 10):
17. if i == 5:
continue
print(i)
FUNCTIONS:
In Python, functions are reusable blocks of code that perform specific tasks. They
allow you to organize your code into logical units, making it easier to read, write, and
maintain. Functions help you avoid code repetition and enable you to break down
complex problems into smaller, more manageable pieces.
Here's the general syntax for defining a function in Python:
```python
def function_name(parameters):
# Function body
# Code to be executed when the function is called
# Optionally, return a value
```
Let's look at an example function that calculates the factorial of a number:
```python
18. def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
```
In the above example, `factorial` is the function name, and `n` is the parameter it
accepts. The function calculates the factorial of `n` using a loop and returns the result.
To call a function, you simply write the function name followed by parentheses,
passing any required arguments inside the parentheses:
```python
result = factorial(5)
print(result) # Output: 120
```
The above code calls the `factorial` function with the argument `5` and assigns the
returned value to the `result` variable. It then prints the result, which is `120` in this
case.
19. Functions can have multiple parameters, including default values for some or all of
them. You can also return multiple values using tuples, and use the `return` statement
to exit the function prematurely.
Here's an example of a function with multiple parameters and a default value:
```python
def greet(name, greeting="Hello"):
print(greeting, name)
greet("Alice") # Output: Hello Alice
greet("Bob", "Hi there") # Output: Hi there Bob
```
In the above code, the `greet` function accepts two parameters: `name` and `greeting`.
The `greeting` parameter has a default value of `"Hello"`. When calling the function,
you can either provide a value for `greeting` or leave it blank, in which case the default
value is used.
These are just some basic concepts related to functions in Python. Functions can
become more complex and powerful, allowing you to solve a wide range of problems
efficiently.
20. 5.STRINGS:
In Python, strings are a sequence of characters enclosed in single quotes (' ') or double
quotes (" "). They are one of the fundamental data types and are commonly used for
representing text.
Here are some basic operations and features related to strings in Python:
1. Creating a string:
```python
my_string = 'Hello, World!'
```
2. Accessing characters in a string:
```python
print(my_string[0]) # Output: 'H'
print(my_string[7]) # Output: 'W'
```
3. String slicing (extracting a portion of a string):
```python
print(my_string[0:5]) # Output: 'Hello'
print(my_string[7:]) # Output: 'World!'
22. 7. String formatting (using placeholders to insert values into a string):
```python
name = 'Alice'
age = 25
print('My name is {} and I am {} years old.'. format(name, age))
# Output: 'My name is Alice and I am 25 years old.'
```
8. Escape sequences (special characters preceded by a backslash):
```python
print('This is a 'single quoted' string.') # Output: "This is a 'single quoted' string."
print("This is a "double quoted" string.") # Output: 'This is a "double quoted"
string.'
print("This is an new line.") # Output: 'This is an new line.' (with a line
break)
```
These are just a few examples of working with strings in Python.
23. LIST,TUPLE ,DICTIONARIES:
Certainly! Here's an example of a list, a tuple, and a dictionary in Python:
1. List:
A list is an ordered collection of items that can be of different data types.
```python
my_list = [1, 2, 'three', 4.5, True]
```
2. Tuple:
A tuple is an ordered, immutable collection of items.
```python
my_tuple = (10, 20, 'thirty', 40.5, False)
```
3. Dictionary:
A dictionary is an unordered collection of key-value pairs, where each key is
unique.
```python
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
```
In the above example, 'name', 'age', and 'city' are the keys, and 'John', 25, and
'New York' are their corresponding values.
24. You can access individual elements in a list, tuple, or dictionary using indexing
or keys. For example:
```python
print(my_list[0]) # Output: 1
print(my_tuple[2]) # Output: 'thirty'
print(my_dict['name']) # Output: 'John'
```
lists and tuples use square brackets and parentheses, respectively, while dictionaries
use curly braces and key-value pairs.
import random
def generatePassword(pwlength):
alphabet = "abcdefghijklmnopqrstuvwxyz"
passwords = []
for i in pwlength:
password = ""
for j in range(i):
next_letter_index = random.randrange(len(alphabet))
password = password + alphabet[next_letter_index]
password = replaceWithNumber(password)
password = replaceWithUppercaseLetter(password)
passwords.append(password)
return passwords
def replaceWithNumber(pword):
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(pword)//2)
pword = pword[0:replace_index] + str(random.randrange(10)) + pword[replace_index+1:]
return pword
def replaceWithUppercaseLetter(pword):
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(pword)//2,len(pword))
pword = pword[0:replace_index] + pword[replace_index].upper() + pword[replace_index+1:]
return pword