[go: up one dir, main page]

0% found this document useful (0 votes)
17 views39 pages

Week 2

The document provides an overview of fundamental data types, constants, variables, and operators in Python and C++. It highlights differences in syntax, compilation processes, and type handling between the two programming languages. Key concepts such as statements, expressions, namespaces, and type conversions are also discussed.

Uploaded by

esin tan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views39 pages

Week 2

The document provides an overview of fundamental data types, constants, variables, and operators in Python and C++. It highlights differences in syntax, compilation processes, and type handling between the two programming languages. Key concepts such as statements, expressions, namespaces, and type conversions are also discussed.

Uploaded by

esin tan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

SE226- WEEK2

Fundamental data types,


constants, variables, operators

prepared by Prof. Dr. Senem Kumova Metin


Python - C++ : Basics
hello.py hello.cpp

print("Hello world") #include <iostream>


using namespace std;
int main()
{
cout << "Hello world!";
return 0;
}

In Python no (not always) need to store source code in a file → INTERPRETED !!!!
C ++ Compilation

C++ actually adds an extra step to the basic compilation process: the code is run through
a preprocessor, which applies some modifications to the source code, before being fed to
the compiler.

adopted from lecture notes of MIT OpenCourseWare


Python Interpretation
• Python requires a piece of software called an interpreter.
• The interpreter is the program you’ll need to run Python code and
scripts.
• The interpreter is able to run Python code in two different ways:
1. As a script or module.

2. As a piece of code typed into an interactive session


Three
arrows
is the
prompt of the
Python
interpreter
Basics: Output
C++ :
cout << “This string will be printed out”;
Python
print(“This string will be printed out”)

This is the syntax for outputting some piece of text to the screen
Basics
• A statement is a unit of code that does something –a basic building
block of a program.

• An expression is a statement that has a value – for instance, a


number, a string, the sum of two numbers, etc. 4+2, x-1, and "Hello,
world!" are all expressions.

• Statements end with a semicolon in C++


cout<< “hello”;
Basics : C++
• Namespaces: In C++, identifiers can be defined within a context called
a namespace.

• To access an identifier defined in a namespace, tell the compiler to


look for it in that namespace using the scope resolution operator (::)
std::cout
• A cleaner alternative is to add the following line
using namespace std;
• This line tells the compiler that it should look in the std namespace
for any identifier we haven’t defined.
Basics
• C++ uses curly braces for blocks

• Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported,
but the standard indentation requires standard Python code to use four spaces.

x=1 #include <iostream>


if x == 1: using namespace std;
# indented four spaces
print("x is 1") int main()
else: {
print("x is not ") int x=1;
if (x==1) cout<< "x is 1";
else cout << " x is not 1";

return 0;
}
Basics: Input
Basics: Input
Constants
Fixed values such as numbers, letters, and strings, are called “constants” because their value does
not change
• Python: String constants use single quotes (‘) or double quotes (")
• C++: String constant use double quotes ("), characters use single quotes (')

#include <iostream>
>>> print(123)
123 using namespace std;
>>> print(98.6)
98.6 int main()
>>> print('Hello world') {
Hello world cout << 123<<endl;
cout << 98.6<<endl;
cout<<" Hello world";

return 0;
}
Reserved Words
C++
Python
asm double new switch
False class return is finally auto else operator template
None if for lambda continue
True def from while nonlocal break enum private this
and del global not with case extern protected throw
as elif try or yield catch float public try
assert else import pass
char for register typedef
break except in raise
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
Data types
• Every expression has a type – a formal description of what kind of
data its value is.
• For instance,0 is an integer, 3.142 is a floating-point (decimal)number

• All variables, literals, and constants must have a “type”


Data types: Python

adopted from https://www.geeksforgeeks.org/python-data-types/


Data types: C++

adopted from https://www.geeksforgeeks.org/python-data-types/


Variables
• In C++ variables must be declared and types must be explicitly given..
• In Python variables must be declared but types are not given..
File.py File.cpp

x=8 #include <iostream>


print(x) using namespace std;

int main()
{ int x;
x=8;
cout << x<<endl;
return 0;
}
Type Matters >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
• Python knows what “type” <module>TypeError: Can't convert
everything is 'int' object to str implicitly

• Some operations are >>> type(eee)


<class'str’>
prohibited
>>> eee=18
• You cannot “add 1” to a string >>>eee
18
• We can ask Python what type
>>> type('hello')
something is by using the <class'str’>
type() function
>>> type(1)
<class'int'>
Python : Several Types of Numbers
>>> xx = 1
>>> type (xx)
• Numbers have two main types <class 'int’>
- Integers are whole numbers:
>>> temp = 98.6
-14, -2, 0, 1, 100, 401233 >>> type(temp)
<class'float’>
- Floating Point Numbers have
decimal parts: -2.5 , 0.0, 98.6, 14.0 >>> type(1)
<class 'int’>
• There are other number types - they
are variations on float and integer
>>> type(1.0)
<class'float'>
Python: Type Conversions
>>> print(float(99) + 100)
199.0
• When you put an integer and >>> i = 42
floating point in an >>> type(i)
expression, the integer is <class'int’>
implicitly converted to a float
>>> f = float(i)
• You can control this with the >>> print(f)
built-in functions int() and 42.0
float()
>>> type(f)
<class'float'>
>>> sval = '123'

Python:String >>> type(sval)


<class 'str’>

Conversions >>> print(sval + 1)


Traceback (most recent call last): File
"<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to

• You can also use int() and str implicitly

float() to convert between >>> ival = int(sval)


>>> type(ival)
strings and integers <class 'int’>

• You will get an error if the string >>> print(ival + 1)


does not contain numeric 124
>>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent call last): File
"<stdin>", line 1, in <module>
ValueError: invalid literal for int() with
base 10: 'x'
C ++ Data Types
C ++ Type Conversion
C++:
String
Conversion
Comments
• 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

• Anything after a # is ignored by Python

• Single-line comments (informally, C++ style), start with // and


continue until the end of the line. If the last character in a
comment line is a \ the comment will continue in the next line.
• Multi-line comments (informally, C style), start with /* and end
with */ .
Operators
Basics
• Operators are special symbols that designate that some sort of
computation should be performed. The values that an operator acts
on are called operands.
>>> a = 10

>>> b = 20

>>> a + b
30
adopted from https://www.geeksforgeeks.org
C ++ operators!!
(new and delete)
In following weeks, we will
learn the details on new and
delete operators!!
Python: Assignment Operators
Operator Description Syntax
= Assign value of right side of expression to left side operand x=y+z
Add and Assign: Add right side operand with left side operand and then assign to left
+= a += b
operand
Subtract AND: Subtract right operand from left operand and then assign to left
-= a -= b
operand: True if both operands are equal
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a *= b
/= Divide AND: Divide left operand with right operand and then assign to left operand a /= b
Modulus AND: Takes modulus using left and right operands and assign result to left
%= a %= b
operand
Divide(floor) AND: Divide left operand with right operand and then assign the
//= a //= b
value(floor) to left operand
Exponent AND: Calculate exponent(raise power) value using operands and assign value
**= a **= b
to left operand
&= Performs Bitwise AND on operands and assign value to left operand a &= b
|= Performs Bitwise OR on operands and assign value to left operand a |= b
^= Performs Bitwise xOR on operands and assign value to left operand a ^= b
>>= Performs Bitwise right shift on operands and assign value to left operand a >>= b
<<= Performs Bitwise left shift on operands and assign value to left operand
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 )

adopted from lecture notes of Charles R. Severance


A variable is a memory location x 0.6
used to store a value (0.6)

0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4

The right side is an expression.


0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.

adopted from lecture notes of Charles R. Severance


A variable is a memory location used to
store a value. The value stored in a x 0.6 0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).

adopted from lecture notes of Charles R. Severance


Assignment Examples in Python
>>> x=[1, 2, 3]
>> x=6
>>> x
>> x+=4 [ 1 2 3]
>> x
>>> type(x)
10 <class 'list'>

>>> x+=[1]

>>> x
[1 2 3 1]
Assignment Examples in C++
Arithmetic Operators: Python
>>> a = 4
>>> b = 3
>>> -b
-3

>>> a + b
7
>>> a / b
1.3333333333333333
>>> a % b
1
>>> a ** b
64
>>> 10 / 5
2.0
>>> type(10 / 5)
<class 'float’>
>>> 2 * 25 + 30
80
Comparison Operators : Python
>>> a = 10
>>> b = 20
>>> a == b
False
>>> a != b
True
>>> a <= b
True
>>> a >= b
False

>>> a = 10
>>> b = 10
>>> a == b
True

>>> type(a==b)
<class 'bool’>
More on Boolean >>> type([])
>>> print(bool(0), bool(0.0), bool(0.0+0j)) <class 'list’>
False False False
>>> bool([])
>>> print(bool(-3), bool(3.14159), bool(1.0+1j)) False
True True True
>>> type([1, 2, 3])
>>>type('') <class 'list’>
<class 'str’>
>>> bool([1, 2, 3])
>>>type('''')
True
<class 'str’>
>>>x=[1, 2, 3]
>>> x
>>> print(bool(''), bool(""))
[ 1 2 3]
False False

>>>x+=[1]
>>> print(bool('foo'), bool("fooooo")) >>> x
True True [1 2 3 1]
>>> x = 5

>>> not x < 10


Logical Operators : Python False

>>> x = 3
>>> y = 4
>>> x or y
3

>>> x = 0.0
>>> y = 4.4
>>> x or y
4.4

>>> string = ‘here’


>>> s = string or '<default_value>’
>>> s
‘here’

>>> string = ''


>>> s = string or '<default_value>’
>>> s
'<default_value>'
Identity operators: Python
is , is not

If values are outside the range of common integers


(ranging from -5 to 256), they’re stored at separate memory addresses.

You might also like