The document discusses Python programming concepts like variables, data types, operators, conditional statements and indentation. It explains that variables store and label data in memory, common data types like integers, floats and strings, basic arithmetic and assignment operators, if/else conditional statements and how Python uses indentation to group blocks of code. It also provides examples of type casting between different data types and prompts for writing Python programs to perform various comparisons and calculations.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
This document discusses Python programming concepts including data types, variables, operators, and functions. It provides examples of Python syntax for writing and executing code as well as built-in data types like strings, integers, and lists. Key concepts covered include variables, data type casting, comments, arithmetic and comparison operators, and functions.
- The document discusses Python programming concepts such as data types, variables, operators, and syntax. It provides examples of Python code for variables, comments, strings, numbers, and more.
- Python is a popular programming language used for web development, software development, mathematics, and more. It runs on different platforms and has a simple, readable syntax.
- Key features of Python include dynamic typing, automatic memory management, and an intuitive syntax that uses indentation rather than brackets.
The document discusses algorithms and problem solving using Python. It defines an algorithm as a step-by-step procedure to get a desired output. Characteristics of algorithms include being unambiguous, having well-defined inputs and outputs, and terminating after a finite number of steps. The document provides an example algorithm to add two numbers and displays the result. It also discusses flowcharts, keywords, identifiers, data types like integers and strings, and data structures in Python like lists and dictionaries.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
Python identifiers follow some basic rules:
1. They can include letters, numbers, and underscores.
2. They cannot start with a number.
3. Keywords like "if" cannot be used.
4. Identifiers are case-sensitive.
Of the given options, valid Python identifiers include: total1234, _abc_abc_, _p. Invalid ones include: 123total (can't start with number), java2share (contains special character), ca$h (contains special character), def (is a keyword).
Python is an interpreted, object-oriented, high-level programming language with dynamic typing and dynamic binding. Its simple, easy to learn syntax emphasizes readability and it uses significant indentation to delimit code blocks rather than curly braces or keywords. Python supports modules and packages, which encourages program modularity and code reuse. It also has a large standard library.
Asit Bangalore is providing best Programming course "C LANGUAGE" and helped them to take internship program which is helped to get real time exposure and placements in global world. For more details Please visit our website.
The document provides a recap of topics covered in Week 0 of a coding initiative for adults, including comments, variables, assignment, operators, statements, and expressions in Python. It defines each concept and provides examples. Comments are explained as a way to document code and "disable" sections. Variables are described as buckets that hold data. Various types of operators are listed and precedence is discussed. Statements are defined as executable instructions, while expressions are combinations of values and operations. Key points are brought together using an example that demonstrates comments, statements, variables, and expressions with assignment and operators.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
The document discusses Python programming language. It provides an overview of what Python is, what it can be used for, and why it is a popular language. Specifically, it notes that Python was created by Guido van Rossum and released in 1991. It is used for web development, software development, mathematics, and system scripting. The document then covers Python syntax, basic data types, operators, decision making and control flow statements like if/else and loops.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
This document provides an introduction to Python programming. It discusses that Python is an interpretive language and describes advantages like automatic memory management and disadvantages like slower speed compared to compiled languages. It also covers Python versions, the Anaconda IDE, variables and data types, operators, strings, lists, tuples, dictionaries, conditional statements, loops and functions like range(). Examples are provided throughout to demonstrate the core concepts of Python syntax and programming.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
Lec2_cont.pptx galgotias University questionsYashJain47002
This document discusses key concepts in Python including variables, data types, expressions, and statements. It covers defining variables and constants, using operators in expressions, and handling different data types. Comments are introduced as a way to document code. Examples demonstrate taking user input, performing calculations, and displaying output. Mnemonic variable names are recommended to improve readability.
Python is an open source programming language created by Guido van Rossum in 1991. It is named after the comedy group Monty Python and is based on the ABC language. Python supports both procedural and object-oriented programming and can be used for web development, data analysis, artificial intelligence, and more. It has a simple syntax and large standard library that make it easy to learn and use for various applications.
This document introduces an introductory Python programming class called ACM init(). It will meet once a week for several weeks and teach beginners Python programming with no prior experience required. It covers why learning computer science and Python is useful for careers and problem solving skills. It demonstrates running a simple Python program to calculate factorials and introduces some basic Python concepts like data types, variables, strings, math operators, and comments.
How to create and manage blogs in odoo 18Celine George
A blog serves as a space for sharing articles and information.
In Odoo 18, users can easily create and publish blogs through
the blog menu. This guide offers step-by-step instructions on
setting up and managing a blog on an Odoo 18 website.
Python is an interpreted, general-purpose, high-level programming language. It allows programmers to define functions for reusing code and scoping variables within functions. Key concepts covered include objects, expressions, conditionals, loops, modules, files, and recursion. Functions can call other functions, allowing for modular and reusable code.
Python identifiers follow some basic rules:
1. They can include letters, numbers, and underscores.
2. They cannot start with a number.
3. Keywords like "if" cannot be used.
4. Identifiers are case-sensitive.
Of the given options, valid Python identifiers include: total1234, _abc_abc_, _p. Invalid ones include: 123total (can't start with number), java2share (contains special character), ca$h (contains special character), def (is a keyword).
Python is an interpreted, object-oriented, high-level programming language with dynamic typing and dynamic binding. Its simple, easy to learn syntax emphasizes readability and it uses significant indentation to delimit code blocks rather than curly braces or keywords. Python supports modules and packages, which encourages program modularity and code reuse. It also has a large standard library.
Asit Bangalore is providing best Programming course "C LANGUAGE" and helped them to take internship program which is helped to get real time exposure and placements in global world. For more details Please visit our website.
The document provides a recap of topics covered in Week 0 of a coding initiative for adults, including comments, variables, assignment, operators, statements, and expressions in Python. It defines each concept and provides examples. Comments are explained as a way to document code and "disable" sections. Variables are described as buckets that hold data. Various types of operators are listed and precedence is discussed. Statements are defined as executable instructions, while expressions are combinations of values and operations. Key points are brought together using an example that demonstrates comments, statements, variables, and expressions with assignment and operators.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
The document discusses Python programming language. It provides an overview of what Python is, what it can be used for, and why it is a popular language. Specifically, it notes that Python was created by Guido van Rossum and released in 1991. It is used for web development, software development, mathematics, and system scripting. The document then covers Python syntax, basic data types, operators, decision making and control flow statements like if/else and loops.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
This document provides an introduction to Python programming. It discusses that Python is an interpretive language and describes advantages like automatic memory management and disadvantages like slower speed compared to compiled languages. It also covers Python versions, the Anaconda IDE, variables and data types, operators, strings, lists, tuples, dictionaries, conditional statements, loops and functions like range(). Examples are provided throughout to demonstrate the core concepts of Python syntax and programming.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
Lec2_cont.pptx galgotias University questionsYashJain47002
This document discusses key concepts in Python including variables, data types, expressions, and statements. It covers defining variables and constants, using operators in expressions, and handling different data types. Comments are introduced as a way to document code. Examples demonstrate taking user input, performing calculations, and displaying output. Mnemonic variable names are recommended to improve readability.
Python is an open source programming language created by Guido van Rossum in 1991. It is named after the comedy group Monty Python and is based on the ABC language. Python supports both procedural and object-oriented programming and can be used for web development, data analysis, artificial intelligence, and more. It has a simple syntax and large standard library that make it easy to learn and use for various applications.
This document introduces an introductory Python programming class called ACM init(). It will meet once a week for several weeks and teach beginners Python programming with no prior experience required. It covers why learning computer science and Python is useful for careers and problem solving skills. It demonstrates running a simple Python program to calculate factorials and introduces some basic Python concepts like data types, variables, strings, math operators, and comments.
How to create and manage blogs in odoo 18Celine George
A blog serves as a space for sharing articles and information.
In Odoo 18, users can easily create and publish blogs through
the blog menu. This guide offers step-by-step instructions on
setting up and managing a blog on an Odoo 18 website.
How to Configure Subcontracting in Odoo 18 ManufacturingCeline George
Subcontracting in manufacturing involves outsourcing specific production tasks to external vendors or subcontractors. These tasks may include manufacturing certain components, handling assembly processes, or even producing entire product lines.
How to Use Owl Slots in Odoo 17 - Odoo SlidesCeline George
In this slide, we will explore Owl Slots, a powerful feature of the Odoo 17 web framework that allows us to create reusable and customizable user interfaces. We will learn how to define slots in parent components, use them in child components, and leverage their capabilities to build dynamic and flexible UIs.
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Rajdeep Bavaliya
Dive into the haunting worlds of German Expressionism as we unravel how shadows and light elevate ‘The Cabinet of Dr. Caligari’ and ‘Nosferatu: A Symphony of Horror’ into timeless masterpieces. Discover the psychological power of chiaroscuro, distorted sets, and evocative silhouettes that shaped modern horror. Whether you’re a film buff or a budding cinephile, this journey through post‑WWI trauma and surreal visuals will leave you seeing movies in a whole new light. Hit play, share your favorite shock‑and‑awe moment in the comments, and don’t forget to follow for more deep‑dives into cinema’s most influential movements!
M.A. Sem - 2 | Presentation
Presentation Season - 2
Paper - 110A: History of English Literature – From 1900 to 2000
Submitted Date: April 1, 2025
Paper Name: History of English Literature – From 1900 to 2000
Topic: Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr. Caligari’ and ‘Nosferatu: A Symphony of Horror’
[Please copy the link and paste it into any web browser to access the content.]
Video Link: https://youtu.be/pWjHqo6clT4
For a more in-depth discussion of this presentation, please visit the full blog post at the following link:
Please visit this blog to explore additional presentations from this season:
Hashtags:
#GermanExpressionism #SilentHorror #Caligari #Nosferatu #Chiaroscuro #VisualStorytelling #FilmHistory #HorrorCinema #CinematicArt #ExpressionistAesthetics
Keyword Tags:
Expressionism, The Cabinet of Dr. Caligari, Nosferatu, silent film horror, film noir origins, German Expressionist cinema, chiaroscuro techniques, cinematic shadows, psychological horror, visual aesthetics
What are the Features & Functions of Odoo 18 SMS MarketingCeline George
A key approach to promoting a business's events, products, services, and special offers is through SMS marketing. With Odoo 18's SMS Marketing module, users can notify customers about flash sales, discounts, and limited-time offers.
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18Celine George
To create a new menu in the "My Accounts" portal and set up a list/form view in Odoo 18, follow these steps. For Example- The custom menu has now been added to the "Fleet" customer portal.
New syllabus entomology (Lession plan 121).pdfArshad Shaikh
*Fundamentals of Entomology*
Entomology is the scientific study of insects, including their behavior, ecology, evolution, classification, and management. Insects are the most diverse group of organisms on Earth, with over a million described species. Understanding entomology is crucial for managing insect pests, conserving beneficial insects, and appreciating their role in ecosystems.
*Key Concepts:*
- Insect morphology and anatomy
- Insect physiology and behavior
- Insect ecology and evolution
- Insect classification and identification
- Insect management and conservation
Entomology has numerous applications in agriculture, conservation, public health, and environmental science, making it a vital field of study.
CURRENT CASE COUNT: 880
• Texas: 729 (+5) (56% of cases are in Gaines County)
• New Mexico: 78 (+4) (83% of cases are from Lea County)
• Oklahoma: 17
• Kansas: 56 (38.89% of the cases are from Gray County)
HOSPITALIZATIONS: 103
• Texas: 94 - This accounts for 13% of all cases in the State.
• New Mexico: 7 – This accounts for 9.47% of all cases in New Mexico.
• Kansas: 2 - This accounts for 3.7% of all cases in Kansas.
DEATHS: 3
• Texas: 2 – This is 0.28% of all cases
• New Mexico: 1 – This is 1.35% of all cases
US NATIONAL CASE COUNT: 1,076 (confirmed and suspected)
INTERNATIONAL SPREAD
• Mexico: 1,753 (+198) 4 fatalities
‒ Chihuahua, Mexico: 1,657 (+167) cases, 3 fatalities, 9 hospitalizations
• Canada: 2518 (+239) (Includes Ontario’s outbreak, which began November 2024)
‒ Ontario, Canada: 1,795 (+173) 129 (+10) hospitalizations
‒ Alberta, Canada: 560 (+55)
Things to keep an eye on:
Mexico: Three children have died this month (all linked to the Chihuahua outbreak):
An 11-month-old and a 7-year-old with underlying conditions
A 1-year-old in Sonora whose family is from Chihuahua
Canada:
Ontario now reports more cases than the entire U.S.
Alberta’s case count continues to climb rapidly and is quickly closing in on 600 cases.
Emerging transmission chains in Manitoba and Saskatchewan underscore the need for vigilant monitoring of under-immunized communities and potential cross-provincial spread.
United States:
North Dakota: Grand Forks County has confirmed its first cases (2), linked to international travel. The state total is 21 since May 2 (including 4 in Cass County and 2 in Williams County), with one hospitalization reported.
OUTLOOK: With the spring–summer travel season peaking between Memorial Day and Labor Day, both domestic and international travel may fuel additional importations and spread. Although measles transmission is not strictly seasonal, crowded travel settings increase the risk for under-immunized individuals.
This article explores the miraculous event of the Splitting of the Moon (Shaqq al-Qamar) as recorded in Islamic scripture and tradition. Drawing from the Qur'an, authentic hadith collections, and classical tafsir, the article affirms the event as a literal miracle performed by Prophet Muhammad ﷺ in response to the Quraysh’s demand for a sign. It also investigates external historical accounts, particularly the legend of Cheraman Perumal, a South Indian king who allegedly witnessed the miracle and embraced Islam. The article critically examines the authenticity and impact of such regional traditions, while also discussing the lack of parallel astronomical records and how scholars have interpreted this event across centuries. Concluding with the theological significance of the miracle, the article offers a well-rounded view of one of Islam’s most discussed supernatural events.
Flower Identification Class-10 by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of rose prepared by:
Kushal Lamichhane
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
New-Beginnings-Cities-and-States.pdf/7th class social/4th chapterFor online c...Sandeep Swamy
New Beginnings: Cities and States This presentation explores the Second Urbanisation of India, examining the rise of janapadas and mah janapadas as crucial developments in India's early history. by sandeep swamy
The Second Urbanisation Urban Revival The emergence of new cities after the decline of the Indus Valley Civilization. Historical Timeline Occurred approximately between 600-200 BCE in the Gangetic plains. New Settlements Formation of organized urban centers with political and economic significance.
Janapadas: Early States Definition Territorial units with distinct cultural and political identities. Significance Formation Evolved from tribal settlements into more organized political entities. Marked the transition from nomadic to settled agricultural communities.
Magadha: The Powerful Kingdom Strategic Location Situated in modern-day Bihar with natural defenses of hills and rivers. Access to iron ore deposits gave military advantage. Capital Cities R jagr#iha (Rajgir) served as the initial capital. Later shifted to P t#aliputra (modern Patna). Ruins of a major structure at R jagr#iha, the early capital of Magadha.
4. How does it work?
• So our question was “ How does a Computer work? ”
• If we talk about latest computers;
• These machines(Hardware) work with Software.
• Who design and develop these Hardware and Software?
• Engineers!!!
• What does a software engineer do?
• Write programs!
5. What is a Program?
• In computer sicence,
a program is a
specific set of
“ordered operations”
for a computer to
perform.
• What is set of
“ordered operations”
6. Ordered Operations!
• To understand ordered
operation,
• Let’s talk about “How to
go out of this classroom?”
• What are the possible
ways?
8. Name:
• What’s your name?
• Name: James
• Code: 007
• Address: MI3
• What are these things?
• Do we need to use such things in programming language too?
• ?????
9. Variable!
• What is Variable?
• Variables are containers for storing data values.
• So In python we can write code=007
• Now again, What is variable?
• Can I write code=700?
• So now code is 007 or 700?, and why?
• Variable= “vary + able”
• Vary means “can change”
10. Variables:
• Can I write? Name = 007
• Code=James
• Are they same?
• Can I write a=10
• b=20
• C=a+b
• We will learn more about it in next class.
12. Try Python Programs:
• Let’s try declaring an Integer variable first.
• a=10
• b=5
• print(a+b)
• We can also do a+b directly, but it’s not same as print(a+b)
• We can also try 10+5 without using variables, python is very user friendly.
• By the way “ Do you have a Question What is Integer?”
• It is Data type, we will learn about it later.
13. Data Types in Python
• Text Type: str
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
14. Integer
• Python could deal with any size of Integer, including negative integer.
• The expressions in the program are exactly the same as those in mathematics,
for example: 1100, -8080, 0, and so on.
• Because computers use binary, it is sometimes convenient to use hexadecimal
to represent integers. Hexadecimal is represented by 0x prefix and 0-9, A-F,
such as 0xff00, 0xa5b4c3d2, etc.
• For large numbers, such as 100000000, it is difficult to count the number of
zeros. Python allows the middle of numbers to be_ Separate, therefore, write
10_ 000_ 000_ 000 and 1000000000 are exactly the same. Hexadecimal
numbers can also be written as 0xa1b2_ c3d4 。
15. Integer
• Try to type the following code in
your computer:
• a = 2
• b = 3
• a*b
• a**b
• a/b
• print(type(a/b))
• print(type(a))
▪ Try to type the following
code in your computer:
▪ x = 16
▪ y = - 16
▪ z = 0x10
▪ t = 1_6
▪ x + y
▪ x – y
▪ x – z
▪ t - x
16. Float
• Floating point numbers, that is, decimals, are called floating-point
numbers because when expressed in scientific notation, the decimal
point position of a floating-point number is variable. For example, 1.23x
and 12.3x are completely equal.
• Floating point numbers can be written mathematically, such as 1.23,
3.14, - 9.01, and so on. However, for large or small floating-point
numbers, they must be represented by scientific counting. Replace 10
with e, 1.23x is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc.
• Integer and floating-point numbers are stored in different ways in the
computer.
17. Float
• Try to type the following code in
your computer:
• a = 2.0
• b = 3.0
• a*b
• a**b
• a/b
• print(type(a/b))
• print(type(a))
▪ Try to type the following
code in your computer:
▪ x = 1.0
▪ y = -2.0
▪ x + y
▪ x – y
▪ z = x + y
▪ (Is there any output for the
expression above? Why?)
19. Python - Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, yourname, total_amount).
• 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)
20. Expressions
• Python Expressions are sequence of operands(objects) and operators.
• 3+5*8 #here 3,5,8 are operands and +, * are operators
• a,b = 10,20
• c = a + b
• d = a + b * c / a
• a = a + b + c
• f = f + a + b + c # are you getting an error?
• del a # deleting a variable
• a = a + b
21. Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• #This is a comment
print("Hello, World!")
• print("Hello, World!") #This is a comment
• #print("Hello, World!")
print("Cheers, NUIT!")
22. Python Numbers
• There are three numeric types in Python:
• int
• float
• complex
• Variables of numeric types are created when
you assign a value to them:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
• To verify the type of any
object in Python, use the
type() function:
• print(type(x))
• print(type(y))
• print(type(z))
23. Type Conversion
You can convert from one type to another with the int(), float(), and
complex() methods:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to
complex:
c = complex(x)
• print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
24. Bool
• Please run the following code:
• 3 > 2
• 2 > 3
• 1+3>2
• 0.001 >2
• True – True
• False + True
• 0==False
• type(True)
▪ Please run the following
code:
▪ a = 2 > 3
▪ print(a)
▪ b = 3 > 2
▪ print(b)
▪ c = True < False
▪ print(c)
▪ d = True – False
25. None
• Null value is a special value in Python, represented by None.
• None cannot be understood as 0. Because 0 is meaningful and None is a special
null value.
Please run the following code:
• print(None)
• a = None
• None – None
• None + True
• type(a)
27. Strings
• We already know what is string and what is use of it; Today we will try
more examples with strings.
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.
• ‘Neusoft' is the same as “Neusoft“
• Assign String to a Variable:
• Assigning a string to a variable is done with the variable name followed
by an equal sign and the string:
• a = “Neusoft"
print(a)
28. Strings are Arrays
• Get the character at position 1 (remember that the first character has the
position 0):
• What is I just want to print one letter from the given string?
• a = "Hello, World!"
print(a[1])
• The len() function returns the length of a string:
• print(len(a))
• To check if a certain phrase or character is present in a string, we can use
the keyword in.
• txt = "The Coffee in the Library is free!"
print("free" in txt)
▪ Try this one; print("Milk" not in txt)
29. Python - Slicing Strings
• What if I want to print ello from the above given string?
• You can return a range of characters by using the slice
syntax.
• Specify the start index and the end index, separated by a
colon, to return a part of the string.
• b = "Hello, World!"
print(b[1:5])
• Note: The first character has index 0.
30. ▪ Slice From the Start
▪ b = "Hello, World!"
print(b[:5])
▪ Slice To the End
▪ print(b[2:])
▪ Negative Indexing
▪ Get the characters:
▪ From: "o" in "World!" (position -5)
▪ To, but not included: "d" in "World!" (position -2)
▪ b = "Hello, World!"
print(b[-5:-2])
31. ▪ String[start : end : step]
▪ nums = “0123456789"
print(nums[0:10:1])
▪ print(nums[0:10:2])
▪ String[ start : end : step]
▪ String slicing can accept a third parameter in addition to
two index numbers. The third parameter specifies
the stride, which refers to how many characters to move
forward after the first character is retrieved from the
string.
32. Python - Escape Characters
• Can we use?:
txt = "We are the Students of
"Neusoft" from China. "
• To fix this problem, use the escape
character ":
r ":
Code Result
' Single Quote
Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed
ooo Octal value
xhh Hex value
34. ▪ Python Arithmetic Operators
▪ Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
35. ▪ Python Assignment Operators
▪ Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
36. ▪ Python Assignment Operators
▪ Assignment operators are used to assign values to variables:
▪ We will try some of them.
Operator Example Same As
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
37. ▪ Python Comparison Operators
▪ Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
38. ▪ Python Logical Operators
▪ Logical operators are used to combine conditional statements
Operator Description Example
and Returns True if both
statements are true
x < 5 and x < 10
or Returns True if one of the
statements is true
x < 5 or x < 4
not Reverse the result, returns
False if the result is true
not(x < 5 and x < 10)
39. ▪ Python Identity Operators
▪ Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same
memory location:
Operator Description Example
is Returns True if both
variables are the same
object
x is y
is not Returns True if both
variables are not the
same object
x is not y
40. ▪ Python Bitwise Operators
▪ Bitwise operators are used to compare (binary) numbers:
▪ We will not practice Examples of bitwise operators.
Operat
or
Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill
left shift
Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> Signed
right shift
Shift right by pushing copies of the leftmost bit in from
the left, and let the rightmost bits fall off
42. Branching programs
• Do you remember the problem of opening a
door?
• The simplest branching statement is a
conditional.
• A test(expression that evaluates to True or
False)
• A block of code to execute if the test is True
• An optional block of code to execute if the test
is False
Code
True
Block
False
Block
Test
Code
43. Python Conditions and If
statements
• Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
44. Example:
• An "if statement" is written by using the if keyword.
• Example: If statement:
• a = 33
b = 200
if b > a:
print ("b is greater than a")
45. Indentation
• Python relies on indentation (whitespace at the beginning of a line) to
define scope in the code. Each indented set of expressions
denotes a block of instructions.
• Other programming languages often use curly-brackets for this purpose.
• Example: If statement, without indentation (will raise an error):
• a = 33
b = 200
if b > a:
print ("b is greater than a") # you will get an error
Indent
expected
!!
46. Python User Input
• Python allows for user input.
• That means we are able to ask the user for input.
• name = input("Enter your name:")
print(“Your name is: " + name)
• Can you write a program to calculate a+b using input?
• a=input(“Enter value of a:”)
• b=input(“Enter value of b:”)
• print(“The sum of a+b is:”, a+b) #Does this work?
47. If - else
• Question time: Given the following code, which part of it
is the True block? Which part of it is the False block?
Code
True
Block
False
Block
Test
Code
a = int(input(“Enter first number:”))
b = int(input(“Enter second number:”))
if a>b:
print("The bigger number: ”, a )
else:
print("The bigger number: ”, b )
print('Done with conditional')
48. Example of Branching programs (elif)
• The elif keyword is python way of saying "if the
previous conditions were not true, then try this
condition".
a = int(input(“Enter first
number:”))
b = int(input(“Enter second
number:”))
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("b is smaller than a")
49. The pass Statement
• if statements cannot be empty, but if you for some
reason have an if statement with no content, put in
the pass statement to avoid getting an error.
• a = 33
b = 200
if b > a:
pass
51. Iteration
• Concept of iteration let us extend
simple branching algorithms to
be able to write programs of
arbitrary complexity
• Strat with a test
• If evaluates to True , then
execute loop body once, and
go back to reevaluate the test.
• Repeat until the test is False,
after which code following
iteration statement is
executed.
Code
Loop body
Test
Code
True
False
52. An example of while loop
x = int(input("Please input an integer:
"))
ans = 0
iterLeft = x
while iterLeft != 0:
ans = ans + x
iterLeft = iterLeft - 1
print(str(x) + '*' + str(x) + '=' +
str(ans))
This program square the value of x by
addition.
53. Python For Loops
• A for loop is used for iterating over a sequence.
•Looping Through a String
• Even strings are iterable objects, they contain a
sequence of characters
• Example:
• for x in "Neusoft":
print(x)
54. The range() Function
• To loop through a set of code a specified number of
times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
• Example:
• for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
55. The break Statement
• With the break statement we can
stop the loop before it has looped
through all the items:
• Exit the loop when x is "banana":
• fruits =
["apple", "banana", "cherry"
]
for x in fruits:
print(x)
if x == "banana":
break
• Exit the loop when x is "banana",
but this time the break comes
before the print:
• fruits =
["apple", "banana", "cherry
"]
for x in fruits:
if x == "banana":
break
print(x)
56. The continue Statement
• With the continue statement we can stop the current iteration of the
loop, and continue with the next:
• Example:
• Do not print banana:
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
57. Else in For Loop
• The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:
• Print all numbers from 0 to 5, and print a message
when the loop has ended:
• for x in range(6):
print(x)
else:
print(“For Loop finished!")
• Note: The else block will NOT be executed if the loop is
stopped by a break statement.
59. Python Lists
• Ordered
• When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
• If you add new items to a list, the new items will be placed at the end of the list.
• Changeable
• The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.
• Allow Duplicates
• Since lists are indexed, lists can have items with the same value:
60. Allow Duplicates
• Example:
• Lists allow duplicate values:
• list1 = ["apple", "banana", "cherry", "apple", "cherry"]
print(list1)
• List Length
• To determine how many items a list has, use the len() function:
• list1 = ["apple", "banana", "cherry"]
print(len(list1))
61. List Items - Data Types
• List items can be of any data type:
• Example:
• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• A list can contain different data types:
• list1 = ["abc", 34, True, 40, "male"]
• Check type:
• print(type(list1))
63. Tuple Items
• Tuple items are ordered, unchangeable, and allow duplicate
values.
• Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
• Ordered: When we say that tuples are ordered, it means
that the items have a defined order, and that order will not
change.
• Unchangeable: Tuples are unchangeable, meaning that we
cannot change, add or remove items after the tuple has been
created.
• Allow Duplicates: Since tuples are indexed, they can have
items with the same value:
64. Create Tuple With One Item
• To create a tuple with only one item, you have to
add a comma after the item, otherwise Python will
not recognize it as a tuple.
• tuple1 = ("apple",)
print(type(tuple1))
#NOT a tuple
tuple2 = ("apple")
print(type(tuple2))
65. Tuple Items - Data Types
• Tuple items can be of any data type:
• tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
• A tuple can contain different data types:
• tuple1 = ("abc", 34, True, 40, "male")
• The tuple() Constructor
• tuple3 = tuple(("apple", "banana", "cherry")) #
note the double round-brackets
print(tuple3)
67. Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• In Python a function is defined using the def keyword:
• def my_function():
print("Hello from a function")
68. Why use Python functions?
• Functions provide a way to compartmentalize your code into small tasks
that can be called from multiple places within a program
• This is especially useful if the code in question will be used several times in
different parts of your program.
• You can think of functions as mini-programs within your bigger program
that implement specific tasks.
• If you have a block of code that gets called more than once, put it in a
function.
• Functions may take optional inputs to work with and may optionally return
a value or values.
69. User-defined function
• As the name suggests, these are functions that are written by the user, to
aid them in achieving a specific goal.
• The main use of functions is to help us organize our programs into
logical fragments that work together to solve a specific part of our
problem.
• General structure of Python function (Syntax)
• The structure of a function is very simple but very important.
def {FunctionName}[(parameters)]: # Function
Header Indented code..... # Code begins here
return
70. Syntax:
• Use the def keyword, followed by the function name.
• The function name must follow the same naming rules for variables (Single
word, No spaces, must start with either a letter or an underscore, etc).
• Add parameters (if any) to the function within the parentheses. End the
function definition with a full colon.
• Write the logic of the function. All code for the function must be indented.
• Finally, use the return keyword to return the output of the function. This is
optional, and if it is not included, the function automatically returns None.
def {FunctionName}[(parameters)]: # Function
Header Indented code..... # Code begins here
return
72. Python Classes/Objects
• Everything in Python is an object and has a type
• Objects are a data abstraction that capture:
• Internal representation through data attributes
• Interface for interacting with object through methods(procedures), defines
behaviors but hides implementation
• Can create new instances of objects
• Can destroy objects
• Explicitly using del or just forget about them
• Python system will reclaim destroyed or inaccessible objects – called ‘garbage
collection’
73. Create a Class
• To create a class, use the keyword class:
• We can say a class is a user defined data type.
• And class can have
• Attributes = variables
• Behavior = Methods(Functions)
class Coordinate(object):
"""
define attributes here.
"""
74. Create a Class
• Similar to def, it needs indentation to indicate which statements are part of the
class definition
• The word object means that Coordinate is a Python object and inherits all its
attributes (Recommend to inherit object)
• Coordinate is a subclass of object
• Object is a superclass of Coordinate.
class Coordinate(object):
"""
define attributes here.
"""
75. What are attributes?
• The data and procedures that “belong” to the class
• Data attributes
• Think of the data as other objects that make up the class
• For example, a coordinate is made up of two numbers
• Procedure attributes(methods or functions)
• Methods that only work with this class
• For example, define a distance between two coordinate instances.
class Coordinate(object):
"""
define attributes here.
"""
76. Creating a class
• First have to define how to create an instance of object
• Use a special method called __init__() to initialize some data attributes
• In python when something starts with “__” it means it’s special
• But the __init__() is being called by default(automatically) in python.
• Self is the parameter which refer to the instance of the class.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
77. Creating a class
• About the x, y(data attribute)
• When we invokes the creation of an instance, this will bind the variables x and
y within that instance to the supplied values.
• For every instance of Coordinate, it will have two data attribute, x and y.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
79. Main Concepts of Object-Oriented
Programming (OOPs)
•Class
•Objects
•Inheritance
•Polymorphism
•Encapsulation
80. Structured Programming & 3 characteristic of
OOP
•Structured Programming:
•Structured programming adopts the top-down and
gradual refinement design method. Each module is
connected through the control structure of
"sequence, iteration, branching structure and
loop", and there is only one entrance and one exit
81. Structured Programming & 3 characteristic of
OOP
• 3 characteristic of OOP :
• Encapsulation(1 mark): that is to encapsulate objective things into abstract
classes, and classes can only allow trusted classes or objects to operate their
own data and methods, and hide information from untrusted ones.(3 marks)
• Inheritance(1 mark): refers to the ability to use all the functions of existing
classes and extend them without rewriting the original classes. (3 marks)
• Polymorphism(1 mark) is a technology that allows you to set the parent object
equal to one or more of its child objects. After assignment, the parent object
can operate in different ways according to the characteristics of the child
object currently assigned to it. (3 marks)
#42: We are going to learn how to make a decision based on test.
Branching programs allow us to make different choices and do different things. But still. The program get executed once.
#72: For now, we know we have a general idea of what is object. To make this more concrete, Let’s take an example of a built-in data type.