Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

CS114 - Fundamental of Programming

Lecture 2: Variables

Dr. Nazia Perwaiz


nazia.perwaiz@seecs.edu.pk

vision.seecs.edu.pk
Recap - week1

• Printing
Contents

• User Input
• Comments
• Operators
• Variables
• Typecasting
• Strings
User Input
Getting input from users:
• The input function takes one argument which should be a question to
ask the user as a string (i.e. in double quotes)
• We can then assign the user’s response, to a variable to use later

4
User Input
• For consistency, the input command will always return a string even if
the user input is better suited for a different type
• Because of this, you may need to convert the variable storing the user
input to a different type

5
Comments
Comments are used:
• to explain Python code.
• to make the code more readable.
• to prevent execution when running code

Single-line comment: 
• Insert # for comment

Multi-line comment:

• Insert # for each line


• Add a multiline string (triple quotes “””) 
Operators
• Arithmetic Operators: used with numeric values to perform mathematical operations

https://www.tutorialspoint.com/python3/python_basic_operators.htm
Operators
• Assignment operators: used to assigning values to variables
Operators
• Comparison operators: compare the values on either side of them and decide the relation among
them
Variables
• Variables let you hold information to be used later in your code
• A variable is essentially a way of naming a particular value so we can
reference it later
• We assign a value to a variable using the equals symbol

• Here we made two variables called ‘name’ and ‘age’ with the values
“David” and 24, respectively
• Once you’ve created a variable it will continue to exist until you either
delete it or close your browser
Variables
• Once we have assigned a variable a value, we can use it in our code
by simply typing its name

• When Python sees `favourite_food` in the above example, it


remembers the last time `favourite_food` was assigned a value and
replaces it with this value
• Note, don’t write variable name name in quotes. Otherwise, Python will
just print their name without replacing it with the corresponding value
Variables
• Assign different values to multiple variables in one line
x, y, z = ”red", “green", “blue" Output:
print(x) red
print(y) green
print(z) blue

• Assign the same value to multiple variables in one line


x = y = z = ”red“ Output:
print(x) red
print(y) red
print(z) red

12
Manipulating Variables
1. Python will only remember the last value that you assigned to a
variable

• The act of giving a variable a new value is known as overwriting


Variable Types

• There are different types of variables in Python. Some we have seen:


• Strings (e.g. “Hello”)—text in quotes, called strings because they are
a string of characters
• Integers (e.g. 4)
• Floats (e.g. 3.14)—decimal numbers
• Booleans (True/False)

• Lists/Tuples/Sets
• Dictionaries
Variable Types

• We can examine the type of a variable by passing it as the input to the


type() function and then wrapping this in print to show the result
Variable Types

• Define the following variables

• What types do you think they will each have?


Variable TypeCasting

• TypeCasting: Explicitly specify the type of variable


• You can use the functions int(), float(), and str() to convert between
types

• Only if it is possible to make a conversion. Otherwise you’ll get an error


Variable TypeCasting

• Possible type conversions:

• int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (ONLY if string is a whole number)
• float() - constructs a float number from an integer literal, a float literal or a
string literal (only if string is a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
String Variables

• Multi-line String:
• Multi-line string are created using 03 double quotes “”” or 03 single quotes ‘’’

a = ""“ Python is widely used for web development, a = ""“ Python is widely used for web development,
scientific computing, data analysis, artificial scientific computing, data analysis, artificial
intelligence, and more. intelligence, and more.

This makes it a versatile language to learn and opens This makes it a versatile language to learn and
up many job opportunities.""" opens up many job opportunities."""
print(a) print(a)

Output:
Python is widely used for web development,
Output: scientific computing, data analysis, artificial
SyntaxError intelligence, and more.

This makes it a versatile language to learn and


opens up many job opportunities.
String Variables

• Concatenation:
• Create two string variables. What happens when we add them together
using `+` and print the result?
string_one = "I am reading" string_one = "I am reading"
string_two = " a great book!" string_two = " a great book!"
string_three = string_one + string_two string_three = string_one + string_two
print(string_three) x=4
y=string_three + x
print(y)
Output: I am reading a great book!
String Variables

• Replication:
• Create two string variables. What happens when we multiply a string by
an integer? [ >> Replicate the given string integer times]

print(“hello ” * 5) s = "hello"
print('s' * 5)

Output: Output:
hello hello hello hello hello sssss
Length of String
• The len() command is versatile (also work with lists, will see later)
• In fact, you can pass a string as the input to len() and it will return the
number of characters (including spaces) in that string

22
String Operations
• String concatenation +
• String replication *
• String starting index [0]
• String slicing [ ] and [:]

23
Variables – Self Practice 1
• Create two variables called ‘name’ and ‘age’, giving them the value of your
name and age respectively
• Get Python to print these in the following format:
Hi, my name is ______ and I am ______

• Print what your age will be in 5 years’ time


In five year’s time I will be _______

• Create a variable whose value is any number.


• Print that number,
• twice the number, and
• one less than the number.
• Now change the number. How did using variables make this process
easier?
24
Variables - Solutions
Code:

x = 20
print(x)
print(2*x)
print(x-1)

Output:

20
40
19

25
Variable - Self Practice 2

• Create a variable `pi` with the value 3.14 and a variable `radius` with
any value of your choosing
• Use these to print the circumference and area of a circle with radius
equal to the value of `radius`
• You may need the following formulae:

• use the round() function to round your answer to 2 decimal places. This
takes to inputs, a number to round and the number of decimal places to
round to (separated by a comma, remember!)
26
Variable - Solution

27
Manipulating Variables - Self Practice 3
• Run the following lines of code:

• What do you think the output of this will be?

28
Manipulating Variables - Solutions

• Not what you expected? Remember: the


equals symbol in Python means ‘assign the
value on the right to the variable on the left’.
It has nothing to do with the equals symbol
in maths.
• Here, the third line says ‘assign the variable
`y` the value of the variable `x`’. When
Python sees `x` it remembers that it has a
value of 2 so this becomes `y = 2`
• Changing `x` after makes no difference
since the last value `y` was set to was `2`,
regardless
29
User Input - Self Practice 4
• Use the input() function to ask the user how many of each animal there
are

• The input() function creates an input box immediately after the question
rather than on a new line. Try adding the characters ‘\r\n’ to the end of
your question to fix this

30
User Input - Solution

• Note, we wrapped the input() function in int() to convert the input to an


integer
31

You might also like