Python Exam 1: Variables, Types, and Operators (10 mixed exercises)
Python Exam 1: Language Basics
Test your skills in Python fundamentals, including variables, printing, and working with strings and numbers.
Exercise 1
Print & Comments
Write a simple Python script:
- Use `print` to output "Hello, World!".
- Add a single-line comment that explains the code.
Solution
# This prints a greeting
print("Hello, World!")
Exercise 2
Variables
Define the following variables:
- A variable `x` with the value 5.
- A variable `y` with the value "John".
- Print the value of each variable.
Solution
x = 5
y = "John"
print(x)
print(y)
Exercise 3
Data Types
Identify data types:
- Define `x = 5`.
- Define `y = 2.8`.
- Define `z = "Hello"`.
- Use `type()` to print the type of each variable.
Solution
x = 5
y = 2.8
z = "Hello"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'str'>
Exercise 4
Casting
Convert between data types:
- Convert `2.8` to an integer.
- Convert `3` to a float.
- Convert `5` to a string.
Solution
x = int(2.8) # 2
y = float(3) # 3.0
z = str(5) # "5"
Exercise 5
Strings
Manipulate strings:
- You have `txt = " Hello World "`.
- Remove leading/trailing spaces with `strip`.
- Convert the text to uppercase with `upper`.
- Replace "H" with "J" using `replace`.
Solution
txt = " Hello World "
print(txt.strip()) # "Hello World"
print(txt.upper()) # " HELLO WORLD "
print(txt.replace("H", "J")) # " Jello World "
Exercise 6
Arithmetic Operators
Perform the following operations:
- Print the result of `10 + 5`.
- Print the result of `10 / 2`.
- Print the result of `2` raised to `3` (`**`).
- Print the integer division result of `15 // 2`.
Solution
print(10 + 5) # 15
print(10 / 2) # 5.0
print(2 ** 3) # 8
print(15 // 2) # 7
Exercise 7
User Input
Interact with the user:
- Ask the user for their name using `input()`.
- Print "Hello" followed by the entered name.
Solution
username = input("Enter username:")
print("Hello " + username)
Exercise 8
F-Strings
Combine variables with text:
- You have `age = 36`.
- Use an f-string to print "My name is John, and I am 36".
Solution
age = 36
txt = f"My name is John, and I am {age}"
print(txt)
Exercise 9
Booleans
Evaluate the following expressions:
- Print the result of `10 > 9`.
- Print the result of `10 == 9`.
- Print `bool("Hello")` (is a non-empty string True?).
Solution
print(10 > 9) # True
print(10 == 9) # False
print(bool("Hello")) # True
Exercise 10
Multiple Assignment
Assign multiple variables in one line:
- Assign "Orange", "Banana", "Cherry" to `x`, `y`, `z` respectively.
- Print each variable.
Solution
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)