python myscript.py
In Python, handling user input and displaying output is straightforward and flexible. This section will cover the basic methods for taking input and displaying output.
In Python, you can take input from the user using the input()
function. This function reads
a line from input, converts it into a string, and returns it. You can then convert this string into the
desired data type using typecasting.
Example:
# Taking input from the user
name = input("Enter your name: ")
print(f"Hello, {name}!")
To convert the input to a specific type, you can use typecasting functions like int()
,
float()
, etc.
Example:
# Taking integer input from the user
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
In Python, you can display output to the user using the print() function. The print() function outputs data to the console.
Example:
# Displaying output
print("Hello, World!")
You can format the output using formatted strings (f-strings), the format() method, or the % operator.
Example using f-strings:
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Example using format() method:
name = "Alice"
age = 30
print("{} is {} years old.".format(name, age))
Example using % operator:
name = "Alice"
age = 30
print("%s is %d years old." % (name, age))
Here’s a simple program that takes an integer input from the user, calculates its square, and displays the result:
# Taking integer input from the user
num = int(input("Enter a number: "))
# Using a lambda function to calculate the square of the number
square = lambda x: x * x
# Displaying the result using an f-string
print(f"The square of {num} is {square(num)}")
In Python, there is no need to explicitly mention the data type when declaring a variable; Python automatically infers the data type based on the assigned value.
This feature is known as dynamic typing, and it allows for greater flexibility in variable assignment. Unlike statically typed languages, where the data type must be explicitly declared before using a variable, Python allows you to assign values to variables without specifying their types.
For example:
# Dynamic Typing in Python
my_variable = 10 # Python infers the data type as integer
my_string = "Hello" # Python infers the data type as string
my_float = 3.14 # Python infers the data type as float
# Variables can change data type dynamically
my_variable = "World" # Now my_variable is a string
Following are all data type used in python:
To determine the data type of a variable in Python, you can use the built-in `type()` function.
x = 5
data_type = type(x)
print(data_type) # Output: <class 'int'>
Slicing:
In Python, slicing is a technique used to extract a portion of a string. The syntax for slicing a string is as follows:
string[start:stop:step]
We should know about forward and backward indexing:
str = "PROGRAMMING"
print(str[0]) # Output : P
print(str[-1]) # Output : G
# Example String
my_string = "Hello, World!"
# Basic Slicing
substring = my_string[7:12] # Extracts "World"
print(substring)
# Omitting Start and Stop (Defaults to the entire string)
whole_string = my_string[:] # Extracts the entire string
print(whole_string)
# Slicing with Step
every_second_char = my_string[::2] # Extracts every second character
print(every_second_char)
# Reverse the String
reverse_string = my_string[::-1] # Reverses the string
print(reverse_string)
#When you use a negative step value like -1, it means that you want to iterate over the original sequence in reverse order.
A list in Python is a versatile and mutable collection that allows you to store and manipulate a sequence of items. Lists are defined by enclosing comma-separated values within square brackets [ ].
Key characteristics and operations associated with lists:
Example of creating a list:
my_list = [1, 2, 3, "Hello", 3.14, True]
Common operations on lists:
Example:
numbers = [1, 2, 3, 4, 5]
print(numbers[2]) # Output: 3
print(numbers[1:4]) # Output: [2, 3, 4]
numbers[0] = 10 # Modifying element at index 0
numbers.append(6) # Appending 6 to the end
numbers.extend([7, 8]) # Extending with another list
numbers.remove(3) # Removing element with value 3
print(len(numbers)) # Output: 7
# Define a list
my_list = [1, 2, 3, 4, 5]
# Print the original list
print("Original list:", my_list)
# Modify the list by changing the second element
my_list[1] = 10
# Print the modified list
print("Modified list:", my_list)
Output:
Original list: [1, 2, 3, 4, 5]
Modified list: [1, 10, 3, 4, 5]
A tuple in Python is an ordered, immutable collection of elements. Tuples are defined by enclosing comma-separated values within parentheses ( ). Once created, the elements of a tuple cannot be modified or altered.
Key characteristics and considerations related to tuples:
Example of creating a tuple:
my_tuple = (1, 2, 3, "Hello", 3.14, True)
Common operations on tuples:
len()
.Example:
coordinates = (4, 5)
print(coordinates[1]) # Output: 5
print(coordinates[0:]) # Output: (4, 5)
print(len(coordinates)) # Output: 2
# Unpacking a tuple
x, y = coordinates
print(x) # Output: 4
print(y) # Output: 5
# Define a tuple
my_tuple = (1, 2, 3, 4, 5)
# Print the original tuple
print("Original tuple:", my_tuple)
# Trying to modify the tuple by changing the second element (this will cause an error)
# my_tuple[1] = 10 # Uncomment this line to see the error
# Print the tuple (unchanged)
print("Tuple after trying to modify:", my_tuple)
A set in Python is an unordered and mutable collection of unique elements. Sets are defined by enclosing comma-separated values within curly braces {}. Sets provide efficient methods for performing mathematical set operations like union, intersection, and difference.
Key characteristics and considerations related to sets:
Example of creating a set:
my_set = {1, 2, 3, "apple", 3.14, True}
Common operations on sets:
Example:
my_set.add(4) # Adding element 4 to the set
my_set.remove("apple") # Removing "apple" from the set
other_set = {2, 3, 5, "orange"}
union_result = my_set.union(other_set) # Union of two sets
intersection_result = my_set.intersection(other_set) # Intersection of two sets
difference_result = my_set.difference(other_set) # Difference between two sets
print(union_result) # Output: {1, 2, 3, 4, 5, 3.14, True, 'orange'}
print(intersection_result) # Output: {2, 3}
print(difference_result) # Output: {1, 4, 'apple', 3.14, True}
Sets are useful for various tasks, such as removing duplicates from a collection, performing set operations, and checking membership in an efficient manner.
A dictionary in Python is a mutable and unordered collection of key-value pairs. Dictionaries are defined by enclosing comma-separated key-value pairs within curly braces {}. Each key in a dictionary must be unique, and it is associated with a specific value.
Key characteristics and considerations related to dictionaries:
Example of creating a dictionary:
my_dict = {"name": "John", "age": 25, "city": "New York"}
Common operations on dictionaries:
del
or
pop()
methods.
keys()
and values()
methods.
Example:
print(my_dict["name"]) # Output: John
my_dict["age"] = 26 # Modifying the age
my_dict["gender"] = "Male" # Adding a new key-value pair
del my_dict["city"] # Removing the "city" key
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'gender'])
print(my_dict.values()) # Output: dict_values(['John', 26, 'Male'])
Dictionaries are versatile and widely used in Python for tasks such as storing and retrieving data with meaningful labels, configuration settings, and more.
You can create a DataFrame in Python using various methods, such as:
pip install pandas
import pandas as pd
# Creating a dictionary
data = {
'Name': ['John', 'Alice', 'Bob', 'Eve'],
'Age': [28, 24, 22, 26],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Seattle']
}
# Creating a DataFrame from the dictionary
df = pd.DataFrame(data)
# Displaying the DataFrame
print("Original DataFrame:")
print(df)
If we want to change the indexing of data frame then we can do the following:
import pandas as pd
data = {'Name': ['John', 'Emma', 'Peter'],
'Age': [30, 25, 35],
'City': ['New York', 'San Francisco', 'Chicago']}
df = pd.DataFrame(data, index=['a', 'b', 'c'])
print(df.loc['a'])
Output:
Name John
Age 30
City New York
Name: a, dtype: object
We can also perform the transpose of the DataFrame using the `.T` attribute or using the 'transpose()' function:
import pandas as pd
# Create a DataFrame
data = {'Name': ['John', 'Emma', 'Peter'],
'Age': [30, 25, 35],
'City': ['New York', 'San Francisco', 'Chicago']}
df = pd.DataFrame(data, index=['a', 'b', 'c'])
# Transpose the DataFrame
transposed_df = df.transpose()
Type conversion, also known as type casting, is the process of changing the data type of a variable from one type to another. Python provides built-in functions for performing type conversion, allowing developers to seamlessly work with different data types as needed.
Key points about type conversion in Python:
Examples of type conversion:
# Implicit conversion
num_int = 5
num_float = 3.14
result = num_int + num_float # Implicitly converts num_int to float before addition
# Explicit conversion
str_num = "123"
int_num = int(str_num) # Converts string to integer using int() function
float_num = float(str_num) # Converts string to float using float() function
# Conversion between sequence types
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts list to tuple using tuple() function
my_set = set(my_list) # Converts list to set using set() function
# Numeric type conversion
float_result = float(num_int) # Converts integer to float using float() function
int_result = int(num_float) # Converts float to integer using int() function
Command line arguments provide a way to pass information to a Python script when it is executed from the command line. These arguments are accessible within the script and can be used to customize its behavior based on user input.
Key points about command line arguments:
Example:
import sys
# Accessing command line arguments
script_name = sys.argv[0]
first_argument = sys.argv[1] if len(sys.argv) > 1 else None
second_argument = sys.argv[2] if len(sys.argv) > 2 else None
print("Script Name:", script_name)
print("First Argument:", first_argument)
print("Second Argument:", second_argument)
When executing the script from the command line:
python script.py arg1 arg2
The output would be:
Script Name: script.py
First Argument: arg1
Second Argument: arg2
Simple program to add two number provided through command line:
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
sum = num1 + num2
print("The sum is = ", str(sum))
When executing the script from the command line:
python3 test.py 5 4
Output:
The sum is 9
Rules of Indentation:
It's essential to adhere to these rules for maintaining readable and error-free Python code.
a = "something"
# Incorrect indentation below; it will result in an error
b = "another"
a = 10
b = 5
result = a + b
print(result) # Output will be 15
a = 10
b = 5
result = a - b
print(result) # Output will be 5
a = 10
b = 5
result = a * b
print(result) # Output will be 50
a = 10
b = 5
result = a / b
print(result) # Output will be 2.0
a = 10
b = 3
result = a % b
print(result) # Output will be 1
a = 2
b = 3
result = a ** b
print(result) # Output will be 8
a = 10
b = 3
result = a // b
print(result) # Output will be 3
a = 10
b = 10
result = a == b
print(result) # Output will be True
a = 10
b = 5
result = a != b
print(result) # Output will be True
a = 10
b = 5
result = a > b
print(result) # Output will be True
a = 5
b = 10
result = a < b
print(result) # Output will be True
a = 10
b = 10
result = a >= b
print(result) # Output will be True
a = 5
b = 10
result = a <= b
print(result) # Output will be True
x = 5
y = 10
z = 15
result = (x < y) and (y < z)
print(result) # Output will be True
x = 5
y = 10
z = 15
result = (x < y) or (x > z)
print(result) # Output will be True
x = 5
y = 10
result = not (x > y)
print(result) # Output will be True
a = 10 # 1010 in binary
b = 4 # 0100 in binary
result = a & b
print(result) # Output will be 0
a = 10 # 1010 in binary
b = 4 # 0100 in binary
result = a | b
print(result) # Output will be 14
a = 10 # 1010 in binary
b = 4 # 0100 in binary
result = a ^ b
print(result) # Output will be 14
a = 10 # 1010 in binary
result = ~a
print(result) # Output will be -11
a = 10 # 1010 in binary
result = a << 1
print(result) # Output will be 20
a = 10 # 1010 in binary
result = a >> 1
print(result) # Output will be 5
a = 10
print(a) # Output will be 10
a = 10
a += 5
print(a) # Output will be 15
a = 10
a -= 5
print(a) # Output will be 5
a = 10
a *= 5
print(a) # Output will be 50
a = 10
a /= 5
print(a) # Output will be 2.0
a = 10
a %= 3
print(a) # Output will be 1
a = 2
a **= 3
print(a) # Output will be 8
a = 10
a //= 3
print(a) # Output will be 3