Skip to the content.

Back to Tutorial Index
Updated 9-21-2020

Python Tutorial 1

Accessing Python; Values, Variables and Functions


Prelude: Hello World

In the programming tradition, we must begin with the following program:

print("Hello, World!")
> Hello, World!

We can run this code at least three ways


Part I: Value types

Python has three basic types of values:


Strings

Strings are sequences of characters that are interpreted as text

Strings are defined using quotation marks (“ or ‘)

"A string can include letters, numbers, or other characters"

'But be careful. Numbers that are represented as strings (like 9)'
'can not be added, subtracted, etc.'

Integers

Integers are whole numbers (i.e., have no decimal places)

Integers can be added, subtracted, multiplied, and divided.

#these are integers:
1
2
3
4

Floats

Floats are numbers that have decimal places

When integers are divided, they are converted to floats

#these are floats:
1.234
2.0
6.789

Part 2: Defining Variables

Defining variables is quite easy in python.

They can be strings, integers, floats (and a variety of other structures)

a = "this is a string"
b = 9
c = 3.2
what will happen when we run the following line of code?
b + c
> 12.2
Important functions

Functions are called (used) via the following syntax:
function(arguments)

Commonly used functions include:

Important Methods

Functions use objects to complete tasks.

Methods are similar to functions, but complete operations on objects, which often changes them.

Methods tend to be specific to particular object types.

Some important string methods include:

Combining methods and functions

So far, we have used very simple Python statements that include simple variable assignment, sometimes using a single function or method. Python statements, however, can be combined in a single line, and methods and functions can both be used.

#print the result of lowering and splitting a string
print("This is a STRING".lower().split())
> ['this', 'is', 'a', 'string']
#print the length of the list that is a result of lowering and splitting a string
print(len("This is a STRING".lower().split()))
> 4

Exercises

  1. Assign the following sentence to a variable called string_sent : Rock climbing and conducting corpus analyses in Python are my favorite activities.
  2. Write a statement that prints the number of characters in string_sent.
  3. Create a version of string_sent that is a list of words and assign it to a variable called list_sent.
  4. Write a statement that prints the number of words in string_sent.
  5. Assign the average number of characters per word to a variable called av_chars. (To get the average number of characters per word, divide the number of characters in the sentence by the number of words in the sentence).
  6. Write a statement that prints the average number of characters per word as a string.

Next up…