Note!
The window is too narrow to use Pythonlab.dev. Use a device with a keyboard!
Reference
Click on a function to read more.
Basics part 1
Syntax
Short description
break
break interrupts code that is repeated
Example
while True:
print('You are nice!')
answer = input('Should I stop saying that? Write yes in that case.')
if answer == 'yes':
break
Explanation
break interrupts code that is repeated. For example when while is used.
continue
continue interrupts a repetition and starts the next
Example
i = 0
while i < 100:
if i % 2 == 0: # continue with the next repetition if i is divisible by 2
continue
print(i,'is an odd number')
Explanation
continue interrupts the execution in the current repetition/iteration and continues with the next repetition. Used in while-statements and for-statements.
elif
elif is a combination of else and if
Example #1
temp = int(input('What is the temperature?'))
if temp > 20:
print('Warm and nice!')
elif temp > 0: #if temp <= 20 and temp > 0
print('Not very cold, but not so warm either.')
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
elif is only used after if. It is a combination of else and if, meaning ELSE (if the above is false) and IF (if the new condition is true). The condition for elif is only tested if the condition for if is false.
Syntax
elif condition:
condition
Required. Something that is True or False.
else
else can be used last in an if-statement
Example
age = int(input('How old are you?'))
if age >= 18:
print('You are an adult!')
else:
print('You are not an adult.')
Explanation
else is only used at the end of a block that starts with if, and the code under else is only executed if the condition for if is false.
float()
Converts to type float (decimal number)
Example
float('0.01') #converts the string '0.01' to 0.01
float(10) #converts the integer 10 to 10.0
Explanation
The function float() converts the argument to type float (decimal number). Usually, the argument is a string or an integer.
Syntax
float(number)
Argument
number
A number in the form of a string or an integer.
if
if controls the code to do different things depending on a condition
Example #1
number = 10
if number == 10:
print('The number is equal to 10.') #this will be printed
Example #2
number = int(input('Enter an integer'))
if number == 0:
print('You entered the number 0.')
elif number > 0:
print('You entered a positive number.')
else:
print('You entered a negative number.')
Explanation
if is used to control what the program does depending on a condition. If the condition is true, the code in the if-block is executed. To control
what happens if the condition is not true, elif and else can be used.
Syntax
if condition:
condition
Required. Something that is True or False.
input()
Receives input from the user
Example
answer = input('What is your name?') #The user's answer is saved in the variable answer
Explanation
The function input() allows the user to enter input into the program. It is possible to include text that describes what should be entered.
Syntax
input(prompt)
Argument
prompt
An optional text the user sees.
int()
Converts to type int (integer)
Example
int(42) #converts the string '42' to 42
int(3.94) #converts the decimal number 3.94 to 3
Explanation
The function int() converts the argument to type int (integer). Usually, the argument is a string or a decimal number.
Syntax
int(number)
Argument
number
A number in the form of a string or a decimal number.
print()
Prints text or the content of a variable to the screen
Example #1
print('Hello World') #prints "Hello World"
print(1+1) #prints the number 2
print(x) #prints the content of variable x
Example #2
print('Hello World', end='') #prints "Hello World" without a new line
Example #3
print('Hello','to','you') #Prints "Hello to you"
print('Hello','to','you',sep=' | ',end='!') #prints "Hello | to | you!" without a new line at the end.
Explanation
The function print() prints a string to the screen. Automatically tries to convert what is to be printed to text.
Syntax
print(*object, sep=' ', end='\n')
Argument
*object
Required. One or more objects to be printed. Separate objects with commas.
sep
Character to separate the objects being printed. Default is space.
end
Character that ends the text being printed. Default is "\n" - which means new line.
randint()
Generates a random integer
Example
from random import randint
roll = randint(1,6) #a random number 1-6
Explanation
The function randint() generates a random integer between two integer values a and b such that a <= N <= b. randint is in the random module.
Syntax
randint(a,b)
Argument
a
The smallest random number that can be generated.
b
The largest random number that can be generated.
round()
Rounds a number
Example #1
round(7.89) #rounds to 8
round(1.23) #rounds to 1
Example #2
round(1.23456,2) #rounds 1.23
round(1.23456,4) #rounds to 1.2346
Explanation
The function round() rounds a decimal number. By default to an integer, it is possible to set round() to round to an arbitrary number of decimals.
Syntax
round(number, decimalplaces = 0)
Argument
number
Required. The number to be rounded.
decimalplaces
Number of decimals the number should be rounded to. Default is 0.
str()
Converts to type string
Example #1
str(2.71) #converts the decimal number 2.71 to the string '2.71'
str(10) #converts the integer 10 to '10'
Example #2
age = 15
print('You are ' + str(age) + ' years old.')
Explanation
The function str() converts the argument to a string. Often the argument is an integer or a decimal number. It can also be significantly more complex data types that can be converted to strings.
Syntax
str(object)
Argument
object
An object that can be converted to a string.
while
while is used to repeat code
Example
n = int(input('How many numbers do you want to print?'))
i = 1
while i <= n:
print(i)
i = i + 1
Explanation
while repeats the code in the block as long as the condition is true.
Syntax
while condition:
condition
Required. Something that is True or False. Must become false at some point for the while-block to be exited.
The if statement
In this section you will learn
How to write an if statement
About elif and else
Simple if statements
Now we will learn how we can make the program run different parts of the code depending on different conditions.
Being able to control which code runs in different situations is fundamental in programming.
Think about what happens when you press the keyboard.
What happens then, of course, depends on which key you have pressed.
If (English: if) you have pressed ESC, something might be canceled, and if you press Enter, something completely different happens.
The syntax (how to write) for an if statement is if condition: where condition is a logical expression, i.e., true or false.
If the condition is true, the code under the if statement is executed; if the condition is false, the code is skipped. In Python, the code under if is indented in its own block
(see first section).
Example
A first if statement. Try changing the value of x and see what happens.
x = 10
if x == 10:
print('x is equal to 10')
print('End')
x = 10
if x == 10:
print('x is equal to 10')
print('End')
Example
We test if the user is named Darth Vader or Yoda and, if so, print a message. Note that Python is case-sensitive.
name = input('Enter your name')
if name == 'Darth Vader':
print('You are not kind.')
if name == 'Yoda':
print('You are very kind.')
print('Goodbye ' + name)
name = input('Enter your name')
if name == 'Darth Vader':
print('You are not kind.')
if name == 'Yoda':
print('You are very kind.')
print('Goodbye ' + name)
Write a program that asks the user for the outdoor temperature (integer). If the temperature is less than -10, print Stay inside.
If the temperature is greater than or equal to -10, print Go outside.
-- Output from your program will be here --
else
Sometimes it's good to run certain code if something is true (as we did with an if statement) and otherwise (English: else) run some other code.
You can use else to run code if the condition in the if statement is false.
An else cannot be used alone, but is always used in conjunction with if.
Example
A simple example of using else. Note that else is at the same indentation level as if.
name = input('What is your name?')
if name == 'Elsa':
print('I think your sister\'s name is Anna.')
else:
print('Your name is not Elsa.')
name = input('What is your name?')
if name == 'Elsa':
print('I think your sister\'s name is Anna.')
else:
print('Your name is not Elsa.')
Example
Another simple example of using else.
age = int(input('How old are you?'))
if age >= 18:
print('You are an adult!')
else:
print('You are under 18 years old.')
age = int(input('How old are you?'))
if age >= 18:
print('You are an adult!')
else:
print('You are under 18 years old.')
Read the code below and try to figure out what the program prints. Run the program after you answer and see if you were correct.
-- Output from your program will be here --
Question: What will the program print?
Feel the force!
You will find only what you bring in.
Do or do not. There is no try.
Great warrior. Wars not make one great.
Feel the force!
Great warrior. Wars not make one great.
Do or do not. There is no try.
You will find only what you bring in.
elif
Most programming languages have something called else if or elseif (Swedish: otherwise if).
In Python, the abbreviation elif is used instead.
Just like with else, elif is only used in conjunction with an if statement, and the program will only reach it if the condition in the if statement above is false.
The difference is that with elif, we write a new condition that must be true for the code block below to be executed.
You can use as many elif as you want in a row.
An if statement thus begins with if condition:, followed by none, one or more elif condition: and possibly ends with an else:.
Think of else as what happens if no conditions above are true.
Example
A menu using elif and else.
menu_choice = int( input('Make your choice:') )
if menu_choice == 1:
print('Pizza ordered.')
elif menu_choice == 2:
print('Hamburger ordered.')
elif menu_choice == 3:
print('Soup ordered.')
else:
print('Your choice is not valid.')
print('MENU')
print('1. Pizza\n2. Hamburger\n3. Soup')
menu_choice = int( input('Make your choice:') )
if menu_choice == 1:
print('Pizza ordered.')
elif menu_choice == 2:
print('Hamburger ordered.')
elif menu_choice == 3:
print('Soup ordered.')
else:
print('Your choice is not valid.')
Why not just use multiple if statements in a row?
With elif as above, the program executes only one code block (a print).
With multiple if statements, all that are true are executed, and there can be multiple blocks.
Your program should take an integer as input. If the user enters a negative number, the program should print Negative, if the number is positive, the program should print Positive, and otherwise Zero is printed.