0% found this document useful (0 votes)
543 views33 pages

Programming Essentials in Python Introduction To Python

This document provides an introduction to the Python programming language. It outlines some key concepts like compilation vs interpretation, data types, variables, input/output operations, and if statements. It also demonstrates basic Python syntax like print functions, literals, operators, and calculations. The goal is to teach programming fundamentals and get started with the Python environment.

Uploaded by

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

Programming Essentials in Python Introduction To Python

This document provides an introduction to the Python programming language. It outlines some key concepts like compilation vs interpretation, data types, variables, input/output operations, and if statements. It also demonstrates basic Python syntax like print functions, literals, operators, and calculations. The goal is to teach programming fundamentals and get started with the Python environment.

Uploaded by

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

Programming Essentials in Python

Introduction to Python
Supervisor Dr. Laki Sandor Instructor Dhulfiqar A Alwahab
lakis@inf.elte.hu aalwahab@inf.elte.hu

What you will learn


• The fundamentals of computer programming;
• Setting up your programming environment;
• Compilation vs. interpretation;
• Introduction to Python
• Data types , variables
• Basic input-output operations
• If statement
Introduction to Python
• Compilation vs. interpretation
Computer programming is the act of composing the selected programming language's
elements in the order that will cause the desired effect.
such a composition has to be correct in many senses:
• alphabetically - a program needs to be written in a recognizable script, such as
Roman, Cyrillic, etc.
• lexically - each programming language has its dictionary and you need to master it;
thankfully, it's much simpler and smaller than the dictionary of any natural language;
• syntactically - each language has its rules and they must be obeyed;
• semantically - the program has to make sense.
Introduction to Python

• Compilation vs. interpretation(cont.)


• There are two different ways of transforming a program from a high-
level programming language into machine language:
• COMPILATION - the source program is translated once (however, this
act must be repeated each time you modify the source code).
• INTERPRETATION - you (or any user of the code) can translate the
source program each time it has to be run; the program performing
this kind of transformation is called an interpreter.
Introduction to Python

• Who created Python?


Python was created by Guido van Rossum, born in 1956 in Haarlem, the Netherlands. Of
course, Guido van Rossum did not develop and evolve all the Python components himself.
• Python goals
In 1999, Guido van Rossum defined his goals for Python:
1. an easy and intuitive language just as powerful as
those of the major competitors;
2. open source, so anyone can contribute to its development;
3. code that is as understandable as plain English;
4. suitable for everyday tasks, allowing for short
development times.
Introduction to Python

Task 1
• Open newfile in pyhton and type
• Print (‘this is test 1 ’) --- what is the output ? Read it !
• Print (‘this is test 1 ’  what is the output ? Read it !
• Prin ( ‘this is the test 1 ’)  what is the output ? Read it !
Introduction to Python
As you can see, the first program
consists of the following parts:
• Hello, World!
• the word print;
print("Hello, World!") • an opening parenthesis;
• a quotation mark;
• a line of text: Hello, World!;
The print() function • another quotation mark;
• a closing parenthesis.
Where do the functions come from?
1. They may come from Python itself; ( built-in)
2. they may come from one or more of Python's add-ons named modules;
some of the modules come with Python, others may require separate
installation.
3. you can write them yourself, placing as many functions as you want and
need inside your program to make it simpler, clearer and more elegant.
Introduction to Python
• In spite of the number of needed/provided arguments, Python functions
strongly demand the presence of a pair of parentheses - opening and
closing ones, respectively.
• Arguments
 Does the print() function in our example have any arguments?
Introduction to Python
• LAB-1.1 ( 5 minutes)

• use the print() function to print the line Hello, Python! to the screen. Use double
quotes around the string;
• having done that, use the print() function again, but this time print your first name;
• remove the double quotes and run your code. Watch Python's reaction. What kind of
error is thrown?
• then, remove the parentheses, put back the double quotes, and run your code again.
What kind of error is thrown this time?
• experiment as much as you can. Change double quotes to single quotes, use multiple
print() functions on the same line, and then on different lines. See what happens.
Introduction to Python
• The print() function - instructions
• print("The itsy bitsy spider climbed up the waterspout.")
• print()
• print("Down came the rain and washed the spider out.")
Output will be
The itsy bitsy spider climbed up the waterspout.

Down came the rain and washed the spider out.


Introduction to Python
• The print() function - the escape and newline characters
• print("The itsy bitsy spider\nclimbed up the waterspout.")
• print()
• print("Down came the rain\nand washed the spider out.")
The itsy bitsy spider
The backslash (\) has a very special meaning when used inside strings – climbed up the waterspout.
this is called the escape character.
Down came the rain
How can you print only \ ? Is print(“\”) is right? and washed the spider out.
My-name-is-Monty-Python.

Introduction to Python
• The print() function - using multiple arguments
The itsy bitsy spider climbed up the waterspout.

print("The itsy bitsy spider" , "climbed up" , "the waterspout.")

• The print() function - the keyword arguments


print("My name is", "Python.", end=“ “ )
print("Monty Python.") My name is Python. Monty Python.

print("My", "name", "is", "Monty", "Python.", sep="-“ )


My-name-is-Monty-Python.
Introduction to Python

• The print() function - the keyword arguments


print("My", "name", "is", sep="_", end="*") My_name_is*Monty*Python.*

print("Monty", "Python.", sep="*", end="*\n")


Introduction to Python
• Literals
• A literal is data whose values are determined by the literal itself.
Example : 102 is litral but a is not.
print("2")  string
Print(2) integer
Integers
11111111 can be written as it or 111_111_111 (+ or -)
octal
0o123 is an octal number with a (decimal) value equal to 83  try print(0o123)
Hexadecimal
0x123 is a hexadecimal number with a (decimal) value equal to 291  try print (0x123)
Floats
0.4 can be written as .4 or 4.0 as 4.
3 x 108 can be written 3E8 ( E comes from exponent)
Introduction to Python

6.62607 x 10-34 will be 6.62607E-34


print(0.000000000000000000001)
will be 1e-22

Strings
Strings are used when you need to process text (like names of all kinds,
addresses, novels, etc.), not numbers.
I like "Monty Python"
print("I like \"Monty Python\"") print('I like "Monty Python"')

I'm Monty Python.


print('I\'m Monty Python.') print("I'm Monty Python.")
Introduction to Python
• Boolean values
What will be the output ? What type of literals are the following
two example
print(True > False)
print(True < False)
"Hello ", "007"
Write a one-line piece of code, using the print() function, as well
"1.5", 2.0, 528, False
as the newline and escape characters, to match the expected
result outputted on three lines.

"I'm"
""learning""
"""Python"""
Introduction to Python
exponentiation print(2 ** 3)=8 remainder print(14 % 4)=2
print(2 ** 3.)=8.0 (modulo) print(12 % 4.5)=3.0
• Python as a calculator print(2. ** 3)=8.0
print(2. ** 3.)=8.0
print(2+2)=4 multiplication print(2 * 3)=6 addition print(-4 - 4)=-8
print(2 * 3.)=6.0 print(4. - 8)=-4.0
Operators and their priorities print(2. * 3)=6.0
print(2. * 3.)=6.0
print(-1.1)=-
print(+2)=2
2+3*5
division print(6 / 3)=2.0
Operators and their bindings print(6 / 3.)=2.0
print(6. / 3)=2.0
print(6. / 3.)=2.0
print(9 % 6 % 2) (left binding)
integer division print(6 // 3)=2
print(2 ** 2 ** 3)(right binding) print(6 // 3.)=2.0
print(6. // 3)=2.0
print(6. // 3.)=2.0
Introduction to Python
Priority Operator
1 +, - unary
2 **
3 *, /, %
4 +, - binary

print(2 * 3 % 5)=1

print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)=10.0

print((2 ** 4), (2 * 4.), (2 * 4))= 16 8.0 8

print((-2 / 4), (2 / 4), (2 // 4), (-2 // 4))=-0.5 0.5 0 -1

print((2 % -4), (2 % 4), (2 ** 3 ** 2))= -2 2 512


Introduction to Python

• What are variables?


• Correct and incorrect variable names!
(keywords are not allowed ) !
var = 1 You can use the print() statement and
account_balance = 1000.0 combine text and variables using the +
client_name = 'John Doe' operator to output strings and variables,
print(var, account_balance, client_name) e.g.:
print(var) var = "3.7.1" print("Python version: " +
var)
Output
Python version: 3.7.1
var = 1 var = 1
print(Var) - error print(var)
var = var + 1
print(var)
Introduction to Python

•LAB 2
• Here is a short story:
• Once upon a time in Appleland, John had three apples, Mary had five apples, and Adam had six apples. They were all
very happy and lived for a long time. End of story.
• Your task is to:
• create the variables: john, mary, and adam;
• assign values to the variables. The values must be equal to the numbers of fruit possessed by John, Mary, and Adam
respectively;
• having stored the numbers in the variables, print the variables on one line, and separate each of them with a comma;
• now create a new variable named totalApples equal to addition of the three former variables.
• print the value stored in totalApples to the console;
• experiment with your code: create new variables, assign different values to them, and perform various arithmetic
operations on them (e.g., +, -, *, /, //, etc.). Try to print a string and an integer together on one line, e.g., "Total number
of apples:" and totalApples.
Introduction to Python
• Shortcut operators
x=x*2 x *= 2
sheep = sheep + 1 sheep += 1
i=i+2*j i += 2 * j
var = var / 2 var /= 2
rem = rem % 10 rem %= 10
j = j - (i + var + rem) j -= (i + var + rem)
x = x ** 2 x **= 2
Introduction to Python
• LAB 3
Scenario
• Miles and kilometers are units of length or distance. kilometers = 12.25
• Bearing in mind that 1 mile is equal to approximately 1.61 kilometers, miles = 7.38
complete the program in the editor so that it converts:
1. miles to kilometers; miles_to_kilometers = ###
2. kilometers to miles. kilometers_to_miles = ###
• Do not change anything in the existing code. Write your code in the
places indicated by ###. Test your program with the data we've print(miles, "miles is", round(miles_to_kilometers, 2),
provided in the source code. "kilometers")
• Pay particular attention to what is going on inside the print() function. print(kilometers, "kilometers is",
Analyze how we provide multiple arguments to the function, and how round(kilometers_to_miles, 2), "miles")
we output the expected data.
• Note that some of the arguments inside the print() function are strings
(e.g., "miles is", whereas some other are variables (e.g., miles).

Expected output
7.38 miles is 11.88 kilometers
12.25 kilometers is 7.61 miles
Introduction to Python
• LAB 4
• Scenario
• Take a look at the code in the editor: it reads a float x = # hardcode your test data here
value, puts it into a variable named x, and prints the x = float(x)
value of a variable named y. Your task is to complete
the code in order to evaluate the following expression: # write your code here
print("y =", y)
• 3x3 - 2x2 + 3x - 1
• The result should be assigned to y.
• Remember that classical algebraic notation likes to omit
the multiplication operator - you need to use it
explicitly. Note how we change data type to make sure
Sample input
that x is of type float.
x=0
• Keep your code clean and readable, and test it using the
data we've provided, each time assigning it to the x x=1
variable (by hardcoding it). Don't be discouraged by any x = -1
initial failures. Be persistent and inquisitive.
Expected Output
y = -1.0
y = 3.0
y = -9.0
Introduction to Python
• Check-point ( what is the output )
var = 2 # print("String #1")
var = 3 print("String #2")
print(var)
my_var # This is In Python, a comment is a piece of text that begins
m a multiline with a # (hash) sign and extends to the end of the line.
101 comment. #
averylongvariablename Example
m101 print("Hello!") # This program evaluates the hypotenuse c.
m 101
Del
del
a = '1' NOTE: If you'd like to quickly comment or uncomment
b = "1"
print(a + b) multiple lines of code, select the line(s) you wish to
a=6 modify and use the following keyboard shortcut: CTRL
b=3
a /= 2 * b
+ / (Windows) or CMD + / (Mac OS).
print(a)
Introduction to Python

• The input() function NOTE:


The result of the input() function is a string.
Example -1 Run this code in your PC.
print("Tell me anything...")
anything = input("Enter a number: ")
anything = input()
print("Hmm...", anything, "... Really?") something = anything ** 2.0
print(anything, "to the power of 2 is", something)
Example -2
anything = input("Tell me anything...")
print("Hmm...", anything, "...Really?")

Type casting is used to solve this problem


int() and float()
Example
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something)
Introduction to Python Example:
fnam = input("May I have your first name, please? ")
• String operators – introduction lnam = input("May I have your last name, please? ")
print("Thank you.")
• Concatenation print("\nYour name is " + fnam + " " + lnam + ".")

The + (plus) sign, when applied to two strings, becomes a concatenation operator:
string + string
• Replication
The * (asterisk) sign, when applied to a string and number (or a number and string,
as it remains commutative in this position) becomes a replication operator:
string * number
number * string Example 1, Example 2, run this code
print("+" + 10 * "-" + "+")
"James" * 3 gives "JamesJamesJames"
print(("|" + " " * 10 + "|\n") * 5, end="")
3 * "an" gives "ananan"
print("+" + 10 * "-" + "+")
5 * "2" (or "2" * 5) gives "22222" (not 10!)
Introduction to Python
• Type conversion: str()
convert a number into a string : str(number)
What is the output of the following snippet?
x = int(input("Enter a number: "))
# the user enters 2
print(x * "5")
______
Example
What is the expected output of the following
leg_a = float(input("Input first leg length: "))
snippet?
leg_b = float(input("Input second leg length: "))
x = input("Enter a number: ")
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))
# the user enters 2
print(type(x))
Introduction to Python
• LAB
Scenario
• Your task is to complete the code in order # input a float value for variable a here
to evaluate the results of four basic # input a float value for variable b here
arithmetic operations.
• The results have to be printed to the # output the result of addition here
console. # output the result of subtraction here
• You may not be able to protect the code # output the result of multiplication here
from a user who wants to divide by zero. # output the result of division here
That's okay, don't worry about it for now.
• Test your code - does it produce the results print("\nThat's all, folks!")
you expect?
• We won't show you any test data - that
would be too simple.
Introduction to Python
• LAB
Scenario
Your task is to prepare a simple code able to
evaluate the end time of a period of time,
given as a number of minutes (it could be hour = int(input("Starting time (hours): "))
arbitrarily large). The start time is given as a mins = int(input("Starting time (minutes): "))
pair of hours (0..23) and minutes (0..59). The dura = int(input("Event duration (minutes): "))
result has to be printed to the console.
For example, if an event starts at 12:17 and # put your code here
lasts 59 minutes, it will end at 13:16.
Don't worry about any imperfections in your
code - it's okay if it accepts an invalid time -
the most important thing is that the code
produce valid results for valid input data.
Test your code carefully. Hint: using the %
operator may be the key to success.
Introduction to Python
Comparison:
• equality operator (==) print(2==2) output will be true
• Inequality: the not equal to operator (!=) print(2!=2) output will be false
• greater than (>) print (2>2) output will be false
• greater than or equal to (≥) output only true or false
• less than or equal to (≤) output only true or false
Priority Operator
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
6 ==, !=
Introduction to Python
• Conditions and conditional execution
if true_or_not:
4spaces OR tab (not both) do_this_if_true
If –else Nested if-else statements
if true_or_false_condition: if the_weather_is_good: The elif statement
if sheep_counter >= 120: perform_if_condition_true if nice_restaurant_is_found: if the_weather_is_good
make_a_bed() else: have_lunch() go_for_a_walk()
take_a_shower() perform_if_condition_false
else: elif tickets_are_available:
sleep_and_dream() -------------------------------------------
if the_weather_is_good: eat_a_sandwich() go_to_the_theater()
feed_the_sheepdogs()
go_for_a_walk() else: elif table_is_available:
Error in indentation
have_fun() if tickets_are_available: go_for_lunch()
else: go_to_the_theater() else:
go_to_a_theater() else: play_chess_at_home()
enjoy_the_movie() go_shopping()
have_lunch()
Find the largest of three numbers

Introduction to Python # read three numbers


number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))

# We temporarily assume that the first number


# is the largest one.
Example: larger between two number # We will verify this soon.
# read two numbers largest_number = number1
number1 = int(input("Enter the first number: ")) # we check if the second number is larger than current
number2 = int(input("Enter the second number: ")) largest_number
# and update largest_number if needed
if number2 > largest_number:
# choose the larger number largest_number = number2
if number1 > number2:
larger_number = number1 # we check if the third number is larger than current
else: largest_number
# and update largest_number if needed
larger_number = number2 if number3 > largest_number:
largest_number = number3
# print the result
# print the result
print("The larger number is:", larger_number) print("The largest number is:", largest_number)
• LAB ( IMPORTANT!)
• Scenario
• Once upon a time there was a land - a land of milk and honey, inhabited income = float(input("Enter the annual income: "))
by happy and prosperous people. The people paid taxes, of course -
their happiness had limits. The most important tax, called the Personal
Income Tax (PIT for short) had to be paid once a year, and was #
evaluated using the following rule: # Put your code here.
• if the citizen's income was not higher than 85,528 thalers, the tax was #
equal to 18% of the income minus 556 thalers and 2 cents (this was the
so-called tax relief)
tax = round(tax, 0)
• if the income was higher than this amount, the tax was equal to 14,839 print("The tax is:", tax, "thalers")
thalers and 2 cents, plus 32% of the surplus over 85,528 thalers.
• Your task is to write a tax calculator.
• It should accept one floating-point value: the income.
• Next, it should print the calculated tax, rounded to full thalers. There's
a function named round() which will do the rounding for you - you'll Test Data
find it in the skeleton code in the editor.
Sample input: 10000
• Note: this happy country never returns money to its citizens. If the Expected output: The tax is: 1244.0 thalers
calculated tax is less than zero, it only means no tax at all (the tax is
equal to zero). Take this into consideration during your calculations. Sample input: 100000
• Look at the code in the editor - it only reads one input value and Expected output: The tax is: 19470.0 thalers
outputs a result, so you need to complete it with some smart
calculations. Sample input: 1000
Expected output: The tax is: 0.0 thalers
• Test your code using the data we've provided.
Sample input: -100
Expected output: The tax is: 0.0 thalers
Introduction to Python
• Congratulations!
You covered :
• the basic methods of formatting and outputting data offered by
Python, together with the primary kinds of data and numerical
operators, their mutual relations and bindings;
• the concept of variables and variable naming conventions;
• the assignment operator, the rules governing the building of
expressions;
• the inputting and converting of data;
• Use if statements

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy