SlideShare a Scribd company logo
1 of 35
Variables, Expressions, and
Statements
Python for Everybody
www.py4e.com
Constants
• Fixed values such as numbers, letters, and strings are called
“constants” because their value does not change
• Numeric constants are as you expect
• String constants use single quotes (')
or double quotes (")
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world')
Hello world
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
12.2
x
14
y
x = 12.2
y = 14
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
12.2
x
14
y
100
x = 12.2
y = 14
x = 100
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
Different: spam Spam SPAM
Reserved Words
• You cannot use reserved words as variable names / identifiers
False class return is finally
None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Sentences or Lines
x = 2
x = x + 2
print(x)
Variable Operator Constant
Reserved
Word
Assignment statement
Assignment with expression
Print statement
Assignment Statements
• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the
right-hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
x = 3.9 * x * ( 1 - x )
0.6
x
The right side is an expression.
Once the expression is evaluated, the
result is placed in (assigned to) x.
0.6 0.6
0.4
0.936
A variable is a memory location
used to store a value (0.6)
x = 3.9 * x * ( 1 - x )
0.6 0.93
x
0.6 0.6
0.4
0.936
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
left side (i.e., x).
A variable is a memory location used to
store a value. The value stored in a
variable can be updated by replacing the
old value (0.6) with a new value (0.93).
Numeric Expressions
• Because of the lack of mathematical
symbols on computer keyboards - we
use “computer-speak” to express the
classic math operations
• Asterisk is multiplication
• Exponentiation (raise to a power) looks
different from in math.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
>>> xx = 2
>>> xx = xx + 2
>>> print(xx)
4
>>> yy = 440 * 12
>>> print(yy)
5280
>>> zz = yy / 1000
>>> print(zz)
5.28
>>> jj = 23
>>> kk = jj % 5
>>> print(kk)
3
>>> print(4 ** 3)
64
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
5 23
4 R 3
20
3
Numeric Expressions
Order of Evaluation
• When we string operators together - Python must know which one
to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others?
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction
• Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right
Parenthesis
Power
Multiplication
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0
>>>
Operator Precedence
• Remember the rules top to bottom
• When writing code - use parenthesis
• When writing code - keep mathematical expressions simple enough
that they are easy to understand
• Break long series of mathematical operations up to make them
more clear
Parenthesis
Power
Multiplication
Addition
Left to Right
Exam Question: x = 1 + 2 * 3 - 4 / 5
What does “Type” Mean?
• In Python variables, literals and
constants have a “type”
• Python knows the difference between
an integer number and a string
• For example “+” means “addition” if
something is a number and
“concatenate” if something is a string
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
concatenate = put together
Type Matters
• Python knows what “type”
everything is
• Some operations are
prohibited
• You cannot “add 1” to a string
• We can ask Python what type
something is by using the
type() function
>>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>TypeError: Can't convert
'int' object to str implicitly
>>> type(eee)
<class'str'>
>>> type('hello')
<class'str'>
>>> type(1)
<class'int'>
>>>
Several Types of Numbers
• Numbers have two main types
• Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
• Floating Point Numbers have
decimal parts: -2.5 , 0.0, 98.6, 14.0
• There are other number types - they
are variations on float and integer
>>> xx = 1
>>> type (xx)
<class 'int'>
>>> temp = 98.6
>>> type(temp)
<class'float'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class'float'>
>>>
Type Conversions
• When you put an integer and
floating point in an
expression, the integer is
implicitly converted to a float
• You can control this with the
built-in functions int() and
float()
>>> print(float(99) + 100)
199.0
>>> i = 42
>>> type(i)
<class'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class'float'>
>>>
Integer Division
• Integer division produces a floating
point result
>>> print(10 / 2)
5.0
>>> print(9 / 2)
4.5
>>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
This was different in Python 2.x
String
Conversions
• You can also use int() and
float() to convert between
strings and integers
• You will get an error if the string
does not contain numeric
characters
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
to str implicitly
>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: 'x'
User Input
• We can instruct Python to
pause and read data from
the user using the input()
function
• The input() function
returns a string
nam = input('Who are you?')
print('Welcome', nam)
Who are you?
Chuck
Welcome Chuck
Converting User Input
• If we want to read a number
from the user, we must
convert it from a string to a
number using a type
conversion function
• Later we will deal with bad
input data
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)
Europe floor? 0
US floor 1
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary information
• Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = input('Enter file:')
handle = open(name, 'r')
# Count word frequency
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
# Find the most common word
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
# All done
print(bigword, bigcount)
String Operations
• Some operators apply to strings
• + implies “concatenation”
• * implies “multiple concatenation”
• Python knows when it is dealing with
a string or a number and behaves
appropriately
>>> print(“abc” + “123”)
abc123
>>> print('Hi' * 5)
HiHiHiHiHi
>>>
Mnemonic Variable Names
• Since we programmers are given a choice in how we choose our
variable names, there is a bit of “best practice”
• We name variables to help us remember what we intend to store
in them (“mnemonic” = “memory aid”)
• This can confuse beginning students because well-named
variables often “sound” so good that they must be keywords
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
What is this bit of
code doing?
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
a = 35.0
b = 12.50
c = a * b
print(c)
What are these
bits of code
doing?
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
a = 35.0
b = 12.50
c = a * b
print(c)
What are these
bits of code
doing?
Exercise
Write a program to prompt the user for hours
and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Exercise
Write a program to prompt the user for hours
and rate per hour to compute gross pay.
# Prompt the user for input
hours = float(input("Enter Hours: "))
rate_per_hour = float(input("Enter Rate: "))
# Calculate gross pay
gross_pay = hours * rate_per_hour
# Display the result
print(f"Pay: {gross_pay:.2f}")
Summary
• Type
• Reserved words
• Variables (mnemonic)
• Operators
• Operator precedence
• Integer Division
• Conversion between types
• User input
• Comments (#)
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) of the University of Michigan School of
Information and made available under a Creative Commons
Attribution 4.0 License. Please maintain this last slide in all
copies of the document to comply with the attribution
requirements of the license. If you make a change, feel free to
add your name and organization to the list of contributors on this
page as you republish the materials.
Initial Development: Charles Severance, University of Michigan
School of Information
… Insert new Contributors and Translators here
...

More Related Content

Similar to Lec2_cont.pptx galgotias University questions

Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Lecture 2 coal sping12
Lecture 2 coal sping12Lecture 2 coal sping12
Lecture 2 coal sping12
Rabia Khalid
 

Similar to Lec2_cont.pptx galgotias University questions (20)

Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
 
Python
PythonPython
Python
 
Lecture 2 coal sping12
Lecture 2 coal sping12Lecture 2 coal sping12
Lecture 2 coal sping12
 
Input Statement.ppt
Input Statement.pptInput Statement.ppt
Input Statement.ppt
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Python basics
Python basicsPython basics
Python basics
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptx
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
c-programming
c-programmingc-programming
c-programming
 
C++ process new
C++ process newC++ process new
C++ process new
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 

Recently uploaded

Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
Cara Menggugurkan Kandungan 087776558899
 
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
gynedubai
 
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night StandCall Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
gajnagarg
 
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night StandCall Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men 🔝Bulandshahr🔝 ...
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men  🔝Bulandshahr🔝  ...➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men  🔝Bulandshahr🔝  ...
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men 🔝Bulandshahr🔝 ...
amitlee9823
 
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
amitlee9823
 
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
yynod
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
amitlee9823
 
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
gajnagarg
 
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
gajnagarg
 
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
amitlee9823
 
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdfreStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
Ken Fuller
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men 🔝bhavnagar🔝 Esc...
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men  🔝bhavnagar🔝   Esc...➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men  🔝bhavnagar🔝   Esc...
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men 🔝bhavnagar🔝 Esc...
amitlee9823
 
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
amitlee9823
 
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night StandCall Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 

Recently uploaded (20)

Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
Cara Gugurkan Kandungan Awal Kehamilan 1 bulan (087776558899)
 
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
<DUBAI>Abortion pills IN UAE {{+971561686603*^Mifepristone & Misoprostol in D...
 
DMER-AYUSH-MIMS-Staff-Nurse-_Selection-List-04-05-2024.pdf
DMER-AYUSH-MIMS-Staff-Nurse-_Selection-List-04-05-2024.pdfDMER-AYUSH-MIMS-Staff-Nurse-_Selection-List-04-05-2024.pdf
DMER-AYUSH-MIMS-Staff-Nurse-_Selection-List-04-05-2024.pdf
 
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night StandCall Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Mahadevapura ☎ 7737669865 🥵 Book Your One night Stand
 
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
Just Call Vip call girls Firozabad Escorts ☎️9352988975 Two shot with one gir...
 
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night StandCall Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kr Puram ☎ 7737669865 🥵 Book Your One night Stand
 
Kannada Call Girls Mira Bhayandar WhatsApp +91-9930687706, Best Service
Kannada Call Girls Mira Bhayandar WhatsApp +91-9930687706, Best ServiceKannada Call Girls Mira Bhayandar WhatsApp +91-9930687706, Best Service
Kannada Call Girls Mira Bhayandar WhatsApp +91-9930687706, Best Service
 
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
 
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men 🔝Bulandshahr🔝 ...
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men  🔝Bulandshahr🔝  ...➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men  🔝Bulandshahr🔝  ...
➥🔝 7737669865 🔝▻ Bulandshahr Call-girls in Women Seeking Men 🔝Bulandshahr🔝 ...
 
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
 
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
怎样办理哥伦比亚大学毕业证(Columbia毕业证书)成绩单学校原版复制
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Jabalpur [ 7014168258 ] Call Me For Genuine Models ...
 
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls fazilka Escorts ☎️9352988975 Two shot with one girl ...
 
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
Chintamani Call Girls Service: ☎ 7737669865 ☎ High Profile Model Escorts | Ba...
 
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdfreStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
reStartEvents 5:9 DC metro & Beyond V-Career Fair Employer Directory.pdf
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men 🔝bhavnagar🔝 Esc...
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men  🔝bhavnagar🔝   Esc...➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men  🔝bhavnagar🔝   Esc...
➥🔝 7737669865 🔝▻ bhavnagar Call-girls in Women Seeking Men 🔝bhavnagar🔝 Esc...
 
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jayanagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
 
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night StandCall Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Chandapura ☎ 7737669865 🥵 Book Your One night Stand
 

Lec2_cont.pptx galgotias University questions

  • 2. Constants • Fixed values such as numbers, letters, and strings are called “constants” because their value does not change • Numeric constants are as you expect • String constants use single quotes (') or double quotes (") >>> print(123) 123 >>> print(98.6) 98.6 >>> print('Hello world') Hello world
  • 3. Variables • A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name” • Programmers get to choose the names of the variables • You can change the contents of a variable in a later statement 12.2 x 14 y x = 12.2 y = 14
  • 4. Variables • A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name” • Programmers get to choose the names of the variables • You can change the contents of a variable in a later statement 12.2 x 14 y 100 x = 12.2 y = 14 x = 100
  • 5. Python Variable Name Rules • Must start with a letter or underscore _ • Must consist of letters and numbers and underscores • Case Sensitive Good: spam eggs spam23 _speed Bad: 23spam #sign var.12 Different: spam Spam SPAM
  • 6. Reserved Words • You cannot use reserved words as variable names / identifiers False class return is finally None if for lambda continue True def from while nonlocal and del global not with as elif try or yield assert else import pass break except in raise
  • 7. Sentences or Lines x = 2 x = x + 2 print(x) Variable Operator Constant Reserved Word Assignment statement Assignment with expression Print statement
  • 8. Assignment Statements • We assign a value to a variable using the assignment statement (=) • An assignment statement consists of an expression on the right-hand side and a variable to store the result x = 3.9 * x * ( 1 - x )
  • 9. x = 3.9 * x * ( 1 - x ) 0.6 x The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) x. 0.6 0.6 0.4 0.936 A variable is a memory location used to store a value (0.6)
  • 10. x = 3.9 * x * ( 1 - x ) 0.6 0.93 x 0.6 0.6 0.4 0.936 The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e., x). A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93).
  • 11. Numeric Expressions • Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations • Asterisk is multiplication • Exponentiation (raise to a power) looks different from in math. Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder
  • 12. >>> xx = 2 >>> xx = xx + 2 >>> print(xx) 4 >>> yy = 440 * 12 >>> print(yy) 5280 >>> zz = yy / 1000 >>> print(zz) 5.28 >>> jj = 23 >>> kk = jj % 5 >>> print(kk) 3 >>> print(4 ** 3) 64 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 5 23 4 R 3 20 3 Numeric Expressions
  • 13. Order of Evaluation • When we string operators together - Python must know which one to do first • This is called “operator precedence” • Which operator “takes precedence” over the others? x = 1 + 2 * 3 - 4 / 5 ** 6
  • 14. Operator Precedence Rules Highest precedence rule to lowest precedence rule: • Parenthesis are always respected • Exponentiation (raise to a power) • Multiplication, Division, and Remainder • Addition and Subtraction • Left to right Parenthesis Power Multiplication Addition Left to Right
  • 15. Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11.0 >>>
  • 16. Operator Precedence • Remember the rules top to bottom • When writing code - use parenthesis • When writing code - keep mathematical expressions simple enough that they are easy to understand • Break long series of mathematical operations up to make them more clear Parenthesis Power Multiplication Addition Left to Right Exam Question: x = 1 + 2 * 3 - 4 / 5
  • 17. What does “Type” Mean? • In Python variables, literals and constants have a “type” • Python knows the difference between an integer number and a string • For example “+” means “addition” if something is a number and “concatenate” if something is a string >>> ddd = 1 + 4 >>> print(ddd) 5 >>> eee = 'hello ' + 'there' >>> print(eee) hello there concatenate = put together
  • 18. Type Matters • Python knows what “type” everything is • Some operations are prohibited • You cannot “add 1” to a string • We can ask Python what type something is by using the type() function >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly >>> type(eee) <class'str'> >>> type('hello') <class'str'> >>> type(1) <class'int'> >>>
  • 19. Several Types of Numbers • Numbers have two main types • Integers are whole numbers: -14, -2, 0, 1, 100, 401233 • Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0 • There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) <class 'int'> >>> temp = 98.6 >>> type(temp) <class'float'> >>> type(1) <class 'int'> >>> type(1.0) <class'float'> >>>
  • 20. Type Conversions • When you put an integer and floating point in an expression, the integer is implicitly converted to a float • You can control this with the built-in functions int() and float() >>> print(float(99) + 100) 199.0 >>> i = 42 >>> type(i) <class'int'> >>> f = float(i) >>> print(f) 42.0 >>> type(f) <class'float'> >>>
  • 21. Integer Division • Integer division produces a floating point result >>> print(10 / 2) 5.0 >>> print(9 / 2) 4.5 >>> print(99 / 100) 0.99 >>> print(10.0 / 2.0) 5.0 >>> print(99.0 / 100.0) 0.99 This was different in Python 2.x
  • 22. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <class 'str'> >>> print(sval + 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> ival = int(sval) >>> type(ival) <class 'int'> >>> print(ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'x'
  • 23. User Input • We can instruct Python to pause and read data from the user using the input() function • The input() function returns a string nam = input('Who are you?') print('Welcome', nam) Who are you? Chuck Welcome Chuck
  • 24. Converting User Input • If we want to read a number from the user, we must convert it from a string to a number using a type conversion function • Later we will deal with bad input data inp = input('Europe floor?') usf = int(inp) + 1 print('US floor', usf) Europe floor? 0 US floor 1
  • 25. Comments in Python • Anything after a # is ignored by Python • Why comment? • Describe what is going to happen in a sequence of code • Document who wrote the code or other ancillary information • Turn off a line of code - perhaps temporarily
  • 26. # Get the name of the file and open it name = input('Enter file:') handle = open(name, 'r') # Count word frequency counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 # Find the most common word bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # All done print(bigword, bigcount)
  • 27. String Operations • Some operators apply to strings • + implies “concatenation” • * implies “multiple concatenation” • Python knows when it is dealing with a string or a number and behaves appropriately >>> print(“abc” + “123”) abc123 >>> print('Hi' * 5) HiHiHiHiHi >>>
  • 28. Mnemonic Variable Names • Since we programmers are given a choice in how we choose our variable names, there is a bit of “best practice” • We name variables to help us remember what we intend to store in them (“mnemonic” = “memory aid”) • This can confuse beginning students because well-named variables often “sound” so good that they must be keywords http://en.wikipedia.org/wiki/Mnemonic
  • 29. x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) What is this bit of code doing?
  • 30. x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) a = 35.0 b = 12.50 c = a * b print(c) What are these bits of code doing?
  • 31. x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) hours = 35.0 rate = 12.50 pay = hours * rate print(pay) a = 35.0 b = 12.50 c = a * b print(c) What are these bits of code doing?
  • 32. Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25
  • 33. Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. # Prompt the user for input hours = float(input("Enter Hours: ")) rate_per_hour = float(input("Enter Rate: ")) # Calculate gross pay gross_pay = hours * rate_per_hour # Display the result print(f"Pay: {gross_pay:.2f}")
  • 34. Summary • Type • Reserved words • Variables (mnemonic) • Operators • Operator precedence • Integer Division • Conversion between types • User input • Comments (#)
  • 35. Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of Information and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information … Insert new Contributors and Translators here ...