PythonProgramming Unit1 Complete
PythonProgramming Unit1 Complete
Essentials of 1.3 Data types and Variables, Getting and setting the data type,
Constants, Lines and indentation, Input/output with print and
Python input, Command line arguments
Programming 1.4 Operators and expressions, Precedence of operators, type
conversion
Programming
6. Platform-Independent
Code can run on different operating systems without modification.
Python Variables
• In Python, variables are created when you assign a value to it
• Python has no command for declaring a variable.
Python Comments
• In Python has commenting capability for the purpose of in-code documentation.
• Comments start with a #, and Python will render the rest of the line as a comment
Variables • Rules for Naming
1. Variables Must begin with a letter or an
underscore (_).
• Variables are containers for storing data values.
• A variable is a name that refers to a memory 2. Can contain letters, numbers, and underscores.
location used to store data. 3. Cannot start with a digit.
• In Python, variables are created when you assign a 4. Cannot use Python keywords (e.g., if, while).
value to them 5. Case-sensitive: variable and Variable are
• Ex: different.
x = 10 • Casting
name = "Amit"
• If you want to specify the data type of a variable,
• Variables do not need to be declared with any this can be done with casting.
particular type, and can even change type after
they have been set. • Ex:
x = str(3) # x will be '3'
• Ex:
y = int(3) # y will be 3
x = 10 # Integer
z = float(3) # z will be 3.0
x = "Hello" # String
print(x) • Checking Type of a Variable
• Use the type() function to find a variable's type:
x = 10
print(type(x)) # Output: <class 'int’>
Getting the Data Type
• Use the type() function to check the data type of a variable.
x = 5
print(type(x))
# Output: <class 'int’>
y = "Hello"
print(type(y))
# Output: <class 'str'>
> Greater than Returns true if the first value is greater a>b
than the second value
< Less than Returns true if the first value is less than a<b
the second value
>= Greater than or equal Returns true if the first value is greater a >= b
to than, or equal to, the second value
<= Less than or equal to Returns true if the first value is less than, a <= b
or equal to, the second value
Logical Operators
• Logical operators are used to check 2 or more different conditions and take decision accordingly
Note
• In the case of AND, the result is true only if both conditions are true.
• In the case of OR, the result is false only if both conditions are false.
• The logical NOT operator takes the operand and reverses the value of the expression
• They are commonly used in decision-making statements like if, while, and for loops to combine
multiple conditions.
and Logical AND Returns 1 if both statements are true if x < y and y < z:
not Logical NOT Reverse the result, returns 0 if the result is if not x > y :
1
Assignment Operators
Operator Description Example Same as
= Simple assignment operator. Assigns values from right side x=5 x=5
operands to left side operand
+= It adds the right operand to the left operand and assign the result x += 3 x=x+3
to the left operand.
-= It subtracts the right operand from the left operand and assigns x -= 3 x=x-3
the result to the left operand.
*= It multiplies the right operand with the left operand and assigns x *= 3 x=x*3
the result to the left operand.
/= It divides the left operand with the right operand and assigns the x /= 3 x=x/3
result to the left operand.
//= It combines the floor division operation with assignment. It x //= 2 x = x // 2
divides the value of the variable on the left by the value on the
right and then assigns the result back to the variable.
%= It takes modulus using two operands and assigns the result to the x %= 3 x=x%3
left operand.
**= It raises the value of the variable on the left to the power of the x **= 2 x = x ** 2
value on the right and assigns the result back to the variable.
Bitwise Operators
Operator Name Description Example
| OR Sets each bit to 1 if one of x|y • Bitwise operators are used on (binary)
two bits is 1 numbers.
^ XOR Sets each bit to 1 if only x^b • These operators are essential for
one of two bits is 1 tasks such as low-level programming,
hardware manipulation, and
~ NOT Binary One's Complement ~x optimizing certain algorithms
Operator is unary and has
the effect of 'flipping' bits.
<< Zero fill left shift Shift left by pushing zeros in x << 2
from the right
>> Signed right Shift right by pushing copies x >> 2
shift of the leftmost bit in from
the left, and let the
rightmost bits fall off
Membership Operators
• Used to check if a value exists in a
Operator Description Example Result sequence.
Identity Operators
• Used to check if two variables
Operator Description Example Result reference the same object.
• str.isalnum(): Checks if all characters are • str.islower(): Checks if all characters are
alphanumeric. lowercase.
print("hello123".isalnum()) print("hello".islower())
# Output: True # Output: True
Special operations on string
String Escaping with Backslashes Raw Strings
• Special characters can be included in strings using • Raw strings treat backslashes as literal characters,
escape sequences, Common escape sequences: useful for regex or file paths
\n: Newline raw_string =
\t: Tab r"C:\Users\Name\Documents"print(raw_string)
# Output: C:\Users\Name\Documents
\\: Backslash
\': Single quote Substring Membership
\": Double quote • Check if a substring exists using in and not in
text = "This is a line.\nThis is a new text = "Python programming“
line." print("Python" in text) # True
# \n for new line print("Java" not in text) # True
print(text)
Count Substring Occurrences
text = "This is a tab:\tHere."
text = "banana"print(text.count("a")) # 3
# \t for tab
print(text) Other
quote = "He said, \"Hello!\"" • len(str): returns no of character in string
# Escaping quotes • ord(char): Returns the ASCII value of the given
print(quote) character.
String formatting operator
• The string formatting operator % is an older method Floating-Point Formatting
for formatting strings. pi = 3.14159265
• It allows you to embed values into strings by using print("Pi is approximately %.2f." % pi)
placeholders. # Output: Pi is approximately 3.14.
• Placeholder Description Hexadecimal and Octal
%s String or any object (uses str()). number = 255
%d Integer print("Hex: %x, Octal: %o" % (number,
%f Floating-point number number))
%.nfFloating-point with n decimal places. # Output: Hex: ff, Octal: 377
%x Hexadecimal (lowercase) Escape % Symbol
%X Hexadecimal (uppercase) • To include a literal % symbol in your string, use %%
%o Octal discount = 50
Basic Usage print("Get a %d%% discount!" % discount)
name = "Alice“ # Output: Get a 50% discount!
age = 25
print("My name is %s and I am %d years
old." % (name, age))
# Output: My name is Alice and I am 25
years old.
String formatting operator
Using a Tuple
name = “Bob”
age = 30
print("Name: %s, Age: %d" % (name, age))
Using a Dictionary
info = {"name": "Bob", "age": 30}
print("Name: %(name)s, Age: %(age)d" %
info)