Types, Operators, Variables, Functions and Conditions (if statements)#

Python Programming for Engineers#

Tel-Aviv University / 0509-1820 / Fall 2025-2026#

Last recitation:#

  • Administration

  • Install Anaconda and Pycharm

  • Simple coding with Pycharm

Agenda#

Types

  • int, float, bool, str

Operators

  • + - * / ** // % ...?!@#

Variables

  • Assignment

Boolean statements

Functions

if-else statements

  • if-else
  • elif
  • nested if

Types and conversions#

c=float(137)
print(c, type(c))
137.0 <class 'float'>
c=int(3.17)
print(c, type(c))
3 <class 'int'>
c=float("3.17")
print(c, type(c))
3.17 <class 'float'>
c=int("3.17")
print(c, type(c))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 c=int("3.17")
      2 print(c, type(c))

ValueError: invalid literal for int() with base 10: '3.17'
c=int(float("3.17"))
print(c, type(c))
3 <class 'int'>

Always: order of actions inner parentheses \(\rightarrow\) outer parantheses#

c=False
print(type(c))
<class 'bool'>
c=bool(3.17)
print(c, type(c))
True <class 'bool'>
c=bool(1)
print(c, type(c))
True <class 'bool'>
c=bool(0)
print(c, type(c))
False <class 'bool'>

Operators#

print(13+7)
20
print(13-7)
6
print(13*7)
91
print(13/7)
1.8571428571428572
13//7
1
13%7
6
13**7
62748517

Slide 13-14

Variables and assignments#

alt_text

  • First evaluate the expression

  • Then assigns the value to the variable

A variable name is a sequence of letters, digits and underscores (‘_’), starting with a letter

n=1
print(n)
n=n+2
print(n)
n=n+4
print(n)
1
3
7

Functions#

Definition: functions are “self-contained” modules of code that accomplish a specific task#

Define a new function#

Function syntax#

def name(param1, param2, ...):  
    ''' documentation''' #Optional documentation   
    # your code here...
    return ...

Exercise 1#

Write code that receives the length of the two legs of a right triangle, a and b.#

  • Calculate the length of the hypotenuse, c

  • Calculate the triangle’s area

  • Calculate the triangle’s circumference

  • Print all three values

alt_text

## "Input" values
a=3
b=7

c=(a**2 + b**2)**0.5
area=(a*b)/2
circum=a+b+c
print(c,area,circum)
7.615773105863909 10.5 17.61577310586391

Now with function…#

Define the pythagoras function#

def pythagoras(a, b):  
    .
    .
    .
    return ...
def pythagoras(a, b):
    c = (a**2 + b**2)**0.5
    area=(a*b)/2
    circum=a+b+c
    return c,area,circum
hypo1 = pythagoras(1,3)
hypo2 = pythagoras(3,7)
hypo3 = pythagoras(1,7)

print(hypo1)
print(hypo2)
print(hypo3)
(3.1622776601683795, 1.5, 7.16227766016838)
(7.615773105863909, 10.5, 17.61577310586391)
(7.0710678118654755, 3.5, 15.071067811865476)

Strings#

  • Ordered collection of characters.

  • First index is zero (0)

H

e

l

l

o

0

1

2

3

4

-5

-4

-3

-2

-1

  • Strings can be enclosed in either ‘single quotes’ or “double quotes”.

print('If you spend all day shuffling words around, you can make anything sound bad')
If you spend all day shuffling words around, you can make anything sound bad
print('I'll tell you how I feel about school... It's a waste of time. Bunch of people runnin’ around... got a guy up front says, ‘Two plus two,’ and the people in the back say, 'Four'...')
  Cell In[23], line 1
    print('I'll tell you how I feel about school... It's a waste of time. Bunch of people runnin’ around... got a guy up front says, ‘Two plus two,’ and the people in the back say, 'Four'...')
          ^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
print('I\'ll tell you how I feel about school... It\'s a waste of time. Bunch of people runnin\' around... got a guy up front says, \'Two plus two,\' and the people in the back say, ‘Four’...')
I'll tell you how I feel about school... It's a waste of time. Bunch of people runnin' around... got a guy up front says, 'Two plus two,' and the people in the back say, ‘Four’...
  • Individual characters are accessed using brackets notation “[]” with the positional index

my_string="c-137"
print(my_string[0].upper())
print(my_string[-2])
print(my_string[4])
print(my_string[5])
C
3
7
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[25], line 5
      1 my_string="c-137"
      2 print(my_string[0].upper())
      3 print(my_string[-2])
      4 print(my_string[4])
----> 5 print(my_string[5])

IndexError: string index out of range
  • len() is used for getting the length of a string

my_string="c-137"
print(len(my_string))
5

String slicing#

  • syntax: some_str[x:y:z]

  • Returns a new string based on characters from some_str

  • from position x (including) until position y (not including) with steps of size (and direction) z

## "Input" values
some_str="Wubba Lubba Dub Dub"
x=1
y=10
z=2
# slice from x to y in step of size 1
print(some_str[x:y])
ubba Lubb
# slice from x to end in step of size z
print(some_str[x::z] )
ub ub u u
# slice from beginning to y with step of size z
print(some_str[:y:z] )
WbaLb

(3): string slicing#

## "Input" values
some_str="Wubba Lubba Dub Dub"
x=1
y=10
z=2

print(some_str[y:x:-z] )
abLab

Comparisons / boolean statements#

Comparison operators:#

==

equal

Note: twice ‘=‘, this is not an assignment!

!=

not equal

>

greater than

<

less than

>=

grater than or equal

<=

less than or equal

Comparisons are evaluated to Boolean (bool) values#

# Simple inequality (numeric)
c=137<138
print(c)
True
# Simple inequality (lexicography)
c='rick' <'morty'
print(c)
False

Multiple comparisons#

c=136<137 and 137<135
print(c)
False
# Can also mix it up:
c=6<7 or 'morty'<'rick'
print(c)
True

Conditional statements if#

alt_text alt_text

Each block contains:

  • exactly 1 if

  • 0 or more elif

  • 0 or 1 else

  • Note how each of if and else has its own indented statements under its own block.

Example #1: if vs elif#

# "Input" values 
rick_chips = 137
morty_chips = 731

if rick_chips > morty_chips:
    print("Rick won")
elif morty_chips > rick_chips:
    print("Morty won")
else:
    print("It's a tie!")
    
print("end")
Morty won
end
# "Input" values 
rick_chips = 137
morty_chips = 731

if rick_chips > morty_chips:
    print("Rick won")
if morty_chips > rick_chips:
    print("Morty won")
else:
    print("It's a tie!")
    
print("end")
Morty won
end

Example #2: nested if#

Write a function that returns whether a number is “positive even”, “positive odd”, “negative even”, “negative odd” or “zero”#

# "Input" values 

def categorize_number(n):
    if n > 0:
        if n%2 == 0:
            return "positive even"
        else:
            return "positive odd"
    elif n < 0:
        if n%2 == 0:
            return "negative even"
        else:
            return "negative odd"
    else:
        return "zero"
categorize_number(138)
categorize_number(-57)
categorize_number(0)
'zero'

Operations on mixed variables#

c=140 
print(c-137)
3
print("c"-137) 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[42], line 1
----> 1 print("c"-137)

TypeError: unsupported operand type(s) for -: 'str' and 'int'
print("c-"+137)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[43], line 1
----> 1 print("c-"+137)

TypeError: can only concatenate str (not "int") to str
print("c-"+"137")
c-137
print(c*2)
280
print("c"*2)
cc
print("c-"*2+137)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[47], line 1
----> 1 print("c-"*2+137)

TypeError: can only concatenate str (not "int") to str
print(c**2)
19600
print("c"**2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[49], line 1
----> 1 print("c"**2)

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

Self learning#

Exercise 1#

  • Return the number resulting from reversing the digit of a given four-digit number

  • No str functions

Example: 1370 –> 731 (0731)

num=1370

num1=(num%10)*1000 
num2=(num%100//10)*100 
num3=(num%1000//100)*10 
num4=((num)//1000)*1

print(num1,num2,num3,num4)
print(num1+num2+num3+num4)
0 700 30 1
731

Now with functions…#

def reverse_digits(num):
    num1=num%10*1000 
    num2=num//1000 
    num3=num%100//10*100 
    num4=num%1000//100*10 
    return num1+num2+num3+num4
print(reverse_digits(1370))
print(reverse_digits(1375))
731
5731

Exercise 2#

Write a code that receives a string s with only lower letters, and prints a similar string, but with the middle letter in an upper case format.#

e.g.,
efghi \(\rightarrow\) efGhi
efghij \(\rightarrow\) efgHij

## "Input" values
s = 'limerick'
# Find string’s length
n = len(s)
print(n)
8
# Find string’s middle index
middle = n / 2 
print(middle)
4.0
# Find string’s middle letter
middle_letter = s[middle]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[56], line 2
      1 # Find string’s middle letter
----> 2 middle_letter = s[middle]

TypeError: string indices must be integers, not 'float'
# A float cannot serve as an index! use integer division instead
middle = n // 2
print(middle)
middle_letter = s[middle]
4
# Converts middle letter to an upper case 
U_middle_letter = middle_letter.upper()
# Slice the string before and after the capitalized character and merge it with the revised character
new = s[0:middle] + U_middle_letter + s[middle+1:]
print(new)
limeRick

Putting in all together in a function#

 def cap_in_middle(s):
    n = len(s)
    middle = n // 2
    middle_letter = s[middle]
    U_middle_letter = middle_letter.upper()
    return s[0:middle] + U_middle_letter + s[middle+1:]
    
print(cap_in_middle('limerick'))
print(cap_in_middle('rickandmorty'))
limeRick
rickanDmorty