introduction - continution¶
hello world¶
- create a new file with editor of your choice and save it as
hello_world.py
- all standard python scripts should be ended with
.py
extension. - type
print("Hello World !")
in newly createdhello_world.py
file and save. - go to activated python virtual environment command prompt and execute python file like this -->
python hello_world.py
. - this should print
Hello World !
in console.
In [ ]:
Copied!
print("Hello World !")
print("Hello World !")
syntax¶
- Python syntax refers to the set of rules that define how you write Python code. These rules determine how the Python interpreter understands and executes your programs.
- Whitespace (Indentation)
- Unlike many other programming languages, Python uses indentation to define code blocks.
- The number of spaces you indent (usually 4 spaces) determines which lines of code belong to the same block.
- Consistent indentation is crucial for Python code to run correctly.
In [ ]:
Copied!
if True: # Indented block for the if statement
print("This code will run because the condition is True.")
else: # Another indented block for the else clause
print("This code won't run because the condition is not False.")
if True: # Indented block for the if statement
print("This code will run because the condition is True.")
else: # Another indented block for the else clause
print("This code won't run because the condition is not False.")
- Comments
- Comments are lines of code that are ignored by the Python interpreter.
- They are used to explain the purpose of code sections, improve readability, and document your program.
- There are two types of comments
- Single-line comments: Start with a hash symbol (
#
) and extend to the end of the line. - Multi-line comments: Enclosed within triple quotes (either three single quotes
'''
or three double quotes"""
).
- Single-line comments: Start with a hash symbol (
In [ ]:
Copied!
# This is a single-line comment
"""
This is a multi-line comment
that can span multiple lines.
"""
'''
This is a multi-line comment
that can span multiple lines.
'''
# This is a single-line comment
"""
This is a multi-line comment
that can span multiple lines.
"""
'''
This is a multi-line comment
that can span multiple lines.
'''
- Keywords
- Python has reserved keywords that have special meanings within the language and cannot be used as variable names.
False, await, else, import, pass, None, break, except, in, raise, True, class, finally, is, return, and, continue, for, lambda, try, as, def, from, nonlocal, while, assert, del, global, not, with, async, elif, if, or, yield
- Python has reserved keywords that have special meanings within the language and cannot be used as variable names.
- Statements
- Statements are instructions that the Python interpreter executes.
- They can be simple assignments, function calls, control flow statements (like
if
andfor
), or expressions that produce a value.
- Built-in Types
- Numeric Types —
int
,float
,complex
- Boolean Type -
bool
- Sequence Types —
list
,tuple
,range
- Text Sequence Type —
str
- Binary Sequence Types —
bytes
,bytearray
,memoryview
- Set Types —
set
,frozenset
- Mapping Types —
dict
- Numeric Types —
- Operators
- Operators are symbols that perform operations on values or variables.
- Python provides arithmetic operators (e.g.,
+
,-
,*
,/
), comparison operators (e.g.,==
, !=
,<
,>
), logical operators (e.g.,and
,or
,not
), assignment operators (e.g.,=
), and more.
- Functions
- Functions are reusable blocks of code that perform specific tasks.
- You define functions using the
def
keyword and specify parameters (inputs) and a return value (output).
- Control Flow Statements
- Control flow statements dictate the order in which the code is executed.
- Python provides
if
statements for conditional execution,for
andwhile
loops for iterative execution, andbreak
andcontinue
statements for controlling loops.
- Modules and Packages
- Modules and packages are ways to organize Python code into reusable components.
- Modules are single Python files containing functions, variables, and classes.
- Packages are collections of modules that are hierarchically organized
variables¶
- In Python, variables act as named containers that hold data values throughout your program's execution. They provide a flexible way to store, manipulate, and reference information as needed.
- Variables provide a way to store and manage data in your Python programs.
- They are dynamically typed, offering flexibility.
- Adhere to naming conventions for readability.
- Understand different data types for appropriate storage.
- Be mindful of variable scope to avoid unintended consequences.
- By effectively using variables, you can write well-organized and maintainable Python code
- The fundamental way to create a variable is by assigning a value to it using the equal sign (
=
). The variable name becomes associated with the value in memory. - Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable beforehand. The interpreter infers the type based on the assigned value.
In [ ]:
Copied!
name = "Chaitanya"
age = 30
distance = 5.2 # Can store floating-point numbers
name = "Chaitanya"
age = 30
distance = 5.2 # Can store floating-point numbers
variable naming rules
- Start with a letter or underscore (
_
):name
,_temp
,total_count
are valid names. - Alphanumeric characters: After the first character, you can use letters, numbers, and underscores.
- Case-sensitive:
age
andAge
are considered different variables. - Avoid reserved keywords: Don't use words that have special meanings in Python, like
if
,for
,while
.
- Start with a letter or underscore (
variable scope
- Local Variables: Variables defined within a function or block of code (indented section) are only accessible within that scope.
- Global Variables: Variables declared outside of any function are considered global and can be accessed from anywhere in the program (use with caution).
- You can change the value stored in a variable later in your code by assigning a new value to it. This doesn't create a new variable, but modifies the existing one's content.
In [ ]:
Copied!
age = 30 # Initial assignment
age = 35 # Reassignment
age = 30 # Initial assignment
age = 35 # Reassignment
operators¶
- Python operators are symbols that perform operations on values or variables.
- They are essential building blocks for creating expressions and manipulating data in your Python programs.
- Arithmetic Operators (Used for performing mathematical calculations)
+
--> (addition)-
--> (subtraction)*
--> (multiplication)/
--> (division) - Returns a float, even if the operands are integers.//
--> (floor division) - Divides and returns the largest integer less than or equal to the result (rounded down towards negative infinity).%
--> (modulo) - Returns the remainder after division.**
--> (exponentiation) - Raises the left operand to the power of the right operand.
In [ ]:
Copied!
a, b = 10, 20
print(a + b) # addition. prints 30
print(a - b) # subtraction. prints -10
print(a * b) # multiplication. prints 200
print(a / b) # division. prints 0.5
print(a // b) # floor division. prints 0
print(a % b) # modulo. prints 10
print(a ** b) # exponentiation. prints 100000000000000000000
a, b = 10, 20
print(a + b) # addition. prints 30
print(a - b) # subtraction. prints -10
print(a * b) # multiplication. prints 200
print(a / b) # division. prints 0.5
print(a // b) # floor division. prints 0
print(a % b) # modulo. prints 10
print(a ** b) # exponentiation. prints 100000000000000000000
- Comparison Operators (Used for comparing values and returning Boolean results (True or False))
==
--> (equal to)!=
--> (not equal to)<
--> (less than)>
--> (greater than)<=
--> (less than or equal to)>=
--> (greater than or equal to)
In [ ]:
Copied!
a, b = 10, 20
print(a == b) # result False
print(a != b) # result True
print(a < b) # result True
print(a > b) # result False
print(a <= b) # result True
print(a >= b) # result False
a, b = 10, 20
print(a == b) # result False
print(a != b) # result True
print(a < b) # result True
print(a > b) # result False
print(a <= b) # result True
print(a >= b) # result False
- Logical Operators (Used for combining conditional expressions)
and
--> Returns True if both operands are True, False otherwise.or
--> Returns True if at least one operand is True, False otherwise.not
--> Inverts the truth value of an operand (True becomes False, False becomes True).
In [ ]:
Copied!
a, b = 10, 20
result = (a > 0) and (b < 20)
print(result) # result False
result = (a > 0) or (b < 20)
print(result) # result True
result = not ((a > 0) and (b < 20))
print(result) # result True
a, b = 10, 20
result = (a > 0) and (b < 20)
print(result) # result False
result = (a > 0) or (b < 20)
print(result) # result True
result = not ((a > 0) and (b < 20))
print(result) # result True
- Assignment Operators (Used for assigning values to variables)
=
(simple assignment)+=
,-=
,*=
,/=
,//=
(compound assignment) --> Perform the operation on the right and assign the result to the variable on the left (e.g.,x += 3
is equivalent tox = x + 3
)
In [ ]:
Copied!
a = 10
print(f'a --> {a}')
a += 10
print(f'a += 10 --> {a}')
a -= 10
print(f'a -= 10 --> {a}')
a *= 10
print(f'a *= 10 --> {a}')
a /= 10
print(f'a /= 10 --> {a}')
a //= 10
print(f'a //= 10 --> {a}')
a = 10
print(f'a --> {a}')
a += 10
print(f'a += 10 --> {a}')
a -= 10
print(f'a -= 10 --> {a}')
a *= 10
print(f'a *= 10 --> {a}')
a /= 10
print(f'a /= 10 --> {a}')
a //= 10
print(f'a //= 10 --> {a}')
- Identity Operators (Used to check object identity (whether they refer to the same object in memory))
is
--> (returns True if objects are the same object)is not
--> (returns True if objects are not the same object)
In [ ]:
Copied!
a, b = 10, 20
result = a is b
print(result) # result False
result = a is not b
print(result) # result True
a, b = 10, 20
result = a is b
print(result) # result False
result = a is not b
print(result) # result True
- Membership Operators (Used to check if a value is a member of a sequence (like a list or tuple))
in
--> (returns True if the value is found in the sequence)not in
--> (returns True if the value is not found in the sequence)
In [ ]:
Copied!
line = 'hello python noob!'
result = 'noob' in line
print(result) # result True
result = 'noob' not in line
print(result) # result False
line = 'hello python noob!'
result = 'noob' in line
print(result) # result True
result = 'noob' not in line
print(result) # result False
- Bitwise Operators (Used for performing bit-level operations on integers (less common, but useful for low-level programming tasks))
&
--> (bitwise AND)|
--> (bitwise OR)^
--> (bitwise XOR)~
--> (bitwise NOT)<<
--> (left shift)>>
--> (right shift)
In [ ]:
Copied!
result = 0xFF & 0x10
print(result)
result = 0xFF | 0x10
print(result)
result = 0xFF ^ 0x10
print(result)
result = ~3
print(result)
result = 0xFF << 1
print(result)
result = 0xFF >> 1
print(result)
result = 0xFF & 0x10
print(result)
result = 0xFF | 0x10
print(result)
result = 0xFF ^ 0x10
print(result)
result = ~3
print(result)
result = 0xFF << 1
print(result)
result = 0xFF >> 1
print(result)
- Remember that operators have precedence (order of operations), which determines how expressions are evaluated.
- You can use parentheses to override the default precedence.
- By effectively using operators, you can write clear, concise, and efficient Python code to perform various calculations, comparisons, and data manipulations.
user input¶
- In Python, you can obtain user input using the
input("prompt")
function. Here's a comprehensive explanation:user_input = input('prompt')
- The
input()
Function Pauses your program's execution and waits for the user to enter some text or data. prompt
(optional): A string that is displayed to the user, providing instructions or context for what kind of input is expected.- The
input()
function returns a string, regardless of what the user types. This is because Python always interprets user input as text.name = input("What is your name? ") print("Hello,", name)
- The program displays the prompt "What is your name? ".
- The user types their name and presses Enter.
- The program stores the user's input (their name) in the variable name.
- The program prints a greeting message that includes the user's name.
- Type Casting
- Since
input()
returns a string, you might need to convert the user input to a different data type (like integer or float) if you want to perform numerical operations on it. You can use built-in functions likeint()
,float()
, orbool()
for type castingage_str = input("How old are you? ") age = int(age_str) # Convert string to integer print("You are", age, "years old.")
- Since
- Error Handling
- It's good practice to anticipate potential errors during user input. For example, if the user enters a non-numeric value when you expect a number, it will cause a
ValueError
. You can usetry-except
blocks to handle such exceptions gracefullytry: number = float(input("Enter a number: ")) result = number * 2 print("The doubled number is:", result) except ValueError: print("Invalid input: Please enter a number.")
- It's good practice to anticipate potential errors during user input. For example, if the user enters a non-numeric value when you expect a number, it will cause a