0% found this document useful (0 votes)
4 views

Py Unit1

Uploaded by

shainnshutup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Py Unit1

Uploaded by

shainnshutup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Example :

 Python is a versatile and widely-used programming language # Basic print statement


known for its readability and ease of use print("Hello, World!")
 It is object oriented programming language # Printing multiple values
name =, nam "Alice"
age = 30
 Python's programming cycle is notably shorter due to its print("Name:"e, "Age:", age)
interpreted nature. # Changing separator and end
 Python skips compile and link steps, distinguishing itself from
print("Four")
traditional languages.
 Programs import modules at runtime, ensuring immediate print("One", "Two", "Three", sep=' | ', end='
execution after changes. *** ')
 Dynamic module reloading in Python allows modifications and
reloads during runtime, facilitating continuous program
updates without interruptions.  The input() function is used to take user input from the
console. It waits for the user to enter some text and returns
that text as a string.
Syntax :
variable = input(prompt)

Example
# Taking user input
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Converting input to integer
age = int(input("Enter your age: "))
print("You will be", age + 1, "years old next
year.")

 Single-Line Comments:
 An Integrated Development Environment (IDE) is a software  Created with #.
suite that streamlines the software development process.  Used for short explanations on the same line.
 Syntax :
# Single-line comment
 Multi-Line (Block) Comments:
 Achieved with triple-quoted strings.
 Used for longer explanations spanning multiple lines.
 Syntax :
'''
Multi-line comment
'''
 Best Practices:
 Provide clarity and context.
 Keep comments concise and up-to-date.
 Avoid redundancy with self-explanatory code.
 Example :
result = calculate_total(price, quantity) # Calculate total cost

 Comments serve to improve code readability and


 Key features include:
understanding without affecting program execution.
1.Code Editing 7.Debugging
2.Build and Compilation 8. Version Control
3.Project Management 9.Testing  A variable holds a value that may change.
4.User Interface Design 10.Auto-Completion  The process of writing the variable name is called declaring
5.Extensibility 11.Performance Profiling the variable.
6.Documentation and Help  In Python, variables do not need to be declared explicitly in
order to reserve memory spaces as in other programming
languages like C, Java, etc.
 The print() function is used to display output on the console.
 When we initialize the variable in Python, Python Interpreter
 It can take one or more arguments and prints them to the
automatically does the declaration process.
standard output (usually the console).
 Syntax :
Syntax
Variable = Expression
print(value1, value2, ..., sep=' ', end='\n')
 Example :
x = 10 # Variable x is initialized with the value 10
 An identifier is a name given to a variable, function, class,  Automatic conversion by Python based on the operation
module, or other entities in a program. being performed.
 Rules for Naming:
 Must start with a letter (a-z, A-Z) or an underscore (_).
 Use specific functions for explicit conversion:
 The remaining characters can be letters, numbers (0-9), or
 int() for integer conversion.
underscores.  float() for float conversion.
 Case-sensitive (e.g., variable and Variable are different).
 str() for string conversion.
 Cannot be a reserved word (e.g., if, else, for, etc.).

Examples:
 Reserved keywords in a programming language are words # Implicit conversion
that have special meanings and cannot be used as identifiers result = 10 + 3.14 # int implicitly converted
(names for variables, functions, etc.)
to float for addition
 because they are reserved for specific purposes in the
language. # Explicit conversion
num_float = 5.5
num_int = int(num_float) # Converts float to
integer
str_num = str(42)

 input() returns a string, so use int() or float() for numerical


input.
 age_str = input("Enter your age: ")
 age_int = int(age_str) # Converts input string to integer

 data types represent the type of data that a variable can hold.
 Here are some common data types in Python:  A combination of symbols that yields a value.
 Integer (int):  Comprises variables, operators, values, sub-expressions, and
 Represents whole numbers without decimal points.
reserved keywords.
 Example: x = 5
 When entered in the command line, expressions are
 Float (float): evaluated by the interpreter, producing a result.
 Represents numbers with decimal points or in exponential
 arithmetic expressions are evaluating to a numeric type are
form. termed arithmetic expressions.
 Example: y = 3.14
 Sub-expressions are parts of larger expressions, enclosed in
 String (str): parentheses.
 Represents text or sequences of characters.
 Example: 4 + (3 * k)
 Example: name = "John"
 Individual Expressions: A single literal or variable can also be
 Boolean (bool): considered an expression (e.g., 4, 3, k).
 Represents either True or False.
 Hierarchy of Sub-Expressions: Expressions may have
 Example: is_valid = True
multiple levels of sub-expressions, forming a hierarchy.
 List (list):  Example: a + (b * (c - d)) has sub-expressions 3 and k.
 Represents an ordered collection of elements.
 Example: numbers = [1, 2, 3]
 Tuple (tuple):  Used for creating, assigning values to, and modifying
 Similar to a list but immutable (cannot be changed after variables.
creation).  Syntax:
 Example: coordinates = (4, 5)  Variable = Expression represents the assignment statement.
 Set (set):
 Represents an unordered collection of unique elements.
 Value-based expression on RHS.
 Example: unique_numbers = {1, 2, 3}
x = 5 + 3 # Assign the result of the expression (5 + 3) to the
 Dictionary (dict):
variable x
 Represents a collection of key-value pairs.
 Current variable on RHS.
 Example: person = {'name': 'Alice', 'age': 25}
y=2
 NoneType (None):
y = y + 1 # Increment the value of the variable y by 1
 Represents the absence of a value or a null value.
 Operation on RHS.
 Example: result = None
a = 10
 Complex (complex):
b=2
 Represents complex numbers with a real and an imaginary
c = a / b # Assign the result of the division operation (a / b)
part.
to the variable c
 Example: z = 3 + 4j

 operators are special symbols or keywords that perform


 Type conversion in Python is changing the data type of a
operations on operands.
variable, allowing operations involving different data types.
Arithmetic Operators:
 Perform basic mathematical operations.
 Examples: + , - , * , / , % , **
Program:
a=5
b=10+a
Print(a, b ) #output 5 15

 Compare two values and return a Boolean result.


 Examples: == , != , < , > , <= , >=
Program
a=5
b=10
Print(a==b , a> b , a< b ) #output:  Operator precedence defines the order in which different
false false true operators are evaluated in an expression. Operators with
higher precedence are evaluated first.
 Perform logical operations on Boolean values.
 Examples: and , or, not  Determines the order of execution for operators with the
Program same precedence.
a=5
b=10 a. Left to Right:
Print( a> b and a< b ) #output: false  Operators of the same precedence are executed from the left
Print( a> b or a< b ) #output: true side first.
b. Right to Left:
Print( not a< b ) #output: false
 Operators of the same precedence are executed from the
right side first.
 Assign values to variables. Associativity in Python:
 Examples: =, +=, -= , *= , /=  Left-to-right associative operators include multiplication,
Program floor division, etc.
a=5  The ** operator is right-to-left associative.
a+=6 Example
Print(a ) #output: 11  result_left = 5 + 3 - 2 # Addition and subtraction with left-to-
right associativity
 print(result_left) # Output: 6
 result_right = 2 ** 3 ** 2 # Exponentiation with right-to-left
 Perform operations on individual bits of binary numbers.
associativity
 Examples: & , | , ^ , ~ , << , >>
print(result_right) # Output: 512
Program
a=5
 PEP 8 is the Python Enhancement Proposal that provides
b=6
style guidelines for writing clean, readable, and consistent
Print(a & b , ~b ) #output: 4, -7 Python code.
 Here are some key points from PEP 8
 Check if a value is a member of a sequence.  Indentation:Use 4 spaces per indentation level.
 Examples: in , not in  Maximum Line Length:Limit all lines to a maximum of 79
Program characters for code, and 72 for docstrings.
a=[5.,3,2,3]  Imports:Import standard libraries first, followed by third-
b=4 party libraries, and then your own modules.
 Whitespace in Expressions and Statements:
Print(b in a , b not in a ) #output: false true
 Immediately inside parentheses, brackets, or braces.
 Immediately before a comma, semicolon, or colon.
 Compare the memory location of two objects.  Comments:Comments should be used to explain complex
 Examples: is ,is not pieces of code or decisions that may not be obvious.
Program  Naming Conventions:
a=5  Use snake_case for function and variable names.

b=a  Use CamelCase for class names.


 Avoid single-letter variable names except for indices and
Print(a is b , a is not b ) #output: true false
loop variables.
 Docstring Conventions:
 Use triple double-quotes for docstrings.
 Write docstrings for all public modules, functions, classes,
and methods.
1. Write a Python program that declares three variables
(integer, string, and float) and prints their values
2. Calculate the average of three numbers
3. Create a program that takes two numbers as input and
calculates their sum, difference, product, and quotient.

4. Write a program that compares two numbers and prints


whether they are equal, greater, or smaller.

5. Develop a program that takes two strings as input and


concatenates them. Print the resulting string.

6. Implement a Python program that demonstrates


incrementing a variable by 1 and then decrementing it by 1.

7. Create a Python program that swaps the values of two


variables without using a temporary variable.

8. Develop a program that uses compound assignment


operators to update the values of variables.

9. Write a Python program that takes user input for their name,
age, and favorite color. Print a formatted output using this
information.

You might also like