0% found this document useful (0 votes)
13 views41 pages

Chapters (1 and 2)

The document provides an overview of Python programming, detailing its classification among programming languages, its features, and its applications. It outlines the programming process, including writing, converting, and executing Python code, as well as installing Python and using its arithmetic and string functionalities. Additionally, it emphasizes Python's ease of use for beginners and its extensive libraries for various applications.

Uploaded by

akdas.busra12
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)
13 views41 pages

Chapters (1 and 2)

The document provides an overview of Python programming, detailing its classification among programming languages, its features, and its applications. It outlines the programming process, including writing, converting, and executing Python code, as well as installing Python and using its arithmetic and string functionalities. Additionally, it emphasizes Python's ease of use for beginners and its extensive libraries for various applications.

Uploaded by

akdas.busra12
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/ 41

Computer Programming I

First Chapter

Python Programming
A general overview
Arithmetic, Strings, and Variables

CENG 111
Dr. Eng. Abdullatif BABA
2020 - 2021
Programming languages
Programming is the process of creating a set of instructions stored inside the memory in order to
tell a microprocessor how to perform a given task. Programming can be done using a variety of
programming languages.

Programming languages are classified as : Machine language, Assembly language, and High level
languages

MACHINE LANGUAGE : is a low-level programming language (the language of 0s and 1s) which is
composed of instructions used directly to control a computer's central processing unit (CPU). Each
instruction causes the CPU to perform a very specific task. Machine code is a strictly numerical
language which is intended to run as fast as possible. The majority of practical programs are written
in higher-level languages or assembly language. The source code is then interpreted to executable
machine code by utilities such as compilers or assemblers.

ASSEMBLY LANGUAGES: is a low-level programming language in which there is a very strong


correspondence between the instructions in the language and the architecture's machine
code instructions. Assembly language depends on the machine code instructions, i.e. It is designed for
exactly a specific CPU architecture. For example the assembly language used with Intel
microprocessors family.
Example of assembly instructions: Add, Sub, load, jump ... etc.

HIGH LEVEL LANGUAGE : high level languages are English like statements and programs. like
Java, C++, C#, Python.
Programming languages

Typically, programs are organized as in : They have an input part, a


processing part, and an output part.
Programming languages
The Python Language

• It is a computer programming language and a corresponding set of software tools and

libraries. It was designed to be interactive as well as easy to read and learn.

• Python supports object-oriented programming (OOP) like C++ .

• Python comes with a wide range of ready-made libraries that can be used in your own

programs.

• A very practical feature of Python is its maintainability. Since Python programs are

relatively easy to read and modify, they are easy for programmers to keep up to date.

Python’s support for maintenance is a big win in the eyes of many professionals.
Programming languages
What Is Python Useful For?
While Python is a general-purpose language that can be used to write any kind of program, it is especially popular for
the following applications:
• Scripts. These short programs automate common administrative tasks, such as adding new users to a system,
uploading files to a website, downloading webpages without using a browser, and so on.
• Website development. A number of Python projects—such as Django, Bottle and Zope, are popular among
developers as tools for quickly creating dynamic websites. The popular news site "reddit.com" was written using
Python.
• Text processing. Python has excellent support for handling strings and text files, including regular expressions and
Unicode.
• Scientific computing. Many superb scientific Python libraries are available on the web, providing functions for
statistics, mathematics, and graphing.
• Education. Thanks to its relative simplicity and utility, Python is becoming more and more popular as a first
programming language in schools.
Python isn’t the best choice for all projects. It is often slower than languages such as Java, C#, or C++. So, for example,
you wouldn’t use Python to create a new operating system.
But when you need to minimize the amount of time a programmer spends on a project, Python is often an excellent
choice.
Programming languages
The programming process

1. Determine what your program is supposed to do—that is, figure out its requirements.

2. Write the source code (in our case, the Python code) in IDLE (Python’s Integrated Development Environment) or any

other text editor. This is often the most interesting and challenging step, and it often involves creative problem solving.

Python source code files end with .py; Example: web.py, urlexpand.py, clean.py, and so on.

3. Convert the source code to object code using the Python interpreter. Python puts object code in .pyc files. For

example, if your source code is in the file urlexpand.py, its object code will be put in the file urlexpand.pyc

4. Run, or execute, the program. With Python, this step is usually done immediately and automatically after step 2 is

finished.

5. Finally, check the program’s output. If errors are discovered, go back to step 2 to try to fix them. The process of fixing

errors is called debugging.

We typically call the contents of a .py file a program, source code, or just code.
Object code is sometimes referred to as executable code, the executable, or even just software.
Programming languages
Installing Python

1. Go to the Python download page at www.python.org/download.

2. Choose the most recent version of Python 3 (it should have a name like Python 3.x, where x is some small number).

This will take you to the appropriate download page with instructions for downloading Python on different computer

systems.

3. Click the appropriate installer link for your computer. For instance, if you are running Windows, click Windows x86

MSI Installer (3.x).

4. Once the installer has finished downloading, run it by double-clicking it.

5. After the installation has finished (which could take a few minutes), test to see that Python is installed properly. Open

the Windows Start menu and choose All Programs. You should see an entry for Python 3.0 (often highlighted in yellow).

Select IDLE (Python GUI), and wait a moment for the IDLE program to launch
Python Programming
Arithmetic, Strings, and Variables

Let’s see how to interact with the Python shell. Start IDLE; you should find it listed as a
program in your Start menu on Windows.

What you should see when you first launch the Python interactive command shell. The
top two lines tell you what version of Python you are running.
Python 3.6.6rc1 (v3.6.6rc1:1015e38be4, Jun 12 2018, 07:51:23) [MSC v.1900 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>

The shell prompt


In a Python transcript, >>> is the Python shell prompt.
A >>> marks a line of input from you, the user, while lines without a >>> are generated by
Python. Thus it is easy to distinguish at a glance what is from Python and what is from you.
Python Programming
Arithmetic, Strings, and Variables

Integer Arithmetic

• An integer is a whole number, such as 25, –86, or 0; Python puts no limit on the size of

an integer

• Python supports the four basic arithmetic operations:

• + (addition), – (subtraction), * (multiplication), and / (division).

• Python also uses ** for exponentiation and % to calculate remainders (for example, 25

% 7 is 4 because 7 goes into 25 three times, with 4 left over).

• Python also has an integer division operator, //. It works like /, except that it always

returns an integer. For example, 7 // 3 evaluates to the integer 2; the digits after the

decimal are simply chopped off (// doesn’t round!).


Python Programming
Arithmetic, Strings, and Variables
Order of evaluation
Arithmetic operators are grouped from lowest precedence to highest precedence.

For example
Python Programming
Arithmetic, Strings, and Variables
Floating Point Arithmetic
All the basic arithmetic operations that work with integers also work with floats,
even % (remainder) and // (integer division)

>>> 3.
3.0
>>> .5
0.5
Python Programming
Arithmetic, Strings, and Variables
Floating Point Arithmetic
Unlike integers, floating point numbers have minimum and maximum values that, if
exceeded, will cause overflow errors.
Example:
>>> 500.0 ** 10000
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
500.0 ** 10000
OverflowError: (34, 'Result too large')
Complex numbers
Python has built-in support for complex numbers that involve the square root of –1.
In Python, 1j denotes the square root of –1:
Example:
>>> 1j
1j
>>> 1j * 1j
(-1+0j)
Python Programming
Arithmetic, Strings, and Variables

Python comes with many different modules of prewritten code, including the math module.
The following table lists some of the most commonly used math module functions.

Rounds X to the nearest integer greater than or


equal to that element

The base of a natural logarithm is the special


number e.
b = 10 it becomes a common logarithm
Python Programming
Arithmetic, Strings, and Variables

• To use the math module, or any existing Python module, you must first import it:

>>> import math

You can now access any math function by putting math. in front of it:

>>> math.sqrt(5)

2.2360679774997898

>>> math.sqrt(2) * math.tan(22)

0.012518132023611912
Python Programming
Arithmetic, Strings, and Variables

• An alternative way of importing a module is this:


>>> from math import *
Now you can call all the math module functions without first appending math.:
>>> log(25 + 5)
3.4011973816621555
>>> sqrt(4) * sqrt(10 * 10)
20.0

• We can also import specific functions from the math module


>>> from math import sqrt, tan

Notice:
When using the from math import * style of importing if you have functions with the same name as any of the functions in
the math module, the math functions will overwrite them!
Thus, it’s generally safer to use the import math style of importing. This will never overwrite existing functions.
Python Programming
Arithmetic, Strings, and Variables
Strings
A string is a sequence of one or more characters, such as "cat!", "567-45442",
and "Up and Down". Characters include letters, numbers, punctuation, plus hundreds
of other special symbols and unprintable characters.
Indicating a string
Python lets you write string literals in three main ways:
• Single quotes, such as 'http', 'open house', or 'cat'
• Double quotes, such as "http", "open house", or "cat"
• Triple quotes, such as """http""", or multiline strings, such as
"""
Me and my monkey
Have something to hide
"""
One of the main uses of single and double quotes is to conveniently handle " and ' characters inside strings:
"It's great"
'She said "Yes!" '
Triple quotes are useful when you need to create long, multiline strings. They can also contain " and ' characters at the
same time.
Python Programming
Arithmetic, Strings, and Variables
String length
To determine the number of characters in a string, use the len(s) function:

>>> len('pear')
4
>>> len('up, up, and away')
16
>>> len("moose")
5
>>> len("") #The empty string has zero characters in it.
0

We can use the len function as follows:

>>> 5 + len('cat') * len('dog')


14
Python Programming
Arithmetic, Strings, and Variables
String Concatenation

You can create new strings by linking (adding) some old strings together:
>>> 'hot ' + 'dog'
'hot dog'
>>> 'Once' + " " + 'Upon' + ' ' + "a Time"
'Once Upon a Time'

A practical shortcut for concatenating the same string many times:


>>> 10 * 'ha'
'hahahahahahahahahaha'
>>> 'hee' * 3
'heeheehee'
>>> 3 * 'hee' + 2 * "!"
'heeheehee!!'
The result of string concatenation is always another string, so you can use concatenation
anywhere that requires a string:
>>> len(12 * 'pizza pie!')
120
>>> len("house" + 'boat') * '12'
'121212121212121212'
Python Programming
Arithmetic, Strings, and Variables
Getting Help
Python is a self-documenting language

1. To see a list of all the built-in functions in Python, type dir(__builtins__) at the
command prompt.
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError',
'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError',
'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',
'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
'_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray',
'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min',
'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']

2. To see the doc string for any function; you can use the help(function_name)
>>> help (round)
Help on built-in function round in module builtins:

round(...)
round(number[, ndigits]) -> number

Round a number to a given precision in decimal digits (default 0 digits).


This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
Python Programming
Arithmetic, Strings, and Variables
Getting Help
Python is a self-documenting language

3. You can run the Python help utility by typing help() at a prompt. This will provide you
with all kinds of useful information, such as a list of all available modules, help with
individual functions and keywords, and more.
>>> help()
Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type


"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>

4. Once you’ve imported a module, you can list all of its functions using
the dir(m) function:
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Python Programming
Arithmetic, Strings, and Variables
Getting Help
Another alternative is to print a documentation strings

>>> print(math.tanh.__doc__)
tanh(x)

Return the hyperbolic tangent of x.

>>> print(bin.__doc__)
Return the binary representation of an integer.

>>> bin(2796202)
'0b1010101010101010101010'
Python Programming
Arithmetic, Strings, and Variables
Converting Between Types of data

1. Implicit Conversions
Sometimes Python will convert between numeric types without requiring an explicit
conversion function. For example:
>>> 25 * 8.5
212.5
Here, 25 is automatically converted to 25.0, and then multiplied by 8.5. In general, when
you mix integers and floats in the same expression, Python automatically converts the
integers to floats.

2. Converting integers and strings to floats


To convert an integer to float, use the float(x) function:
>>> float(3)
3.0

Converting a string to a float is similar:


>>> float('3.2')
3.200000000000000
>>> float('3')
3.0
Python Programming
Arithmetic, Strings, and Variables
Converting Between Types of data

3. Converting integers and floats to strings


The str(n) function converts any number to a corresponding string:
>>> str(85)
'85'
>>> str(-9.78)
'-9.78'

4. Converting a float to an integer


You have to decide how to handle the digits after the decimal in your float.
The int(x) function simply chops off extra digits, while round(x) does the usual kind of
rounding off:
>>> int(8.64)
8
>>> round(8.64)
9
>>> round(8.5) In Python the numbers ending in .5 are rounded to the nearest even
8 ? integer. Thus, sometimes numbers ending in .5 are rounded down,
>>> round(9.5) and sometimes they are rounded up.
10
Python Programming
Arithmetic, Strings, and Variables
Converting Between Types of data

5. Converting strings to numbers


This is easily done with the int(s) and float(s) functions:
>>> int('5')
5
>>> float('5.1')
5.1

6. the Python math module has a number of functions for removing digits after
decimals: math.trunc(x), math.ceil(x), and math.floor(x).

>>> help(math.trunc)
Help on built-in function trunc in module math:

trunc(...)
trunc(x:Real) -> Integral

Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

>>> math.trunc(4.7) >>> math.ceil(4.5) >>> math.floor(4.5)


4 5 4
>>> math.trunc(4.1) >>> math.ceil(3.2) >>> math.floor(3.2)
4 4 3
Python Programming
Arithmetic, Strings, and Variables
Variables and Values
Variables, functions, modules, and classes all have names; these names are called
identifiers.

• A variable name can be of any length, the characters could be letters, numbers, or the
underscore character (_).
• Spaces, dashes, punctuation, quotation marks, and other such characters are not allowed.
• The first character of a variable name cannot be a number; it should be a letter or an
underscore character.
• Python is case sensitive; thus TAX, Tax, and tax are three different variable names.
• You cannot use Python keywords as variable names. For
example: if, else, while, def, or, and, not, in, and is are some of Python’s keywords.
Python Programming
Arithmetic, Strings, and Variables
Variables and Values

In all programming langaues variables label, or point to, a value; i.e. values should be
assigned to variables.
>>> fruit = 'Python_Programming'
>>> fruit
'Python_Programming‘

>>> cost = 2.99


>>> 0.1 * cost
0.29900000000000004
>>> 1.06 * cost + 5.99
9.1594000000000015
>>> else = 25
SyntaxError: invalid syntax
Python Programming
Arithmetic, Strings, and Variables
Assignment Statements
The left-hand side of any assignment must always be a variable, while the right-hand side
can be a variable, a value, or any expression that evaluates to a value.
>>> x = 5 >>> x = 5
>>> 2 * x + 1 >>> y = 'cat'
11 >>> x = y
>>> x = 99 >>> x
'cat'
• The first assignment statement, x = 5, does double
>>> y
duty: It is an initialization statement. It tells Python
'cat'
to create a new variable named x and that it should
be assigned the value 5. We can now
• A variable can be assigned any value, even if it
use x anywhere an integer can be used.
comes from other variables
• The second assignment statement, x = 99,
reassigns x to point to a different value. It
does not create x, because x already exists thanks to
the previous assignment statement.
>>> 2 * y + 1
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
2*y+1
NameError: name 'y' is not defined
• If you don’t initialize a variable, Python complains with an error
Python Programming
Arithmetic, Strings, and Variables

Multiple Assignment Swapping variable values

>>> x, y, z = 1, 'two', 3.0 >>> a, b = 5, 9


>>> x >>> a, b
1 (5, 9)
>>> y >>> a, b = b, a
'two' >>> a, b
>>> z (9, 5)
3.0
>>> x, y, z
(1, 'two', 3.0)
Python Programming
Arithmetic, Strings, and Variables
Garbage collection
Python automatically deletes it. In general, Python keeps track of all values and
automatically deletes them when they are no longer referenced by a variable

>>> rate = 0.04


>>> rate_2008 = 0.06
>>> rate = rate_2008

It’s essential to understand that assignment statements don’t make a copy of the value they
point to. All they do is label, and re-label, existing values.
Python Programming
The source book of this course is illustrated below

The University of Turkish Aeronautical Associaiton


Computer Eng. dept.
2020-2021

Dr. Eng. Abdullatif BABA Second Chapter


Python Programming
Writing Programs

• Up to now, we’ve been writing single Python statements and running them at the

interactive command line. While that’s useful for learning about Python functions where

we can write many lines of Python code.

• Thus we turn to writing programs (also known as scripts). Programs are just text files

containing a collection of Python commands.

• When you run (or execute) a program, Python performs each statement in the file one after

the other.
Python Programming
Writing Programs

To write a new program in IDLE


1. Launch IDLE.
2. Choose File > New Window.
A blank editor window should pop up.
3. To test it, enter the following into it: print('Welcome to Python!')
4. Save your program by choosing File > Save. Save it in your Python programs folder with
the name welcome_to.py; the .py at the end indicates that this is a Python file.
5. Run your program by choosing Run > Run Module.
A Python shell should appear, and you should see
>>>
RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python36-32/welcome_to.py
Welcome to Python!
>>>

Running programs from the command line


C:\> cd C:\Users\Admin\AppData\Local\Programs\Python\Python36-32
C:\Users\Admin\AppData\Local\Programs\Python\Python36-32> python welcome_to.py
Welcome to Python!
Python Programming
Writing Programs

Compiling Source Code

We often refer to the statements inside a Python program as source code, and so a program
file is sometimes called a source code file, or source file.
All Python source code files end with the extension .py.

The Object code


When you run a .py file, Python automatically creates a corresponding .pyc file . A .pyc file
contains object code, or compiled code.
Object code is essentially a Python-specific language that represents the Python source code
in a way that is easier for the computer to run efficiently. It is not meant for humans to read,
and so most of the time you should just ignore the .pyc files that start to appear.
Python Programming
Writing Programs

Compiling Source Code

Python consists of three major components:

• An interpreter for running single statements;

• A compiler for converting .py files to .pyc files;

• A virtual machine for running .pyc files.

A Python program runs using a special piece of software called a virtual machine. This is

essentially a software simulation of a computer designed just to run Python, and it is part of

the reason why many .pyc files can run on different computer systems without any change.

Note that IDLE is not strictly part of Python; it is a separate application that sits on top of Python to make it easier to
use.
Python Programming
Writing Programs
First program: Reading Strings from the Keyboard
# name_py_program_example
name = input('What is your first name? ') .strip()
print('Hello ' + name.capitalize() + '!')
To run this in IDLE, open name.py in an IDLE window, and then to run it press F5 (or, equivalently, choose Run > Run
Module).
You should see this in the window that appears:
What is your first name? cenk
Hello Cenk!

# name_py_program_example A comment
This line calls the input function, which is the standard built-in function for reading strings
from the keyboard. When it runs, the prompt 'What is your name?' appears in the output
window, followed by a blinking cursor. The program waits until the user enters a
name = input('What is your string and presses Enter.
first name? ') .strip() The input function evaluates to whatever string the user enters, and so the variable name ends
up labeling the string that the user types in.
strip() function to remove any leading/trailing whitespace characters
Example: >>> ' oven '.strip()
'oven'

This line displays a greeting. The function name.capitalize() ensures that the first character of
print('Hello ' +
name.capitalize() + '!') the string is uppercase and the remaining characters are lower-case. This way, if the user
happens to enter a name that isn’t correctly capitalized, Python will correct it.

To see what functions are available for strings, type dir('') at IDLE’s interactive command line.
Python Programming
Writing Programs
Second program: Reading numbers from the keyboard
# age.py
age = input('How old are you today? ')
age10 = int(age) + 10
print('In 10 years you will be ' + str(age10) + ' years old.')

You should see this in the window that appears:


How old are you today? 34
In 10 years you will be 44 years old.

• Suppose the user types in 34 in response to this program.


• The variable age labels the string '34'—Python does not automatically convert strings that
look like numbers to integer or float values. If you want to do arithmetic with a string, you
must first convert it to a number using either int(s) (if you want an integer) or float(s) (if
you want a float).
• In the print statement, it’s necessary to convert the variable age10 (which labels an
integer) back into a string so that it can be printed. If you forget this conversion, Python
issues an error saying it can’t add numbers and strings.
Python Programming
Writing Programs

input function and eval function

>>> input('? ')


? 4*5+6
'4*5+6' In both cases (when using numbers or characters)
the input values are considered strings

>>> input('? ')


? abc
When the function eval is used; the inputs of character
'abc'
type are not allowed. Eval function is able to deal only
with numbers.
>>> eval(input('? '))
? 4*5+6
26
Python Programming
Writing Programs

Different Types of Numbers


Consider these four different values: 5, 5.0, '5', and '5.0'. While they look similar, they have
very different internal representations.
5 is an integer and can be used directly for arithmetic.
5.0 is a floating point number that can also be used for arithmetic, but it allows for digits after
the decimal place.
'5' and '5.0' are strings consisting of one and three characters, respectively. Strings are meant
for being displayed on the screen or for doing character-based operations (such as removing
whitespace or counting characters). Strings can’t be used to do numeric arithmetic. Of course,
strings can be used with concatenation, although the results might be a bit jarring at first.
For example:
>>> 3 * '5'
'555'
>>> 3 * '5.0'
'5.05.05.0'
Python Programming
Writing Programs

Printing Strings on the Screen

The print statement is the standard built-in function for printing strings to the screen. As we

will see, it is extremely flexible and has many useful features for formatting strings and

numbers in the right way.

You can pass any number of strings to print:

>>> print('jack', 'ate', 'no', 'fat')

jack ate no fat

By default, it prints out each string in the standard output window, separating the strings with

a space. You can easily change the string separator like this:

>>> print('jack', 'ate', 'no', 'fat',sep = '.')

jack.ate.no.fat
Python Programming
Writing Programs

Printing Strings on the Screen


By default, a printed string ends with a newline character: \n. A newline character causes the
cursor to move to the next line when the string is printed, and so, by default, you can’t print
anything on the same line after calling print:
# jack1.py
print('jack ate ')
print('no fat')
This prints two lines of text:
jack ate
no fat
To put all the text on a single line, you can specify the end character of the first line to be the
empty string:
# jack2.py
print('jack ate ', end = '')
print('no fat')
Python Programming
Writing Programs
Third program: This program asks the user how many coins of various types you have,
and then prints the total amount of money in pennies. The user has to give the number
of nickels, dimes, and quarters

# coins_short.py
n = int(input('Nickels? ')) # 1 nicle = 5 cents
d = int(input('Dimes? ')) # 1 dime = 10 cents
q = int(input('Quarters? ')) # 1 quarter = 25 cents
# calculate the total amount of money
total = 5 * n + 10 * d + 25 * q
# print the results
print() # prints a blank line
print(str(total) + ' cents')

You should see this in the window that appears:


Nickels? 5
Dimes? 4
Quarters? 3

140 cents

Indicating in comments what parts are for input, processing, and output is a good habit to get into. It helps clarify the different tasks your
program performs; and when we start writing functions, it provides a natural way of dividing up your programs into sensible functions.

You might also like