Il 0% ha trovato utile questo documento (0 voti)
6 visualizzazioni

1python1 AA

intro to python

Caricato da

sabakabha
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Il 0% ha trovato utile questo documento (0 voti)
6 visualizzazioni

1python1 AA

intro to python

Caricato da

sabakabha
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Sei sulla pagina 1/ 36

Python

Variables, Expressions, and Statements


Interactive vs Script mode
Online Compiler
Interactive mode:

https://www.python.org/shell/

google colab

Script mode:

https://repl.it/languages/python3

https://www.onlinegdb.com/online_python_interpreter
Hello world
Output
Escape Sequence
Using ‘%’ for string formatting

%s is used for strings

%d for decimal integers

%f for float

%e for float exponent


String Constants

• String constants use single quotes (')


or double quotes (")

>>> print('Hello world')


Hello world
Exercise
• What is the expected output of the following statements
(interactive mode)

11

x = 18

x+9

y=x+x

y+x
Python Variable Name Rules
• Must start with a letter or underscore _

• Must consist of letters, numbers, and underscores (A-z, 0-9, and _ )

• 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
Excercise
Are the following correct statements:

• 76trombones = 'big parade'

• more@ = 1000000

• class = 'Advanced Theoretical Zymurgy'


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 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

What are these bits


of code doing?
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication / Division
• Exponentiation (raise to a power) looks ** Power
different than in math
% Remainder
Numeric Expressions
>>> xx = 2 >>> jj = 23
>>> xx = xx + 2 >>> kk = jj % 5 Operator Operation
>>> print(xx) >>> print(kk)
+ Addition
4 3
>>> yy = 440 * 12 >>> print(4 ** 3) - Subtraction
>>> print(yy) 64 * Multiplication
5280
>>> zz = yy / 1000 4R3 / Division

>>> print(zz) 5 23 ** Power


5.28 20 % Remainder

3
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:

• Parentheses are always respected Parenthesis


Power
• Exponentiation (raise to a power) Multiplication
Addition
• Multiplication, Division, and Remainder
Left to Right
• Addition and Subtraction

• Left to right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0 1 + 8 / 4 * 5
>>>
1 + 2 * 5
Parenthesis
Power
Multiplication 1 + 10
Addition
Left to Right 11
What Does “Type” Mean?
• In Python variables and constants
have a “type” >>> ddd = 1 + 4
>>> print(ddd)
• Python knows the difference between 5
an integer number and a string >>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
• For example “+” means “addition” if
something is a number and
“concatenate” if something is a string
concatenate = put together
Type Matters
• Python knows what “type” >>> eee = 'hello ' + 'there'
everything is >>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
• Some operations are <module>TypeError: Can't convert
prohibited 'int' object to str implicitly
>>> type(eee)
• You cannot “add 1” to a string <class'str'>
>>> type('hello')
<class'str'>
• We can ask Python what type >>> type(1)
something is by using the <class'int'>
type() function >>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types >>> type (xx)
<class 'int'>
- Integers are whole numbers: >>> temp = 98.6
-14, -2, 0, 1, 100, 401233 >>> type(temp)
<class'float'>
- Floating Point Numbers have >>> type(1)
decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'int'>
>>> type(1.0)
<class'float'>
>>>
Type Conversions
>>> print(float(99) + 100)
• When you put an integer and 199.0
>>> i = 42
floating point in an expression,
>>> type(i)
the integer is implicitly
<class'int'>
converted to a float >>> f = float(i)

• You can control this with the >>> print(f)


42.0
built-in functions int() and >>> type(f)
float() <class'float'>
>>>
Integer Division

>>> print(10 / 2)
Integer division produces a floating 5.0
>>> print(9 / 2)
point result
4.5
>>> print(9 // 2)
4
String
>>> sval = '123'
>>> type(sval)
<class 'str'>

Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

• You can also use int() and


TypeError: Can't convert 'int' object
to str implicitly
>>> ival = int(sval)
float() to convert between >>> type(ival)
strings and integers <class 'int'>

• You will get an error if the string


>>> print(ival + 1)
124
>>> nsv = 'hello bob'
does not contain numeric >>> niv = int(nsv)
characters 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 nam = input('Who are you? ')
the user using the input() print('Welcome', nam)
function
• The input() function
returns a string
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 inp = input('Europe floor?')
usf = int(inp) + 1
number using a type print('US floor', usf)
conversion function
• Later we will deal with bad
input data 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


Exercise 1
• Write a program that uses input to prompt a user to enter
his name then his year of birth. Then welcomes him and
print his age.
Exercise 2
• Assume that we execute the following assignment
statements:

width = 13

height =8.0
what will be the output of the follwoing
•width // 2 //: qoutient of division but decimal part neglected
•width / 2.0

•height / 5

•3+2*3%5*2**2
Exercise 3

Write a program to prompt the user for hours


and rate per hour to compute gross pay.

E.g.
Enter Hours: 35
Enter Rate: 2.75

Pay: 96.25
Exercise 4
• Write a program which prompts the user for a Celsius
temperature, convert the temperature to Fahrenheit, and
print out the converted temperature

Note: °C to °F: Divide by 5, then multiply by 9, then add 32


Summary
• Type • Integer Division

• Reserved words • Conversion between types

• Variables (mnemonic) • User input

• Operators • Comments (#)

• Operator precedence
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

Ahmad Alzghoul, PSUT

Potrebbero piacerti anche