0% found this document useful (0 votes)
39 views

Variables and Data Types

This document discusses programming concepts in Python including variables, data types, operators, and strings. It provides examples of integer, float, string, and boolean data types in Python. The document also demonstrates arithmetic, relational, and logical operators. Key concepts covered include variable naming rules, string manipulation operators, and converting between data types for user input and output. Classwork problems are provided as examples for length and temperature conversions.

Uploaded by

Osha Al Mansoori
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Variables and Data Types

This document discusses programming concepts in Python including variables, data types, operators, and strings. It provides examples of integer, float, string, and boolean data types in Python. The document also demonstrates arithmetic, relational, and logical operators. Key concepts covered include variable naming rules, string manipulation operators, and converting between data types for user input and output. Classwork problems are provided as examples for length and temperature conversions.

Uploaded by

Osha Al Mansoori
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

12/09/2021

1 Introduction to Programming and Problem Solving


SWE-225
2 Topics of Discussion
‣ Variables and Data Types
‣ Basic Data Types in Python

‣ Operators
‣ Arithmetic Operators
‣ Relational Operators
‣ Logical Operators

‣ String Manipulation
3 Variables and Data Types
Integer, Float, String, and Boolean
4 Keywords
Keywords are the reserved words in Python.
Keywords cannot be used as variable names.
They are used to define the syntax and structure of the Python
language.
In Python, keywords are case sensitive.
5 Identifiers
‣ An Identifier is the name used for creating variables (functions,
classes, etc.). Identifiers help to differentiate one entity from
another.
‣ Rules for creating Identifiers in Python
1. Identifiers can be a combination of letters in
‣ lowercase (a to z) or
‣ uppercase (A to Z) or
‣ digits (0 to 9) or
‣ an underscore ( _ ).
2. An identifier cannot start with a digit.
‣ 1variable is invalid, but
‣ variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
6 Variables
‣ In the following algorithm there are two variable names
‣ number

1
6
‣ In the following algorithm there are two variable names
‣ number
‣ square
‣ Algorithm
1. Start
2. number = 3
3. square = number * number
4. Write square
5. Stop
7 Variables and Data Types
‣ As discussed, Variables are reserved memory locations to store
data (values).
‣ When a variable is created, space is reserved in memory.

‣ But, how much memory is reserved?
‣ This would depend on the type of data (or data type) that would
be stored in the variable
‣ The type of data could be numbers, words, or a combination

‣ Therefore, the program needs to tell the computer the data type of
a variable, so that
‣ the computer can allocate sufficient memory and
‣ monitor the type of data that is stored in the reserved memory
location.

‣ Python variables do not need explicit declaration to reserve
memory space.
‣ The declaration happens automatically when you assign a value
to a variable.
‣ The equal sign (=) is used to assign values to variables.
8 Basic Data Types
‣ The data stored in memory can be of many types.
‣ For example,
‣ a person's age is stored as a numeric value
‣ the address is stored as alphanumeric characters (i.e.
numbers and alphabets) .

‣ Python has the following basic data types
‣ Numbers :int, float ,complex
‣ String: set of characters

9
‣ Numbers :int, float ,complex
‣ String: set of characters
‣ Boolean: true and false
‣ List
‣ Tuple
‣ Dictionary
9 Numbers
‣ Python supports three numerical types
‣ int (integers)( whole numbers)
‣ float (floating point real numbers) ( decimal numbers)
‣ complex (complex numbers). ( with variable )
‣ Examples
10 Class Work
1 ‣ Write a program that asks the user for length expressed in Feet.
Your program must convert and display the length in Meters.
2 ‣ Algorithm
‣ Start
‣ Write “Enter length in Feet: “
‣ Read lenFeet
‣ lenMeter = lenFeet * 0.3048
‣ Write “The length in Meter is: “ + lenMeter
‣ Stop
Python:
Feet = int(input("enter the length:"))
lm= feet*0.348
print(" the length in meter is" ,lm)

11 Class Work
# Reading user input
# Length Conversion

# User input lengthInFeet is read as a string


def main():
lengthInFeet = input("Enter length in feet: ")

# lengthInFeet is converted to a float for calculation

lengthInMeters = float(lengthInFeet) * 0.3048


# lengthInMeters is converted to string for printing
lengthInMeters = float(lengthInFeet) * 0.3048
# lengthInMeters is converted to string for printing
print("The length in Meter is: " + str(lengthInMeters)) #
lengthmeter is converted to string
print(“the length is Meter is: lengthMeter)
a=“bc”
print(“the length is Meter is” + a)

main()
int(nameOFvariable)
Float(nameOf varibale)
Str(name of variable)
12 Class Work
‣ Write a program that asks the user for an amount of money in
Dirhams. Your program must convert and display the amount in
US Dollars.
‣ Python:
‣ money =float(input("enter the amount in dirhms" ))
dollars= money/0.3
print("The amount in dirham is:", dollars)
‣ Output:
‣ enter the amount in dirhms456
‣ The amount in dirham is: 1520.0

13 Class Work
‣ The formula for converting temperature in Degree Celsius (C) to
Fahrenheit (F) is as follows:
F = 9/5 x C + 32
‣ Write a Python program to ask the user for the temperature in
Degree Celsius and convert it to Fahrenheit.
‣ Display the result with proper remarks
‣ Ensure that comments are included in the program
‣ Verify the results
Python:
temp=float (input("enter the tempreture"))
F = 9/5 * temp+ 32
print("the temp in F is", F)
Output:
enter the tempreture 90
the temp in F is 194.0
14
1

2
enter the tempreture 90
the temp in F is 194.0
14 Strings
1 ‣ Strings are identified as a contiguous set of characters
represented in a pair of quotation marks.
‣ Python allows for either pairs of single or double quotes.
2 # Data Type - Strings
def main():
string1 = "Hello World!"
print (string1) # Prints the complete string

string1 = "123456" when I add “” the number inside are


characters not number
print (string1) # Prints the complete string

string1 = "AED 230.50"


print (string1) # Prints the complete string

string1 = "Today we learned about strings"


print (string1) # Prints the complete string

main()
15 Strings
1 ‣ In Python, subsets of strings can be taken using the slice operator
‣ [ ] and [:]
‣ Indexes start at 0
2 # Data Type - Strings
def main():
string1 = "Hello World!" space between letters is counted as an
index

firstChar = string1[0]
print (firstChar) # Prints first character of the string

secondChar = string1[1:2]
print(secondChar) # Prints second character of the string
print (string1[2:5]) # Prints characters starting from 3rd to 5th
print (string1[2:]) # Prints starting from 3rd character to the end
print (string1[-1]) # Prints the last character of the string

16

17
print (string1[-1]) # Prints the last character of the string

main()
16 Class Work
‣ Write a Python program to ask the user to enter a string and then
print the last character of the string that the user entered.
17 Strings
1 ‣ The plus (+) sign is a string concatenation operator.
2 # Data Type - Strings
def main():
string1 = "College of"
string2 = "Technological"
string3 = "Innovation"

# Here we print to concatenated string


print (string1 + " " + string2 + " " + string3)

main()
18 Strings
1 ‣ The comma (,) is another string concatenation operator.
2 # Data Type - Strings
def main():
string1 = "College of"
string2 = "Technological"
string3 = "Innovation"

# Here we print to concatenated string


print (string1, string2, string3)

main()
19 Strings
1 The asterisk (*) sign is the string repetition operator.
2 # Data Type - Strings
def main():
string1 = "Hello World!"

# Prints string two times

print (string1 * 2)
print (string1 * 2)

# Prints string once and concatenates


# with the string printed two times
print (string1 + string1 * 2)

main()
20 Boolean
1 ‣ The boolean data type, is used to represent truth values i.e. True
and False.
‣ The two truth states can be assigned to variables and can also be
used to evaluate expressions.
‣ For example:
‣ Is 45 > 35? The answer would be: True
‣ Is 89 < 79? The answer would be: False
2 # Data Type – Boolean
def main():
# Boolean values

zero = False
one = True
print (zero)
print (one)

main()
21 Operators
Basic Operators in Python
22 Arithmetic Operators
1 ‣ Basic arithmetic operations:

+, -, *, /, and ** (exponentiation)

‣ The operators can be used with parentheses to force the order of
operations away from normal operator precedence.
2 # Arithmetic Operators
def main():
# basic arithmetic operators
2

# basic arithmetic operators

print (5+5)
print (90-45)
print (7*2)
print (7/2)

# use of parenthesis in arithmetic operations

print(2+3*4)
print((2+3)*4)

# power operations
print(2**10)
print(2**100)

main()
23 Operator Precedence
‣ To evaluate expressions with multiple operators, the precedence
of operators are used




‣ Operators in 1 have a higher precedence than operators in 2
‣ When operators have the same level of precedence, operations
are performed from left to right
‣ Evaluate result in the following expressions (on paper) then verify
using Python:
‣ result = 3 + 4 * 5
‣ result = 3 * (7 – 6) + 2 * 5 / 4 + 6
‣ result =7.0 + 3 * 8 + 2 / 10
24 Arithmetic Operators
# Arithmetic Operators

def main():
# division operations
print(6/3)
print(7/3)
print(7//3) # integer division
print(7/3)
print(7//3) # integer division

print(3/6)
print(3//6) # integer division

# modulus (remainder) operation


print(7%3)
print(3%6)

main()
25 Class Work
‣ A box of cookies can hold 24 cookies and a container can hold 75
boxes of cookies. Write a program that prompts the user to enter
the total number of cookies. The program then outputs the number
of boxes and the number of containers to ship the cookies. Note
that each box must contain the specified number of cookies and
each container must contain the specified number of boxes. If the
last box of cookies contains less than the number of specified
cookies, you can discard it, and output the number of leftover
cookies. Similarly, if the last container contains less than the
number of specified boxes, you can discard it, and output the
number of leftover boxes.
26 Relational Operators
1 ‣ Relational operators are used to compare values
‣ The result of a comparison is always a truth value (True or False)
2 # Relational Operators
def main():
result = (56 > 55)
print("Greater Than:", result)
result = (56<55)
print ("Less Than:", result)
result = (56 == 55)
print("Equal To:", result)
result = (56!=55)
print ("Not Equal To:", result)

main()
27 Logical Operators
1 ‣ The Logical operators are:

2
27 Logical Operators
1 ‣ The Logical operators are:
‣ and
‣ or
‣ not
‣ Relational and logical operators can be combined to result in truth
values, True or False.
2 # Logical Operators
def main():
x = True
y = False

# Output: x and y is False


print('x and y is', x and y)

# Output: x or y is True
print('x or y is', x or y)

# Output: not x is False


print('not x is', not x)

main()
28 Example
# Logical operators and operations

def main():
print(False and True) # result is False
print((55>56) and (55==55)) # result is False

print(False and False)


print((55>56) and (55!=55)) # result is False

print (True and True)


print ((56>55) and (56==56)) # result is True

# not operation

zero = False
one = True
print(not zero) # result is True

29
30

one = True
print(not zero) # result is True

print (not one) # result is False

31 main()
29 Assignment Operators
30 Class work
‣ Suppose x, y, and z are variables and x=2, y=5, and z=6. What is
the output of each of the following statements?
32 a. print("x = " + str(x) + ", y = " + str(y) + ", z = " + str(z))
b. print("x + y = " + str(x + y))
c. print("Sum of "+ str(x) + " and "+ str(z) + " is "+ str(x+z))
d. print("z / x = " + str(z / x))
e. print("2 times " + str(x) + " = " + str(2 * x))
33
31 Class work
‣ Write a program that prompts the user to enter the capacity, in
litres, of an automobile’s fuel tank and the kilometres per litres the
automobile can be driven. The program then outputs the number
of kilometres the automobile can be driven without refuelling.
32 Class work
‣ Write a Python program that prompts the user to input the elapsed
time for an event in seconds. The program then outputs the
elapsed time in hours, minutes, and seconds. (For example, if the
elapsed time the
d. Outputs is 9630
profitseconds, then the
for producing milkoutput is 2:40:30.)
33
34 More on Strings
String Manipulations
35 String Manipulation
1 ‣ Python uses some built-in methods to manipulate strings
‣ It is very beneficial to know and use these while programming
2 # String Manipulation
def main():
word = "Hello World"
# determine the length of the string

print(len(word))
34

main()
35
36
1

2
main()
36 String Manipulation
# String Manipulation
def main():
word = "Hello World"
print(word.count('l')) # count how many times l is in the string
print(word.count(' ')) # count the spaces is in the string
print(word.find("W")) # location of the character W in the string
print(word.index("World")) # find the location of the letters World
in the string

print(word.replace("Hello", "Salam Aleykoum")) # replace word

print(word.upper()) # change to upper case


print(word.lower()) # change to lower case
print(word.title()) # change to camel case
print(word.capitalize()) # change first letter to upper case
print(word.swapcase()) # swaps cases

print(word.isalnum()) # test if all char are alphanumeric


print(word.isalpha()) # test if all char in the string are alphabetic
print(word.isdigit()) # test if string contains digits
print(word.istitle()) # test if string contains title words
print(word.isupper()) # test if string contains upper case
print(word.islower()) # test if string contains lower case
print(word.isspace()) # test if string contains spaces
print(word.startswith('H')) # test if string starts with H
print(word.endswith('H')) # test if string ends with H

main()
37 String Manipulation
# String Manipulation
def main():
word = "Hello World"

print(word[0]) # get first char of the word


print(word[0:1]) # get one char of the word (same as above)
print(word[0:1]) # get one char of the word (same as above)

print(word[0:3]) # get the first three char


print(word[:3]) # get the first three char

print(word[-3:]) # get the last three char


print(word[3:]) # get all but the three first char
print(word[:-3]) # get all but the three last character

main()
38 In Summary
‣ Keywords
‣ Identifiers
‣ Variables
‣ Reserving memory space and good variable names
‣ Data Types
‣ Numbers, Strings, Boolean
‣ Operators
‣ Arithmetic Operators
‣ Relational Operators
‣ Logical Operators
‣ String Manipulations

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