Python Installation
sudo apt-get update
sudo apt-get install python3.6
Check the version
python3 --version
Why their is need for Python in DevOps? If we have yaml for scripting?
Python's versatility, extensive libraries, and ease of use make it a preferred choice in DevOps.
Python's automation and scripting capabilities streamline DevOps tasks.
Python's data analysis libraries facilitate insights into system performance and resource utilization.
Python integrates seamlessly with popular DevOps tools and frameworks.
Python's versatility extends to custom tools, web applications, and large-scale deployments.
Python's code readability enhances collaboration and maintainability.
Data Type In Python
Python supports several built-in data types. Here's a list of some commonly used data types in Python:
Numeric Types:
int
: Integer type (e.g., 42)float
: Floating-point type (e.g., 3.14)complex
: Complex number type (e.g., 1 + 2j)
Sequence Types:
str
: String type (e.g., "Hello, World!")list
: List type (e.g., [1, 2, 3])tuple
: Tuple type (e.g., (1, 2, 3))range
: Represents a range of values
Text Type:
str
: String type for handling textual data
Set Types:
set
: Unordered collection of unique elementsfrozenset
: Immutable version of a set
Mapping Type:
dict
: Dictionary type (e.g., {'key': 'value'})
Boolean Type:
bool
: Boolean type representing True or False
None Type:
None
: Represents the absence of a value or a null value
Binary Types:
bytes
: Immutable sequence of bytesbytearray
: Mutable sequence of bytesmemoryview
: A view object that exposes an array's buffer interface
code:-
# Integer
integer_var = 42
print("Integer Variable:", integer_var)
# Float
float_var = 3.14
print("Float Variable:", float_var)
# String
string_var = "Hello, World!"
print("String Variable:", string_var)
# List
list_var = [1, 2, 3, 4, 5]
print("List Variable:", list_var)
# Tuple
tuple_var = (10, 20, 30, 40, 50)
print("Tuple Variable:", tuple_var)
# Dictionary
dict_var = {'a': 1, 'b': 2, 'c': 3}
print("Dictionary Variable:", dict_var)
# Set
set_var = {1, 2, 3, 4, 5}
print("Set Variable:", set_var)
# Basic tasks
# Integer and Float operations
result = integer_var + float_var
print("Integer + Float:", result)
# String concatenation
new_string = string_var + " Have a nice day!"
print("Concatenated String:", new_string)
# List manipulation
list_var.append(6)
list_var.remove(2)
print("Modified List:", list_var)
# Dictionary operations
dict_var['d'] = 4
del dict_var['a']
print("Modified Dictionary:", dict_var)
# Set operations
set_var.add(6)
set_var.remove(3)
print("Modified Set:", set_var)
Here '#' is used for commenting the line.
For more example Visit this github repo:- https://github.com/sidharthhhh/python
User Inputs, Control Statements, Loops
User Inputs
To take user inputs in Python, you can use the input()
function. By default, input()
returns a string, so you'll need to convert it to the desired data type (int, float, or string) using int()
, float()
, or leave it as is.
# Taking an integer input
user_input_int = int(input("Enter an integer: "))
# Taking a floating-point input
user_input_float = float(input("Enter a float: "))
# Taking a string input
user_input_string = input("Enter a string: ")
# Printing the inputs
print(f"You entered an integer: {user_input_int}")
print(f"You entered a float: {user_input_float}")
print(f"You entered a string: {user_input_string}")
Control statement
Certainly! Here are examples of if
, else
, elif
, and nested if
statements in Python
if
statement:
# Example 1: Checking if a number is positive
num = 10
if num > 0:
print("The number is positive.")
elif
statement:
# Example 3: Determining the grade based on a score
score = 75
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
elif score >= 60:
print("Grade D")
else:
print("Grade F")
Nested if
statements:
# Example 4: Nested if statements to determine eligibility for a loan
income = 50000
credit_score = 700
if income >= 60000:
if credit_score >= 700:
print("You are eligible for a loan with a low interest rate.")
else:
print("You are eligible for a loan with a higher interest rate.")
else:
print("You are not eligible for a loan.")
Loops
For loops
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
While Loops:
count = 0
while count < 5:
print(count)
count += 1
Break and Continue:
Use break
to exit a loop prematurely, and continue
to skip the current iteration.
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i == 5:
continue
print(i)
Looping through Dictionaries
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(f'{key}: {value}')
Loop Control with Else
for i in range(5):
print(i)
else:
print("Loop completed without a break.")
List Comprehensions
numbers = [i for i in range(10) if i % 2 == 0]
SAMPLE PROGRAM
# User inputs
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Control statement (if-else)
if age >= 18:
print(f"Hello {name}! You are eligible to vote.")
else:
print(f"Hello {name}! You are not yet eligible to vote. You can vote in {18 - age} years.")
# For loop
print("Printing numbers from 1 to 5 using a for loop:")
for i in range(1, 6):
print(i)
# While loop
num = int(input("Enter a number: "))
fact = 1
i = 1
while i <= num:
fact *= i
i += 1
print(f"The factorial of {num} is: {fact}")
Conclusion
Here we discuss about python Installation, datatype, control flow statement, loops .
Happy learning!