SlideShare a Scribd company logo
1 of 38
15-110: Principles of
Computing
Basic Elements of Python Programs
Lecture 2, September 04, 2018
Mohammad Hammoud
Carnegie Mellon University in Qatar
Today…
• Last Session:
• Motivation
• Introduction to Hardware Basics & Programming Languages
• Writing Simple Python Commands
• Today’s Session:
• Basic Elements of Python Programs: Literals, Assignments, Datatype Conversion,
Identifiers, and Expressions
• Announcement:
• We will practice on the Python basic elements on Thursday, September 06, 2018
during the recitation
• In the following example, the parameter values passed to the print
function are all technically called literals
• More precisely, “Hello” and “Programming is fun!” are called textual literals,
while 3 and 2.3 are called numeric literals
>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3
Literals
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements
 x is a variable and 2 is its value
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements
 x is a variable and 2 is its value
 x can be assigned different values;
hence, it is called a variable
• A simple way to view the effect of an assignment is to assume that
when a variable changes, its old value is replaced
>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements: Box View
2
Before
x = 2.3
2.3
After
x x
• Python assignment statements are actually slightly different from the
“variable as a box” model
• In Python, values may end up anywhere in memory, and variables are used to
refer to them
>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements: Actual View
2
Before
x = 2.3
2
After
x x
2.3
What will
happen to
value 2?
• Interestingly, as a Python programmer you do not have to worry about
computer memory getting filled up with old values when new values
are assigned to variables
• Python will automatically clear old
values out of memory in a process
known as garbage collection
Garbage Collection
2
After
x
2.3
X
Memory location
will be automatically
reclaimed by the
garbage collector
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?
• In Python, input is accomplished via an assignment statement
combined with a built-in function called input
• When Python encounters a call to input, it prints <prompt> (which is a
string literal) then pauses and waits for the user to type some text and
press the <Enter> key
Assigning Input
<variable> = input(<prompt>)
• Here is a sample interaction with the Python interpreter:
• Notice that whatever the user types is then stored as a string
• What happens if the user inputs a number?
Assigning Input
>>> name = input("Enter your name: ")
Enter your name: Mohammad Hammoud
>>> name
'Mohammad Hammoud'
>>>
• Here is a sample interaction with the Python interpreter:
• How can we force an input number to be stored as a number and not as
a string?
• We can use the built-in eval function, which can be “wrapped around” the
input function
Assigning Input
>>> number = input("Enter a number: ")
Enter a number: 3
>>> number
'3'
>>>
Still a string!
• Here is a sample interaction with the Python interpreter:
Assigning Input
>>> number = eval(input("Enter a
number: "))
Enter a number: 3
>>> number
3
>>>
Now an int
(no single quotes)!
• Here is a sample interaction with the Python interpreter:
Assigning Input
>>> number = eval(input("Enter a
number: "))
Enter a number: 3.7
>>> number
3.7
>>>
And now a float
(no single quotes)!
• Here is another sample interaction with the Python interpreter:
Assigning Input
>>> number = eval(input("Enter an equation: "))
Enter an equation: 3 + 2
>>> number
5
>>>
The eval function will evaluate this formula and
return a value, which is then assigned to the variable “number”
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
Datatype Conversion
>>> number = int(input("Enter a number: "))
Enter a number: 3
>>> number
3
>>>
An integer
(no single quotes)!
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
Datatype Conversion
>>> number = float(input("Enter a number: "))
Enter a number: 3.7
>>> number
3.7
>>>
A float
(no single quotes)!
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str functions
Datatype Conversion
>>> x = 10
>>> float(x)
10.0
>>> str(x)
'10'
>>>
>>> y = "20"
>>> float(y)
20.0
>>> int(y)
20
>>>
>>> z = 30.0
>>> int(z)
30
>>> str(z)
'30.0'
>>>
integer  float
integer  string
string  float
string  integer
float  integer
float  string
• Python allows us also to assign multiple values to multiple variables all
at the same time
• This form of assignment might seem strange at first, but it can prove
remarkably useful (e.g., for swapping values)
Simultaneous Assignment
>>> x, y = 2, 3
>>> x
2
>>> y
3
>>>
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
Simultaneous Assignment
>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x
3
>>> y
3
X CANNOT be done with
two simple assignments
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
Simultaneous Assignment
>>> x = 2
>>> y = 3
>>> temp = x
>>> x = y
>>> y = temp
>>> x
3
>>> y
2
>>>

CAN be done with
three simple assignments,
but more efficiently with
simultaneous assignment
Thus far, we have been using
different names for
variables. These names
are technically called
identifiers
• Python has some rules about how identifiers can be formed
• Every identifier must begin with a letter or underscore, which may be
followed by any sequence of letters, digits, or underscores
>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid syntax
Identifiers
• Python has some rules about how identifiers can be formed
• Identifiers are case-sensitive
>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
Identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
Identifiers
>>> for = 4
File "<stdin>", line 1
for = 4
^
SyntaxError: invalid syntax
An example…
• You can produce new data (numeric or text) values in your program
using expressions
Expressions
>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
 This is an expression that uses the
addition operator
• You can produce new data (numeric or text) values in your program
using expressions
Expressions
>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
 This is an expression that uses the
addition operator
 This is another expression that uses the
multiplication operator
• You can produce new data (numeric or text) values in your program
using expressions
Expressions
>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
 This is an expression that uses the
addition operator
 This is another expression that uses the
multiplication operator
 This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together
• You can produce new data (numeric or text) values in your program
using expressions
Expressions
>>> x = 6
>>> y = 2
>>> print(x - y)
4
>>> print(x/y)
3.0
>>> print(x//y)
3
>>> print(x*y)
12
>>> print(x**y)
36
>>> print(x%y)
0
>>> print(abs(-x))
6
Yet another
example…
Another
example…
Expressions: Summary of Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponentiation
abs() Absolute Value
// Integer Division
% Remainder
Python Built-In Numeric Operations
• Data conversion can happen in two ways in Python
1. Explicit Data Conversion (we saw this earlier with the int, float, and str
built-in functions)
2. Implicit Data Conversion
• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since
string is not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an
integer) and not vice versa so as the fractional part of the float is not lost
Explicit and Implicit Data Type Conversion
Implicit Data Type Conversion: Examples
>>> print(2 + 3.4)
5.4
>>> print( 2 + 3)
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
 The result of an expression that involves
a float number alongside (an) integer
number(s) is a float number
Implicit Data Type Conversion: Examples
>>> print(2 + 3.4)
5.4
>>> print( 2 + 3)
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
 The result of an expression that involves
a float number alongside (an) integer
number(s) is a float number
 The result of an expression that involves
values of the same data type will not result
in any conversion
• One problem with entering code interactively into a Python shell is
that the definitions are lost when we quit the shell
• If we want to use these definitions again, we have to type them all over again!
• To this end, programs are usually created by typing definitions into a
separate file called a module or script
• This file is saved on disk so that it can be used over and over again
• A Python module file is just a text file with a .py extension, which can
be created using any program for editing text (e.g., notepad or vim)
Modules
• A special type of software known as a programming environment
simplifies the process of creating modules/programs
• A programming environment helps programmers write programs and
includes features such as automatic indenting, color highlighting, and
interactive development
• The standard Python distribution includes a programming
environment called IDLE that you can use for working on the
programs of this course
Programming Environments and IDLE
• Programs are composed of statements that are built from identifiers and
expressions
• Identifiers are names
• They begin with an underscore or letter which can be followed by a combination
of letter, digit, and/or underscore characters
• They are case sensitive
• Expressions are the fragments of a program that produce data
• They can be composed of literals, variables, and operators
Summary
• A literal is a representation of a specific value (e.g., 3 is a literal
representing the number three)
• A variable is an identifier that stores a value, which can change (hence,
the name variable)
• Operators are used to form and combine expressions into more complex
expressions (e.g., the expression x + 3 * y combines two expressions
together using the + and * operators)
Summary
• In Python, assignment of a value to a variable is done using the equal
sign (i.e., =)
• Using assignments, programs can get inputs from users and manipulate
them internally
• Python allows simultaneous assignments, which are useful for swapping
values of variables
• Datatype conversion involves converting implicitly and explicitly between
various datatypes, including integer, float, and string
Summary
• Functions- Part I
Next Lecture…

More Related Content

Similar to Lecture-2-Python-Basic-Elements-Sep04-2018.pptx

An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Basics of Python Programming
Basics of Python ProgrammingBasics of Python Programming
Basics of Python ProgrammingManishJha237
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptxAnum Zehra
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python programming
Python programmingPython programming
Python programmingsaroja20
 

Similar to Lecture-2-Python-Basic-Elements-Sep04-2018.pptx (20)

An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Basics of Python Programming
Basics of Python ProgrammingBasics of Python Programming
Basics of Python Programming
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptx
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
PYTHON
PYTHONPYTHON
PYTHON
 
Python programming
Python programmingPython programming
Python programming
 
Python unit 1 part-2
Python unit 1 part-2Python unit 1 part-2
Python unit 1 part-2
 

Recently uploaded

FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiSuhani Kapoor
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 

Recently uploaded (20)

FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service AmravatiVIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
VIP Call Girls in Amravati Aarohi 8250192130 Independent Escort Service Amravati
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 

Lecture-2-Python-Basic-Elements-Sep04-2018.pptx

  • 1. 15-110: Principles of Computing Basic Elements of Python Programs Lecture 2, September 04, 2018 Mohammad Hammoud Carnegie Mellon University in Qatar
  • 2. Today… • Last Session: • Motivation • Introduction to Hardware Basics & Programming Languages • Writing Simple Python Commands • Today’s Session: • Basic Elements of Python Programs: Literals, Assignments, Datatype Conversion, Identifiers, and Expressions • Announcement: • We will practice on the Python basic elements on Thursday, September 06, 2018 during the recitation
  • 3. • In the following example, the parameter values passed to the print function are all technically called literals • More precisely, “Hello” and “Programming is fun!” are called textual literals, while 3 and 2.3 are called numeric literals >>> print("Hello") Hello >>> print("Programming is fun!") Programming is fun! >>> print(3) 3 >>> print(2.3) 2.3 Literals
  • 4. • A literal is used to indicate a specific value, which can be assigned to a variable >>> x = 2 >>> print(x) 2 >>> x = 2.3 >>> print(x) 2.3 Simple Assignment Statements  x is a variable and 2 is its value
  • 5. • A literal is used to indicate a specific value, which can be assigned to a variable >>> x = 2 >>> print(x) 2 >>> x = 2.3 >>> print(x) 2.3 Simple Assignment Statements  x is a variable and 2 is its value  x can be assigned different values; hence, it is called a variable
  • 6. • A simple way to view the effect of an assignment is to assume that when a variable changes, its old value is replaced >>> x = 2 >>> print(x) 2 >>> x = 2.3 >>> print(x) 2.3 Simple Assignment Statements: Box View 2 Before x = 2.3 2.3 After x x
  • 7. • Python assignment statements are actually slightly different from the “variable as a box” model • In Python, values may end up anywhere in memory, and variables are used to refer to them >>> x = 2 >>> print(x) 2 >>> x = 2.3 >>> print(x) 2.3 Simple Assignment Statements: Actual View 2 Before x = 2.3 2 After x x 2.3 What will happen to value 2?
  • 8. • Interestingly, as a Python programmer you do not have to worry about computer memory getting filled up with old values when new values are assigned to variables • Python will automatically clear old values out of memory in a process known as garbage collection Garbage Collection 2 After x 2.3 X Memory location will be automatically reclaimed by the garbage collector
  • 9. • So far, we have been using values specified by programmers and printed or assigned to variables • How can we let users (not programmers) input values? • In Python, input is accomplished via an assignment statement combined with a built-in function called input • When Python encounters a call to input, it prints <prompt> (which is a string literal) then pauses and waits for the user to type some text and press the <Enter> key Assigning Input <variable> = input(<prompt>)
  • 10. • Here is a sample interaction with the Python interpreter: • Notice that whatever the user types is then stored as a string • What happens if the user inputs a number? Assigning Input >>> name = input("Enter your name: ") Enter your name: Mohammad Hammoud >>> name 'Mohammad Hammoud' >>>
  • 11. • Here is a sample interaction with the Python interpreter: • How can we force an input number to be stored as a number and not as a string? • We can use the built-in eval function, which can be “wrapped around” the input function Assigning Input >>> number = input("Enter a number: ") Enter a number: 3 >>> number '3' >>> Still a string!
  • 12. • Here is a sample interaction with the Python interpreter: Assigning Input >>> number = eval(input("Enter a number: ")) Enter a number: 3 >>> number 3 >>> Now an int (no single quotes)!
  • 13. • Here is a sample interaction with the Python interpreter: Assigning Input >>> number = eval(input("Enter a number: ")) Enter a number: 3.7 >>> number 3.7 >>> And now a float (no single quotes)!
  • 14. • Here is another sample interaction with the Python interpreter: Assigning Input >>> number = eval(input("Enter an equation: ")) Enter an equation: 3 + 2 >>> number 5 >>> The eval function will evaluate this formula and return a value, which is then assigned to the variable “number”
  • 15. • Besides, we can convert the string output of the input function into an integer or a float using the built-in int and float functions Datatype Conversion >>> number = int(input("Enter a number: ")) Enter a number: 3 >>> number 3 >>> An integer (no single quotes)!
  • 16. • Besides, we can convert the string output of the input function into an integer or a float using the built-in int and float functions Datatype Conversion >>> number = float(input("Enter a number: ")) Enter a number: 3.7 >>> number 3.7 >>> A float (no single quotes)!
  • 17. • As a matter of fact, we can do various kinds of conversions between strings, integers and floats using the built-in int, float, and str functions Datatype Conversion >>> x = 10 >>> float(x) 10.0 >>> str(x) '10' >>> >>> y = "20" >>> float(y) 20.0 >>> int(y) 20 >>> >>> z = 30.0 >>> int(z) 30 >>> str(z) '30.0' >>> integer  float integer  string string  float string  integer float  integer float  string
  • 18. • Python allows us also to assign multiple values to multiple variables all at the same time • This form of assignment might seem strange at first, but it can prove remarkably useful (e.g., for swapping values) Simultaneous Assignment >>> x, y = 2, 3 >>> x 2 >>> y 3 >>>
  • 19. • Suppose you have two variables x and y, and you want to swap their values (i.e., you want the value stored in x to be in y and vice versa) Simultaneous Assignment >>> x = 2 >>> y = 3 >>> x = y >>> y = x >>> x 3 >>> y 3 X CANNOT be done with two simple assignments
  • 20. • Suppose you have two variables x and y, and you want to swap their values (i.e., you want the value stored in x to be in y and vice versa) Simultaneous Assignment >>> x = 2 >>> y = 3 >>> temp = x >>> x = y >>> y = temp >>> x 3 >>> y 2 >>>  CAN be done with three simple assignments, but more efficiently with simultaneous assignment Thus far, we have been using different names for variables. These names are technically called identifiers
  • 21. • Python has some rules about how identifiers can be formed • Every identifier must begin with a letter or underscore, which may be followed by any sequence of letters, digits, or underscores >>> x1 = 10 >>> x2 = 20 >>> y_effect = 1.5 >>> celsius = 32 >>> 2celsius File "<stdin>", line 1 2celsius ^ SyntaxError: invalid syntax Identifiers
  • 22. • Python has some rules about how identifiers can be formed • Identifiers are case-sensitive >>> x = 10 >>> X = 5.7 >>> print(x) 10 >>> print(X) 5.7 Identifiers
  • 23. • Python has some rules about how identifiers can be formed • Some identifiers are part of Python itself (they are called reserved words or keywords) and cannot be used by programmers as ordinary identifiers Identifiers False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise Python Keywords
  • 24. • Python has some rules about how identifiers can be formed • Some identifiers are part of Python itself (they are called reserved words or keywords) and cannot be used by programmers as ordinary identifiers Identifiers >>> for = 4 File "<stdin>", line 1 for = 4 ^ SyntaxError: invalid syntax An example…
  • 25. • You can produce new data (numeric or text) values in your program using expressions Expressions >>> x = 2 + 3 >>> print(x) 5 >>> print(5 * 7) 35 >>> print("5" + "7") 57  This is an expression that uses the addition operator
  • 26. • You can produce new data (numeric or text) values in your program using expressions Expressions >>> x = 2 + 3 >>> print(x) 5 >>> print(5 * 7) 35 >>> print("5" + "7") 57  This is an expression that uses the addition operator  This is another expression that uses the multiplication operator
  • 27. • You can produce new data (numeric or text) values in your program using expressions Expressions >>> x = 2 + 3 >>> print(x) 5 >>> print(5 * 7) 35 >>> print("5" + "7") 57  This is an expression that uses the addition operator  This is another expression that uses the multiplication operator  This is yet another expression that uses the addition operator but to concatenate (or glue) strings together
  • 28. • You can produce new data (numeric or text) values in your program using expressions Expressions >>> x = 6 >>> y = 2 >>> print(x - y) 4 >>> print(x/y) 3.0 >>> print(x//y) 3 >>> print(x*y) 12 >>> print(x**y) 36 >>> print(x%y) 0 >>> print(abs(-x)) 6 Yet another example… Another example…
  • 29. Expressions: Summary of Operators Operator Operation + Addition - Subtraction * Multiplication / Float Division ** Exponentiation abs() Absolute Value // Integer Division % Remainder Python Built-In Numeric Operations
  • 30. • Data conversion can happen in two ways in Python 1. Explicit Data Conversion (we saw this earlier with the int, float, and str built-in functions) 2. Implicit Data Conversion • Takes place automatically during run time between ONLY numeric values • E.g., Adding a float and an integer will automatically result in a float value • E.g., Adding a string and an integer (or a float) will result in an error since string is not numeric • Applies type promotion to avoid loss of information • Conversion goes from integer to float (e.g., upon adding a float and an integer) and not vice versa so as the fractional part of the float is not lost Explicit and Implicit Data Type Conversion
  • 31. Implicit Data Type Conversion: Examples >>> print(2 + 3.4) 5.4 >>> print( 2 + 3) 5 >>> print(9/5 * 27 + 32) 80.6 >>> print(9//5 * 27 + 32) 59 >>> print(5.9 + 4.2) 10.100000000000001 >>>  The result of an expression that involves a float number alongside (an) integer number(s) is a float number
  • 32. Implicit Data Type Conversion: Examples >>> print(2 + 3.4) 5.4 >>> print( 2 + 3) 5 >>> print(9/5 * 27 + 32) 80.6 >>> print(9//5 * 27 + 32) 59 >>> print(5.9 + 4.2) 10.100000000000001 >>>  The result of an expression that involves a float number alongside (an) integer number(s) is a float number  The result of an expression that involves values of the same data type will not result in any conversion
  • 33. • One problem with entering code interactively into a Python shell is that the definitions are lost when we quit the shell • If we want to use these definitions again, we have to type them all over again! • To this end, programs are usually created by typing definitions into a separate file called a module or script • This file is saved on disk so that it can be used over and over again • A Python module file is just a text file with a .py extension, which can be created using any program for editing text (e.g., notepad or vim) Modules
  • 34. • A special type of software known as a programming environment simplifies the process of creating modules/programs • A programming environment helps programmers write programs and includes features such as automatic indenting, color highlighting, and interactive development • The standard Python distribution includes a programming environment called IDLE that you can use for working on the programs of this course Programming Environments and IDLE
  • 35. • Programs are composed of statements that are built from identifiers and expressions • Identifiers are names • They begin with an underscore or letter which can be followed by a combination of letter, digit, and/or underscore characters • They are case sensitive • Expressions are the fragments of a program that produce data • They can be composed of literals, variables, and operators Summary
  • 36. • A literal is a representation of a specific value (e.g., 3 is a literal representing the number three) • A variable is an identifier that stores a value, which can change (hence, the name variable) • Operators are used to form and combine expressions into more complex expressions (e.g., the expression x + 3 * y combines two expressions together using the + and * operators) Summary
  • 37. • In Python, assignment of a value to a variable is done using the equal sign (i.e., =) • Using assignments, programs can get inputs from users and manipulate them internally • Python allows simultaneous assignments, which are useful for swapping values of variables • Datatype conversion involves converting implicitly and explicitly between various datatypes, including integer, float, and string Summary
  • 38. • Functions- Part I Next Lecture…