

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
this is the clas of notes of ptyhon 1st unit up to 13 topics coverd
Typology: Summaries
1 / 25
This page cannot be seen from the preview
Don't miss anything!


















1.5.Explain The Process Of Running Python Scripts : There are various methods to Run a Python script, we will go through some generally used methods for running a Python script: Interactive Mode Command Line Text Editor (VS Code) IDE (PyCharm)
Here is a simple code to print ‘Hello World!’. EX: print('Hello World!') To Execute this program, first we have to save it with the '.py' extension. Then we can execute this file with the help of the terminal. There are various ways to run a script in Python but before going toward the different ways to run a Python script, we first have to check whether a Python interpreter is installed on the system or not. So in Windows, open ‘cmd’ (Command Prompt) and type the following command. python -V This command will give the version number of the Python interpreter installed or will display an error if otherwise.
1. Run Python Script Interactively In Python Interactive Mode, you can run your script line by line in a sequence. To enter an interactive mode, you will have to open Command Prompt on your Windows machine, type ‘python’ and press Enter.
Example1: Using Print Function Run the following line in the interactive mode: print('Hello World !') Output:
Example 2: Using Interactive Execution Run the following lines one by one in the interactive mode. Output:
name = "Aakash" print("My name is " + name)
Example 3: Interactive Mode Comparison Run the following lines one by one in the interactive mode. Output:
a = 1 b = 3
4. Run Python Scripts using an IDE To run Python script on an IDE (Integrated Development Environment) like PyCharm , you will have to do the following: Create a new project. Give a name to that project as ‘GfG’ and click on Create. Select the root directory with the project name we specified in the last step. Right-click on it, go to New, anto, and click on the ‘ Python file ’ option. Then give the name of the file as ‘ hello ’ (you can specify any name as per your project requirement). This will create a ‘ hello.py ’ file in the project root directory. Note: You don’t have to specify the extension as it will take it automatically.
Now write the below Python script to print the message: print('Hello World !') To run this Python script, Right click and select the ‘Run File in Python Console’ option. This will open a console box at the bottom and show the output there. We can also run using the Green Play Button at the top right corner of the IDE.
1.6.Explain Identifiers,keywords,indentation,variables : Python Keywords are reserved words with fixed meanings that define Python’s syntax. Cannot be used as names. Python Identifiers are user-defined names for variables, functions, or classes. Must follow naming rules (no digits at start, only _ allowed). Indentation means spaces at the beginning of a line. Python uses indentation to define blocks of code 1.Keywords in Python:
Predefined and reserved words with special meanings. Used to define the syntax and structure of Python code. Cannot be used as identifiers, variables, or function names. Written in lowercase, except True and False. Python 3.11 has 35 keywords. The keyword module provides: o iskeyword() → checks if a string is a keyword. o kwlist → returns the list of all keywords. Rules for Keywords in Python Python keywords cannot be used as identifiers. All the keywords in Python should be in lowercase except True and False. List of Python Keywords Category Keywords Value Keywords True, False, None Operator Keywords and, or, not, is, in Control Flow Keywords if, else, elif, for, while, break, continue, pass, try, except, finally, raise, assert Function and Class def, return, lambda, yield, class Context Management with, as Import and Module (^) import, from Scope and Namespace global, nonlocal
3.Indentation in Python: ndentation is used to define blocks of code. It indicates to the Python interpreter that a group of statements belongs to the same block. All statements with the same level of indentation are treated as part of the same code block. Indentation is created using tabs or spaces and the commonly accepted convention is to use four spaces. Python expects the indentation level to be consistent within the same block. This inconsistency causes an IndentationError as shown in the below code. print("I have no Indentation ") print("I have tab Indentation ") Explanation: The first print statement has no indentation, so it is correctly executed. The second print statement has tab indentation, but it doesn't belong to a new block of code, that's why it throws IndentationError. 4.Python Variables:
Variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike Java and many other languages, Python variables do not require explicit declaration of type. Type of the variable is inferred based on the value assigned.
x = 5 name = "Alex" print(x) print(name) Output: 5 Alex Rules for Naming Variables To use variables effectively, we must follow Python’s naming rules:
1.7.List And Explain Various Data Types : Data types in Python are a way to classify data items. They represent the kind of value which determines what operations can be performed on that data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of these classes. The following are standard or built-in data types in Python: Numeric: int, float, complex Sequence Type: string, list, tuple Mapping Type: dict Boolean: bool Set Type: set, frozenset Binary Types: bytes, bytearray, memoryview
DataTypes Below code assigns variable 'x' different values of few Python data types - int, float, list, tuple and string. Each assignment replaces previous value, making 'x' take on data type and value of most recent assignment. x = 50 # int x = 60.5 # float x = "Hello World" # string x = ["geeks", "for", "geeks"] # list x = ("geeks", "for", "geeks") # tuple i). Numeric Data Types: Python numbers represent data that has a numeric value. A numeric value can be an integer, a floating number or even a complex number. These values are defined as int, float and complex classes. Integers: value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). There is no limit to how long an integer value can be.
print(s[1]) print(s[2]) print(s[-1] Output: Welcome to the Geeks World
e l d
(b).List Data Type Lists are similar to arrays found in other languages. They are an ordered and mutable collection of items. It is very flexible as items in a list do not need to be of the same type. Creating a List in Python: Lists can be created by just placing sequence inside the square brackets[].
a = []
a = [1, 2, 3] print(a)
b = ["Cbit", "Diploma", "Pdtr", 4, 5] print(b) output: [1, 2, 3] ['Cbit', 'Diploma', 'Pdtr', 4, 5]
(c).Tuple Data Type Tuple is an ordered collection of Python objects. The only difference between a tuple and a list is that tuples are immutable. Tuples cannot be modified after it is created.
Creating a Tuple in Python: tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use of parentheses for grouping data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, lists, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
tup1 = () tup2 = ('Im a', 'Student') print("\nTuple with the use of String: ", tup2) Output: Tuple with the use of String: ('Im a', 'Student')
Access Tuple Items: In order to access tuple items refer to the index number. Use the index operator [ ] to access an item in a tuple. tup1 = ( 1 , 2 , 3 , 4 , 5 )
print(tup1[ 0 ]) print(tup1[- 1 ]) print(tup1[- 3 ]) Output: 1 5 3
iii). Boolean Data Type Python Boolean Data type is one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true) and those equal to False are falsy (false). However non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false. It is denoted by class bool.
EX: is_python_easy = True print(type(is_python_easy)) Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'} {1: 'Geeks', 2: 'For', 3: 'Geeks'}
1.8. Explain Declaration And initialization of variables :
1.Variable Declaration in Python : Variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike languages such as C or Java, Python does not require explicit declaration of variables. A variable is created automatically when you assign a value to it. Example x = 10
Here: x → variable name = → assignment operator 10 → value stored in the variable Python automatically understands that x is an integer variable.
2. Variable Initialization
Initialization means giving a variable its first value. Example name = "Alice" The variable name is initialized with the string "Alice".
3. Examples of Different Variable Types age = 25 # Integer price = 99.99 # Float city = "Delhi" # String is_student = True # Boolean
Python decides the data type automatically.
4. Multiple Variable Initialization
You can initialize multiple variables in one line. Example a, b, c = 1 , 2 , 3 Or assign the same value to multiple variables: x = y = z = 0
6. Rules for Naming Variables
A variable name: Can contain letters, numbers, and underscores Must start with a letter or underscore Cannot start with a number Cannot use spaces Cannot use Python keywords Valid Examples student_name = "Ram" _age = 20 marks1 = 95 Invalid Examples 1 name = "Sam" # Starts with number student name = 5 # Contains space class = 10 # Keyword 1.9. Explain Input And Output Statements: The print() function is used for output in various formats and the input() function enables interaction with users.
Taking Input using input() Python's input() function is used to take user input. By default, it returns the user input in form of a string.
How old are you?: 23 Evaluate 7/2: 3. 23 3.
1.10. explain formatted input output : In Python, formatted input and output allow you to control how data is received from users and how it is displayed on the screen.
Output formatting makes your data readable by aligning text, controlling decimal precision, or embedding variables into messages.
1. Using f-strings (Recommended)
name age == 20 "Ravi"
print(f"My name is {name} and I am {age} years old.")
My name is Ravi and I am 20 years old.
2. Formatting Numbers pi = 3. print(f"Value of pi: {pi:.2f}")
Value of pi: 3.
.2f → show 2 digits after decimal
3. Width and Alignment name = "Python" print print((f"f"{{namename::>10<10}}"")) # Right# Left align align print(f"{name:^10}") # Center align
Python^ Python Python
4. Using format() Method name marks = ="Anu" 95
print("Name: {}, Marks: {}".format(name, marks))
Name: Anu, Marks: 95
5. Old % Formatting name age == 22 "Kiran"
print("Name: %s Age: %d" % (name, age))
Name: Kiran Age: 22
%s → string %d → integer %f → float
split() separates values by spaces map(int, ...) converts them to integers
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program.
It enhance the readability of the code.It can be used to identify functionality or structure the code-base. It can help understanding unusual or tricky scenarios handled by the code to prevent accidental removal or changes. It can be used to prevent executing any specific part of your code, while making changes or testing.
i)Single Line Comments Single line comments starts with hashtag symbol #. Example:
Output
ii)Multi-Line Comments Python does not provide the option for we can write multiline comments. multiline comments. However, there are different ways through which
1. Using multiple hashtags (#) We can use multiple hashtags (#) to write multiline comments. Each and every line will be considered as a single-line comment.
2. Using String Literals Python ignores the comments. string literals that are not assigned to a variable. So, we can use these string literals as
In Python programming, Operators in general are used to perform operations on values and variables. Operators:Operands: Value on which the operator is applied.Special symbols like -, + , * , /, etc.
Types of Operators in Python:
i)Arithmetic Operators: Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication and division. In Python, the division operator (/) returns a floating-point result, while floor division (//) returns an integer result.