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

PYTHON-PROGRAMMING-topic-2

Uploaded by

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

PYTHON-PROGRAMMING-topic-2

Uploaded by

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

PYTHON

FUNDAMENTALS
PYTHON KEYWORDS & INDENTATION
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 reserved in
Python and cannot be
used as identifiers.
Python Keywords and Identifiers Examples
Example # 1
Using of ang, or, not, True, False Keywords
Example # 2
Using break, continue keywords and identifier
Example # 3
Using for, in, if, elif, else keywords
Example # 4
Using of def, if, and else keywords
Example # 5
Using of try, except, raise
Example # 6
Using of lambda keyword
Example # 7
Using of return keyword
Example # 8
Using of a del keyword
Example # 9
Using of global keyword
Example # 10
Using of yield keyword
Example # 11
Using of assert keyword
Example # 12
Using of generator keyword
Example # 13
Using of finally keyword
Example # 14
Using of import keyword
Example # 15
Using of is keyword
Example # 16
Using from keyword
Example # 17
Using async and await keyword
Python Indentation
 Indentation refers to the spaces at the beginning of a code
line. Where in other programming languages the indentation in
code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code.

 Python indentation refers to adding white space before a


statement to a particular block of code. In other words, all the
statements with the same space to the left, belong to the same
code block.
Comments
 Comments are hints that we add to our code to make it
easier to understand. Comments are completely ignored and
not executed by code editors.

Single-line Comment
We use the hash
(#) symbol to write a
single-line comment.
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.
We should use comments:
•For future references, as comments make our code readable.
•For debugging.
•For code collaboration, as comments help peer developers to
understand each other's code.

Comments are not and should not be used as a substitute to


explain poorly written code.
Always try to write clean, understandable code, and then use
comments as an addition.
In most cases, always use comments to explain 'why' rather than
'how' and you are good to go.
Python Basic Data Types
Python Numeric Data type
 In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall
under Python numbers category. They are defined
as int, float and complex classes in Python.
• int - holds signed integers of non-limited length.
• float - holds floating decimal points and it's accurate up
to 15 decimal places.
• complex - holds complex numbers.
 We can use the type() function to know which class a variable or a
value belongs to.
Python String Data Type

x = "string in a double quote"
y = 'string in a single quote'

print()
print("\t",x)
print("\t",y)

# using ',' to concate the two or several strings


print("\t",x,"concated with",y)

#using '+' to concate the two or several strings

print("\t",x+" concated with "+y)


print()
print("\t End of Program")
Python List Data Type
List is an ordered collection of similar or different types of items
separated by commas and enclosed within brackets [ ]
#list of having only integers
print()
x= [100,200,300,400,500,600]
print("\t",x)

#list of having only strings


y=[“Jennifer",“Andrea",“Michael",“Jorge"]
print("\t",y)

#list of having both integers and strings


z= ["hey","you",1,2,3,"go"]
print("\t",z)

print()
print("\t",y[0]) #this will print “Jennifer" in list y
print()
print("\t End of Program”)
Access List Items
Tuple is an ordered sequence of items same as
a list. The only difference is that tuples are
Python Tuple immutable. Tuples once created cannot be
Data Type modified.
In Python, we use the parentheses () to store
items of a tuple.
Python Set Data Type
Set is an unordered collection of unique items. Set is
defined by values separated by commas inside braces { }.
set1 = set(['a', 'b', 'c', 'c', 'd'])
set2 = set(['a', 'b', 'x', 'y', 'z'])

print()
print("\tset1: " , set1)
print("\tset2: " , set2)
print("\tintersection: ", set1 & set2)
print("\tunion: ", set1 | set2)
print("\tdifference: ", set1 - set2)
print("\tsymmetric difference: ", set1 ^ set2)
print()
print("\tEnd of Program")
Python Dictionary Data Type

VARIABLES
What is a Variable?
 A variable is simply a name the programmer uses to refer to the
computer storage locations.

 The term variables are used because the value stored in the variable
can change or vary.

 The computer keeps track of the actual memory address that


corresponds to each name the programmer assigns.
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:A variable name must start
with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )

• Variable names are case-sensitive (age, Age and AGE are three different variables)

• A variable name cannot be any of the Python keywords.


Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

Camel Case
Each word, except the first, starts with a capital
letter:
Snake Case
Each word is separated by
an underscore character:
Pascal Case
Each word starts with a capital letter:
Exercises:
 Which is NOT a legal variable name?
Many Values to Multiple Variables

 Python allows you to assign values to multiple variables in one line:


One Value to Multiple Variables
 You can assign the same value to multiple variables in one line:
Unpack a Collection

 If you have a collection of values in a list, tuple etc. Python allows you
to extract the values into variables. This is called unpacking.
What is a correct syntax to add the value 'Hello World',
to 3 values in one statement?
OUTPUT VARIABLES
The Python print() function is often used to output variables.

In the print() function, you output multiple variables, separated by a comma:


You can also use the + operator to output multiple variables:

Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".

For numbers, the + character works as a mathematical operator:


In the print() function, when you try to combine a string and a number
with the + operator, Python will give you an error:

The best way to output multiple variables in the print() function is to separate
them with commas, which even support different data types:
Consider the following code:
print('Hello', 'World')
What will be the printed result?
Global Variables
 Variables that are created outside of a function are known as global
variables.
 Global variables can be used by everyone, both inside of functions and
outside.

Create a variable outside of a function, and use it inside the function


If you use
the global keyword, the use the global keyword if you
variable belongs to the want to change a global variable
global scope: inside a function.
OPERATORS
What is an Operators?


Arithmetic Operators in Python


Example of Arithmetic
Operators in Python
Python Assignment Operators
List of different assignment operators available in Python.
Assignment
operators are used
to assign values to
variables.
Example 2: Assignment Operators
Python Comparison
Operators
Example 3:
Comparison Operators
Python Logical Operators
Logical operators are used to
check whether an expression
is True or False. They are used in
decision-making.
Example 4: Logical Operators
Python Bitwise operators

For
example, 2 is 10 in
binary,
and 7 is 111.

Let x = 10 (0000
1010 in binary)
and y = 4 (0000
0100 in binary)
Python Special Operators

Identity operators
❑ In Python, is and is not are used to check if two values are
located at the same memory location.
❑ It's important to note that having two variables with equal
values doesn't necessarily mean they are identical.
Example 4: Identity Operators in Python
Membership Operators
❑ In Python, in and not in are the membership operators.
❑ They are used to test whether a value or variable is found in
a sequence (string, list, tuple, set and dictionary).
❑ In a dictionary, we can only test for the presence of a key,
not the value.
Example 5: Membership Operators in Python
Problem No. 1
Write a program that will ask the user to input three numbers and then the
program will compute the sum of the three numbers and display the result
on the screen.
Problem No. 2
Write a program that will ask the user to input principal amount loan, the
number of years the loan to be paid and percentage interest per year. The
program will compute the yearly interest rate of the loan and display the
result on the screen.

You might also like