Python Basics

Data and Expressions

A literal is a sequence of one or more character that stands for itself.

Numeric Literals

Contains decimal point -> floating-point value

Otherwise -> integer value


In [1]:
type(1.0)


Out[1]:
float

In [2]:
3+6


Out[2]:
9

In [3]:
type(1)


Out[3]:
int

In [4]:
# Limit of Precision
1.0/3


Out[4]:
0.3333333333333333

In [5]:
5.0//3


Out[5]:
1.0

In [6]:
3*(1.0/3)


Out[6]:
1.0

In [7]:
# Built-in Format Function 
12.0/5


Out[7]:
2.4

In [8]:
a = format(12.0/5, '.2f')
a


Out[8]:
'2.40'

In [9]:
type(a) # It's string careful.


Out[9]:
str

In [10]:
float(a)


Out[10]:
2.4

In [11]:
int('123')


Out[11]:
123

In [12]:
str(13)


Out[12]:
'13'

In [13]:
a


Out[13]:
'2.40'

In [14]:
5.0/7


Out[14]:
0.7142857142857143

In [15]:
2*a


Out[15]:
'2.402.40'

In [16]:
float(format(5.0/7, '.2f'))


Out[16]:
0.71

String Literals

Strings represent a sequence of characters.

Strings surrounded by a matching pair of either single (') or double (") quotes.


In [17]:
print('Hello World!')


Hello World!

In [18]:
print('String 10 String 20')


String 10 String 20

In [19]:
'String 1' # single quotes


Out[19]:
'String 1'

In [20]:
"String 2" # Double quotes


Out[20]:
'String 2'

In [21]:
"Enes's String" # Usage of single and double together


Out[21]:
"Enes's String"

In [22]:
type("") # Empty string


Out[22]:
str

In [23]:
' ' # String which contains only space


Out[23]:
' '

So how is computer understands the character, since language of computer is made of 1s and 0s?

There is a special encoding for character which represents a number between 0 to 127.


In [24]:
ord('1') # Returns the ASCII value of string 1


Out[24]:
49

In [25]:
chr(122) # Returns the character value of ASCII 122


Out[25]:
'z'

Variable

A variable is an identifier (name) that is associated with a value.


In [26]:
num = 10

In [27]:
num


Out[27]:
10

Variable can be assigned different values during a program's execution.

Variables are assigned values by use of the assignment operator (=)


In [28]:
# Update Variable
num = num + 1 # num += 1

In [2]:
num = ("Nazugum")

In [3]:
type(num)


Out[3]:
str

Now let's learn how to assign values which comes from the user inputs.


In [4]:
name = input("What is your first name?")


What is your first name?Enes

In [5]:
(name + " ")* 2


Out[5]:
'Enes Enes '

In [8]:
num_credits


Out[8]:
54

In [7]:
num_credits = 54
  • All input is returned by the input function as as string type.
  • For the input of numeric values, the response must be converted to the appropriate type.

In [9]:
line = input('How many credits do you have?')


How many credits do you have?118

In [10]:
num_credits = int(line)
num_credits


Out[10]:
118

In [11]:
num_credits


Out[11]:
118

There are some restrictions on declaring variable names:

  • quotes not allowed
  • spaces not allowed
  • cannot begin with digit
  • should not begin with underscore

In [12]:
name" = 2


  File "<ipython-input-12-e8008b0a2052>", line 1
    name" = 2
             ^
SyntaxError: EOL while scanning string literal

In [13]:
"name" = "Enes"


  File "<ipython-input-13-59bec5546018>", line 1
    "name" = "Enes"
                   ^
SyntaxError: can't assign to literal

In [14]:
name_student = "Enes"
name_student


Out[14]:
'Enes'

In [15]:
2012name = "Enes"


  File "<ipython-input-15-6b786e92b5ef>", line 1
    2012name = "Enes"
           ^
SyntaxError: invalid syntax

In [16]:
name-enes


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-b0397dc7290d> in <module>()
----> 1 name-enes

NameError: name 'enes' is not defined

In [17]:
name = "Enes"
name


Out[17]:
'Enes'

Another important rule when it comes to usage of specific names. You cannot use predefined names. This is really important because Python won't complain when you use them but it will cause unwanted damages to your program.

Apply it!

You will write a small program using the basics I talked about above which produces the following output:

This program will calculate a restaurant tab for a couple with a gift certificate, with a reataurant tax of 8.0%
Enter the amount of the gift certificate: 200
Enter ordered items for person 1
Appetizer: 5.50
Entree: 21.50
Drinks: 4.25
Dessert: 6.00

Enter ordered items for person 2
Appetizer: 6.25
Entree: 18.50
Drinks: 6.50
Dessert: 5.50

Ordered items: $ 74.00
Restaurant tax: $ 5.92
Tab: $ -120.08
(negative amount indicates unused amount of gift certificate)

You need to use input function for gift certificate, appetizer, entree, drinks, dessert

For solution run scripts/restaurant_tab_calculation.py on your terminal with python

Test Time

Question1: Which of the following are valid assignment statements, in which only variable k has already been assigned a value?

  1. n = k + 1
  2. n = n + 1
  3. n + k = 10
  4. n + 1 = 1

Question2: What is the value of variable num after the following assignment statements are executed?

num = 0
num = num + 1
num += 5


Question3: Do variables num and k reference the same memory location after the following instructions are executed? (YES/NO)

num = 10
k = num
num += 1

Question4: Which of the following are valid identifi ers in Python?

  1. errors
  2. error_count
  3. error-count

Question5: Which of the following are keywords in Python?

  1. and
  2. As
  3. while
  4. until
  5. NOT

Question6: Which one of the following is correct for reading and storing and integer value from the user?

  1. n = input('Enter: ')
  2. n = int(input('Enter: ')

Operators

An operator is a symbol that represents an operation that may be performed on one or more operands.

Arithmetic Operators


In [21]:
20 - 5


Out[21]:
15

In [22]:
-10 * 2


Out[22]:
-20

In [23]:
2 ** 4


Out[23]:
16

In [24]:
2.5 ** 4


Out[24]:
39.0625

In [25]:
25.0 // 10


Out[25]:
2.0

In [26]:
25 // 10


Out[26]:
2

In [27]:
25.0 / 10


Out[27]:
2.5

Apply it!

You will write a small program using the basics I talked about above which producing the following output:

This program will determine your place in the universe.
Enter your weight in pounds: 150
You contain approximately 3.30e+28 atoms
Therefore, you comprise 3.30e-51 % of the universe

Use these initial variables:
num_atoms_universe = 10e80
weight_avg_person = 70 # 70 Kg == (154 lbs)
num_atoms_avg_person = 7e27

For solution run scripts/your_place_in_universe.py on your terminal with python

Test Time

Question1: Give the results for each of the following.

  1. -2 * 3
  2. 15 % 4
  3. 3 ** 2

Question2: Give the exact results of each of the following division operations.

  1. 5 / 4
  2. 5 // 4
  3. 5.0 // 4

Question3: Which of the expressions in question 2 is an example of integer division?

Question4: Do any two of the expressions in question 2 evaluate to the exact same result? (YES/NO)

Question5: How many operands are there in the following arithmetic expression?

2 * 24 + 60 - 10

Expression and Data Types

An expression is a combination of symbols that evaluates to a value.

4 + (3 * k)

This expression has two subexpressions, 4 and (3 * k). Subexpression (3 * k) itself has two subexpressions, 3 and k.

An expression is a combination of symbols (or single symbol) that evaluates to a value. A sub-expression is any expression that is part of a larger expression.