Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

python-1-chapter

The document provides an introduction to Python programming, highlighting its dynamic, high-level, open-source nature and features such as ease of coding, readability, and support for object-oriented programming. It also covers Python keywords, identifiers, variables, comments, and data types, detailing rules for naming and examples of each. Additionally, it explains standard data types in Python, including numbers, strings, and lists, along with their characteristics and usage.

Uploaded by

ogman506
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python-1-chapter

The document provides an introduction to Python programming, highlighting its dynamic, high-level, open-source nature and features such as ease of coding, readability, and support for object-oriented programming. It also covers Python keywords, identifiers, variables, comments, and data types, detailing rules for naming and examples of each. Additionally, it explains standard data types in Python, including numbers, strings, and lists, along with their characteristics and usage.

Uploaded by

ogman506
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

Introduction and syntaxt of paython programming

Python

Python is a dynamic, high-level, free open source, and interpreted programming
language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it is a
dynamically typed language. For example, x = 10 Here, x can be anything such as
String, int, etc. In this article we will see what characteristics describe the python
programming language

Features in Python
In this section we will see what are the features of Python programming language:
1. Free and Open Source
Python language is freely available at the official website and you can download it
from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that source
code is also available to the public. So you can download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in the Python language and anybody can learn Python basics in a few
hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s
syntax is really straightforward. The code block is defined by the indentations rather
than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in Python. PyQt5 is the most popular option for creating graphical
apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need
to remember the system architecture, nor do we need to manage the memory.
7. Large Community Support
Python has gained popularity over the years. Our questions are constantly answered
by the enormous StackOverflow community. These websites have already provided
answers to many questions about Python, so Python users can consult them as needed.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and
correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can determine
what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for
Windows and if we want to run this code on other platforms such as Linux, Unix, and
Mac then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc

Keywords in Python
Python Keywords are some predefined and reserved words in Python that
have special meanings. Keywords are used to define the syntax of the
coding. The keyword cannot be used as an identifier, function, or variable
name. All the keywords in Python are written in lowercase except True and
False. There are 35 keywords in Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword()
function that can be used to check whether a given string is a valid keyword
or not. Furthermore, we can check the name of the keywords in Python by
using the kwlist attribute of the keyword module.

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


Keywords Description

This is a logical operator which returns true if both the operands


and
are true else returns false.
Keywords Description

This is also a logical operator which returns true if anyone operand


or
is true else returns false.

This is again a logical operator it returns True if the operand is


not
false else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif


elif
statement is executed if the previous conditions were not true.

Else is used with if and elif conditional statements. The else block
else
is executed if the given condition is not true.

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.


Keywords Description

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used to


assert
check the correctness of code

class It helps us to define a class.

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be


finally
executed no matter if there is an exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

It‟s used to check whether a value is present in a list, range, tuple,


in
etc.

is This is used to check if the two variables are equal or not.

This is a special constant used to denote a null value or avoid. It‟s


none important to remember, 0, any empty container(e.g empty list) do
not compute to None

nonlocal It‟s declared a non-local variable.


Keywords Description

raise This raises an exception.

yield It ends a function and returns a generator.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

The following code allows you to view the complete list of Python‟s
keywords.
This code imports the “keyword” module in Python and then prints a list of all
the keywords in Python using the “kwlist” attribute of the “keyword” module.
The “kwlist” attribute is a list of strings, where each string represents a
keyword in Python. By printing this list, we can see all the keywords that are
1

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module,
etc. The identifier is a combination of character digits and an underscore.
They are case-sensitive i.e., „num‟ and „Num‟ and „NUM‟ are three different
identifiers in python. It is a good programming practice to give meaningful
names to identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a
string is a valid identifier or not.

Rules for Naming Python Identifiers


 It cannot be a reserved python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).

Examples of Python Identifiers


Valid identifiers:
 var1
 _var1
 _1_var
 var_1
Invalid Identifiers
 !var1
 1var
 1_var
 var#1
 var 1

Python Variables
Last Updated : 25 Jan, 2025


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 many other programming languages, Python variables do not require explicit
declaration of type. The type of the variable is inferred based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our
program.

# Variable 'x' stores the integer value 10


2

x=5
3

# Variable 'name' stores the string "Samantha"


5

name = "Samantha"
6

print(x)
8

print(name)
Output
5
Samantha
In this article, we’ll explore the concept of variables in Python, including their syntax,
characteristics and common operations.

Rules for Naming Variables


To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores (_).
 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.

Python Comments
In the previous tutorial, you learned to write your first Python program. Now,
let's learn about Python comments..
Comments are hints that we add to our code to make it easier to understand.
Python comments start with # . For example,
# print a number
print(25)
Run Code

Here, # print a number is a comment.


Comments are completely ignored and not executed by code editors.

Single-line Comment
We use the hash ( # ) symbol to write a single-line comment. For example,
# declare a variable
name = "John"

# print name
print(name) # John
Run Code

In the above example, we have used three single-line comments:

 # declare a variable

 # print name

 # John

A single-line comment starts with # and extends up to the end of the line.
We can also use single-line comments alongside the code:

print(name) # John

Note: Remember the keyboard shortcut to apply comments. In most text


editors, it's Ctrl + / if you are on Windows & Cmd + / if you are on a Mac.

Multiline Comments
Unlike languages such as C++ and Java, Python doesn't have a dedicated
method to write multi-line comments.

However, we can achieve the same effect by using the hash ( # ) symbol at the
beginning of each line.
Let's look at an example.

# This is an example of a multiline comment


# created using multiple single-line commenced
# The code prints the text Hello World
print("Hello, World!")
Run Code

We can also use multiline strings as comments like:

'''This is an example
of multiline comment'''
print("Hello, World!")
Run Code

Output

Hello World

Python Data Types


Every value has a datatype, and variables can hold values. Python is a powerfully
composed language; consequently, we don't have to characterize the sort of variable while
announcing it. The interpreter binds the value implicitly to its type.

1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.

We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.

Consider the following illustration when defining and verifying the values of various data
types.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can contain a variety of values. On the other hand, a person's id must be stored
as an integer, while their name must be stored as a string.

The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

The data types will be briefly discussed in this tutorial section. We will talk about every
single one of them exhaustively later in this instructional exercise.

Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type. The instance () capability is utilized to check whether an
item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,

1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.

o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150,
and so on. An integer can be any length you want in Python. Its worth has a
place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and
y signify the genuine and non-existent parts separately. The complex numbers
like 2.14j, 2.0 + 2.3j, etc.

Sequence Type

String
The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes.

String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.

When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

The Python string is demonstrated in the following example.


Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:

string using double quotes


A multiline
string
Look at the following illustration of string handling.

Example - 2

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections
[].

To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).

Look at the following example.

Example:

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.

Let's look at a straightforward tuple in action.

Example:

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

Look at the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized
to decide the given assertion valid or misleading. The class book indicates this. False can
be represented by the 0 or the letter "F," while true can be represented by any value that is
not zero.

Look at the following example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)
Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It
might return the element's altered sequence. Either a sequence of elements is passed
through the curly braces and separated by a comma to create the set or the built-in function
set() is used to create the set. It can contain different kinds of values.

Look at the following example.

1. # Creating Empty set


2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Simple program to print welcome message

Ans Print(“welcome”)

You might also like