• Show all results for " "

Variables and Assignment Statements Quiz

Variables and Assignment Statements Quiz

More actions.

  • PDF Questions
  • Make a copy

Questions and Answers

What does the left-hand side (lhs) of an assignment statement consist of.

  • A variable (correct)
  • An expression
  • A comparison operator

Which data type is associated with a whole number without a fractional part?

  • Integer (correct)

What does the '=' sign do in an assignment statement?

  • Increments the variable by 1
  • Copies the value on the right side into the variable on the left side (correct)
  • Multiplies the two values
  • Compares two values

If an existing variable is assigned a new value, what happens?

<p>The previous contents of the variable are cleared</p> Signup and view all the answers

What happens when executing the assignment: 'cansPerPack = cansPerPack + 2'?

<p>Adds 2 to cansPerPack</p> Signup and view all the answers

What is not a data type mentioned in the text?

<p>&quot;Alice&quot;</p> Signup and view all the answers

Which of the following is NOT a valid variable name in Python?

<p>2morrow</p> Signup and view all the answers

In Python, what is the importance of using descriptive variable names?

<p>It improves code readability and understanding</p> Signup and view all the answers

What is the purpose of using named constants in Python?

<p>To explain numerical values used in calculations</p> Signup and view all the answers

Why is it customary to use all UPPER_CASE letters for constants in Python?

<p>To make constants easier to identify in the code</p> Signup and view all the answers

Which variable name is more self-descriptive?

<p>canVolume = 0.35</p> Signup and view all the answers

What can happen if a programmer does not use descriptive variable names in Python?

<p>Other programmers will not be able to understand the code</p> Signup and view all the answers

What is the correct syntax for naming variables in Python?

<p>Variable names must start with a letter or underscore, and can contain letters, digits, and underscores</p> Signup and view all the answers

Which of the following is an example of a floating-point number in Python?

<p>0.5</p> Signup and view all the answers

What is the term used for values like 6 or 0.355 that occur in a Python program?

<p>Number literals</p> Signup and view all the answers

Which of the following is NOT allowed when naming variables in Python?

<p>Including spaces in variable names</p> Signup and view all the answers

What will happen if a variable is assigned different data types at different points in a program in Python?

<p>It will take the data type of the last assignment without issue</p> Signup and view all the answers

Which statement correctly describes the naming of variables in Python?

<p>'canVolume' is preferred over 'cv'</p> Signup and view all the answers

Study Notes

Variables and data types.

  • A variable is defined and initialized using the assignment statement (=) and the data type is associated with the value, not the variable.
  • There are three types of data: whole numbers (integers), numbers with fractional parts (floats), and sequences of characters (strings).
  • Examples of integers: -7, 6, 24
  • Examples of floats: 8.88, -9.4, 1E6, 2.96E-2
  • Examples of strings: "Bob"

Updating a Variable

  • If an existing variable is assigned a new value, the new value replaces the previous contents of the variable.
  • Example: cansPerPack = 6 then cansPerPack = 8 updates the value to 8.
  • Calculate the right-hand side of the assignment.
  • Store the result in the variable on the left side.

Number Types in Python

  • Integers: whole numbers without fractions, e.g. 6, -32
  • Floats: used when a fractional part is required, e.g. 0.5, 1.0, -9.4
  • Number literals: values that occur in a Python program, e.g. 6, 0.355

Naming Variables

  • Variable names should describe the purpose of the variable, e.g. canVolume instead of cv .
  • Must start with a letter or underscore (_)
  • Can include letters, digits, or underscore, but no other symbols or spaces
  • Case sensitive, e.g. canVolume and canvolume are different
  • Should not use reserved Python words (see Appendix C)
  • A constant is a variable whose value should not be changed after assignment.
  • Good practice to use all caps when naming constants, e.g. BOTTLE_VOLUME = 2.0 .
  • Named constants can explain numerical values used in calculations, making code clearer.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Description

Test your knowledge on variables, assignment statements, and expressions in programming. Learn about defining and initializing variables, using the assignment operator, and differentiating between the left-hand side and right-hand side of an assignment statement.

More Quizzes Like This

Primitive Data Types and Operations I Quiz

Primitive Data Types and Operations I Quiz

EffusiveWetland avatar

Variables and Data Types: Understanding Identifiers and Assignment Ope...

LuminousFluorine avatar

C Program: Adding Two Integers Quiz

y88mi avatar

Programming Variables Assignment Quiz

RewardingIndianArt avatar

Upgrade to continue

Today's Special Offer

Save an additional 20% with coupon: SAVE20

Upgrade to a paid plan to continue

Trusted by top students and educators worldwide

Stanford

We are constantly improving Quizgecko and would love to hear your feedback. You can also submit feature requests here: feature requests.

Create your free account

By continuing, you agree to Quizgecko's Terms of Service and Privacy Policy .

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

Advertisement

Home » Python

Python Variables MCQs

Python Variables MCQs : This section contains multiple-choice questions and answers on Python Variables. These MCQs are written for beginners as well as advanced, practice these MCQs to enhance and test the knowledge of Python Variables.

List of Python Variables MCQs

1. What are variables?

  • Variables are used to identify the module, class i.e., entity
  • Variables are the names we used to store the values
  • Variables are special inbuilt names

Answer: B) Variables are the names we used to store the values.

Explanation:

Variables are the names we used to store the values; these are the user-defined names that are used to assign the values.

Discuss this Question

2. Can you include digits in defining a variable name?

Answer: A) Yes

Yes, variable names can include digits. Variables can include the group of characters and numbers.

3. Are variables names case-sensitive?

Yes, variable names are case-sensitive. A and a are two different variables.

4. What are identifiers?

  • Identifiers are used to identify the module, class i.e., entity
  • Identifiers are the names we used to store the values
  • Identifiers are special inbuilt names

Answer: A) Identifiers are used to identify the module, class i.e., entity.

Identifiers are used to identify the module, class i.e., entity.

5. Can you include special characters as variable names?

Answer: B) No

No, variable names cannot contain special characters.

6. Which of the following is the valid variable name?

  • True="hello"
  • For="hello"
  • Else="hello"

Answer: B) A="hello"

Among, all the given variables only option b is valid as other names are also keywords.

7. What are keywords?

  • keywords are used to identify the module, class i.e., entity
  • keywords are the names we used to store the values
  • keywords are the special inbuilt names

Answer: C) keywords are the special inbuilt names.

Keywords are special inbuilt names.

8. Can you make keywords as variable names?

Keywords cannot be used as variable names. As keywords are the in-built names and if you will use them as the variable name you will get the error.

9. Which of the following is an invalid variable name?

  • 100_ = 1000

Answer: B) 100_ = 1000

A variable name cannot start from a digit. It can start from the underscore.

10. How can you assign one value to different variables?

  • a, b, c = 100
  • a = b = c = 100
  • a = b = c == 100

Answer: B) a = b = c = 100

a = b = c = 100 , this is how you can assign a single value to multiple variables.

11. Check whether the given statement is correct or not

a, b, c = 10, 12, 12 it is one of the methods to assign three different variables to three different values in a single line of code.

12. How many types of variables are there In Python

Answer: D) 2

In Python, there are two types of variables local variables and global variables.

13. ____ variable is the variable that is stored inside the function.

Answer: A) Local

In Python, the Local variable is the type of variable which are stored inside the function.

14. Can you use a local variable outside the function?

  • Only in the special case

Answer: B) Java

In Python, Local variables cannot be used outside the function, if you will use them it will show you the name error.

15. ____ variables are the variables that can be used in the entire program.

Answer: A) Global

In Python, global variables are the variables that can be used all over the program.

16. Which keyword is used to assign a local variable?

  • No, it has no keyword

Answer: C) No, it has no keyword.

In Python, Local variables are assigned directly no specified keywords are used with them.

17. Which keyword is used to assign a global variable?

Answer: A) global

In Python, the global keyword is used to define a global variable if you are making a global variable inside some function, else you don't require any keyword.

18. Can you delete the variable during a program?

In Python, you can easily delete the variable during a program, (if you don't want them).

19. Which keyword is used to delete the variable?

Answer: C) del

In Python, the del keyword is used to delete the variable during a program.

20. ____ are the smallest unit inside a program and can be defined as reserved words and each word in a statement?

  • Preprocessor

Answer: D) Tokens

Tokens are the smallest unit inside a program and can be defined as reserved words and each word in a statement

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

Java Guides

Java Guides

Search this blog, java variables quiz - mcq - multiple choice questions.

Java is one of the most popular programming languages in the world. If you're a beginner, it's crucial to understand the fundamentals of Java, and variables are a great place to start. Test your knowledge with this Java Variables Quiz consisting of 10 multiple-choice questions.

Each question is followed by the correct answer and an explanation to help reinforce your knowledge.

1. Which of the following is a valid variable declaration in Java?

Explanation:.

In Java, variable names cannot begin with numbers (option a), cannot have single quotes (option c), and type names are case-sensitive, meaning string is incorrect, it should be String (option d).

2. Which data type is used to store a single character in Java?

In Java, the char data type is used to store a single character.

3. How many bytes does an int data type occupy in Java?

In Java, an int data type occupies 4 bytes.

4. Which of the following is the correct way to declare multiple variables of the same type?

All the given options are valid ways to declare multiple variables in Java.

5. Which keyword in Java is used for constant variables?

In Java, the final keyword is used to declare constant variables.

6. What will be the default value of an int variable if not initialized in a class?

If an int variable is a member of a class and is not initialized, its default value is 0.

7. Which of the following is a valid variable name in Java?

Variable names in Java can contain letters, digits, underscores, and dollar signs. They cannot start with a digit or contain Java-reserved words like float.

8. The boolean data type in Java can have values:

The boolean data type in Java can only have the values true or false .

9. Which data type can be used to store large decimal numbers in Java?

The double data type is used to store large decimal numbers in Java.

This quiz should give beginners a basic understanding of Java variables. If you got all the answers correct, well done! If not, don't worry; practice makes perfect. Keep studying and practicing!

Related Java and Advanced Java Tutorials/Guides

Related quizzes:, post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

logo

Have an account?

Suggestions for you See more

Quiz image

Computer Hardware

9th -  12th  , hardware & software, 6th -  7th  , computer basics, 6th -  8th  , 50.1k plays, 5th -  8th  , 15.1k plays, 7th -  8th  , parts of a computer, kg -  1st  , university  .

pencil-icon

Variables and Assignments

User image

10 questions

Player avatar

Introducing new   Paper mode

No student devices needed.   Know more

The variable age is to be used to represent a person’s age, in years. Which of the following is the most appropriate data type for age ?

The variable is Open is to be used to indicate whether or not a store is currently open. Which of the following is the most appropriate data type for isOpen ?

Consider the following code segment.

What is the value of r as a result of executing the code segment?

What are the values of first and second as a result of executing the code segment?

The value of first is true, and the value of second is true.

The value of first is true, and the value of second is false.

The value of first is false, and the value of second is true.

The value of first is false, and the value of second is false.

Which of the following is a benefit of using a list as a data abstraction in a program?

Lists often allow their size to be easily updated to hold as many data values as needed.

Lists convert all elements to strings so that they can be inspected character-by-character.

Lists prevent duplicate data values from appearing in the list.

Lists are used to store all input data so that there is a running record of all user input.

A programmer has a need to round many numeric values to the nearest integer. Which of the following best explains the benefit of using a list as a data abstraction in this situation?

Keeping the numeric values in a list makes it easier to round a number to the nearest integer.

Keeping the numeric values in a list makes it easier to apply the same computation to every data element.

Keeping the numeric values in a list makes it easier to prevent a program from unintentionally changing the value of a variable.

Keeping the numeric values in a list makes it easier to prevent a program from attempting to access an index beyond the length of the list.

Assume that both lists and strings are indexed starting with index 1.

The list wordList has the following contents.

["abc", "def", "ghi", "jkl"]

Let myWord be the element at index 3 of wordList. Let myChar be the character at index 2 of myWord. What is the value of myChar ?

What are the contents of yourList after the code segment is executed?

[10, 30, 50, 70]

[20, 40, 60, 80]

[10, 30, 50, 70, 20, 40, 60, 80]

[20, 40, 60, 80, 10, 30, 50, 70]

Item 5Consider the following code segment.

firstList ← ["guitar", "drums", "bass"]

secondList ← ["flute", "violin"]

thirdList ← [ ]

thirdList ← firstList

firstList ← secondList

secondList ← thirdList

What are the contents of secondList after the code segment is executed?

["guitar", "drums", "bass"]

["flute", "violin"]

["flute", "violin", "guitar", "drums", "bass"]

The list wordList contains a list of 10 string values. Which of the following is a valid index for the list?

Explore all questions with a free account

Google Logo

Continue with email

Continue with phone

Search Tutorials

Java variables mcq - multiple choice questions and answers, q. what is the purpose of a variable in java, q. what is the data type of the variable "x" in the following code snippet: int x = 5;, q. which of the following is not a valid variable name in java, q. what is the default value of an uninitialized int variable in java, q. which keyword is used to declare a constant variable in java, q. which of the following is a valid variable declaration in java, q. what is the scope of a local variable in java, q. what is the difference between instance variables and local variables in java, q. what is the purpose of the final keyword in java, q. what is the data type of the variable "name" in the following code snippet: string name = "john";, q. what is the correct way to declare an integer variable in java, q. what will be the value of x after executing the following code snippet, q. what is the correct syntax to declare a constant variable in java, q. which of the following statements is true about variable names in java, q. what is the scope of a variable declared inside a method in java, q. what is the default value of an uninitialized integer variable in java, q. which of the following is a valid variable name in java, q. what is the difference between local variables and instance variables in java, q. which of the following is the correct way to declare a string variable in java, q. what is the purpose of initializing a variable in java, popular posts.

  • Spring Boot Interview Questions
  • Implement Spring Boot Security and understand Spring Security Architecture
  • E-commerce Website - Online Book Store using Angular 8 + Spring Boot
  • Spring Boot +JSON Web Token(JWT) Hello World Example
  • Angular 7 + Spring Boot Application Hello World Example
  • Build a Real Time Chat Application using Spring Boot + WebSocket + RabbitMQ
  • Pivotal Cloud Foundry Tutorial - Deploy Spring Boot Application Hello World Example
  • Deploying Spring Based WAR Application to Docker
  • EIP patterns using Apache Camel
  • Spring Cloud- Netflix Eureka + Ribbon Simple Example
  • Spring Cloud- Netflix Hystrix Circuit Breaker Simple Example
  • Spring Boot + Swagger Example Hello World Example
  • Spring Boot Batch Simple example
  • Spring Boot + Apache Kafka Example
  • Spring Boot Admin Simple Example
  • Spring Boot Security - Introduction to OAuth
  • Spring Boot OAuth2 Part 1 - Getting The Authorization Code
  • Spring Boot OAuth2 Part 2 - Getting The Access Token And Using it to Fetch Data.
  • JBoss Drools Hello World-Stateful Knowledge Session using KieSession
  • Understand Drools Stateful vs Stateless Knowledge Session
  • JBoss Drools- Understanding Drools Decision Table using Simple Example
  • Spring Batch Interview Questions
  • Spring AOP Interview Questions
  • Angular 2 Interview Questions
  • Apache Camel Interview Questions
  • JBoss Fuse Interview Questions
  • Drools Interview Questions
  • Java 8 Interview Questions
  • Spring Cloud Interview Questions
  • Microservices Interview Questions
  • Java HashMap and ConcurrentHashMap Interview Questions
  • Snowflake frequently asked interview questions
  • SAP FI - Accounts Receivable frequently asked interview questions
  • Top SAP ALV Interview Questions
  • Top SAP Business Objects Administration Interview Questions
  • EC2 frequently asked interview questions
  • Mule ESB frequently asked interview questions
  • Apache Kafka Interview Questions
  • Tosca Testing Tool Interview Questions
  • Top Maven Build Tool Interview Questions
  • Top Gradle Build Tool Interview Questions
  • Miscellaneous Topics

Java Variables MCQ

Java is one of the most popular programming languages in the world. If you’re a beginner, it’s crucial to understand the fundamentals of Java, and variables are a great place to start. Test your knowledge with this Java Variables Quiz consisting of 10 multiple choice questions.

Each question is followed by the correct answer and an explanation to help reinforce your knowledge.

1. Which of the following is a valid variable declaration in Java?

Explanation:.

In Java, variable names cannot begin with numbers (option a), cannot have single quotes (option c), and type names are case-sensitive, meaning string is incorrect, it should be String (option d).

2. Which data type is used to store a single character in Java?

In Java, the char data type is used to store a single character.

3. How many bytes does an int data type occupy in Java?

In Java, an int data type occupies 4 bytes.

4. Which of the following is the correct way to declare multiple variables of the same type?

All the given options are valid ways to declare multiple variables in Java.

5. Which keyword in Java is used for constant variables?

In Java, the final keyword is used to declare constant variables.

6. What will be the default value of an int variable if not initialized in a class?

If an int variable is a member of a class and is not initialized, its default value is 0.

7. Which of the following is a valid variable name in Java?

Variable names in Java can contain letters, digits, underscores, and dollar signs. They cannot start with a digit or contain Java-reserved words like float.

8. The boolean data type in Java can have values:

The boolean data type in Java can only have the values true or false .

9. Which data type can be used to store large decimal numbers in Java?

The double data type is used to store large decimal numbers in Java.

10. What is the use of Variables in Java?

Variables in Java are containers for storing data values, allowing the program to manipulate or access these values.

11. Which data type is used to store text value in Java?

The 'String' data type in Java is used to store text values, which are enclosed in double quotes.

12. What is the purpose of the 'final' keyword in variable declarations in Java?

The 'final' keyword in Java is used to declare a variable as constant or unchangeable, making it read-only after its initial assignment.

13. What type of variable in Java is best suited for storing large whole numbers?

The 'long' data type in Java is used for storing large whole numbers, which are bigger than what 'int' can store.

14. In Java, what is the default value of a boolean variable?

The default value of a boolean variable in Java is 'false' if it is not explicitly initialized.

15. What happens when you assign a new value to an existing variable in Java?

When a new value is assigned to an existing variable in Java, the original value is overwritten with the new one.

This quiz should give beginners a basic understanding of Java variables. If you got all the answers correct, well done! If not, don’t worry; practice makes perfect. Keep studying and practicing!

Related MCQ (Multiple Choice Questions) :

C++ functions mcq, java control statements mcq, java loops mcq, java arrays mcq, java multithreading mcq, java string mcq, java operators mcq, java exception handling mcq, java data types mcq, java methods mcq, java objects and classes mcq, java abstraction mcq, leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Python Variables Quiz

Interactive Quiz ⋅ 9 Questions By John Sturtz

Test your understanding of Python variables and object references.

Take this quiz after reading our Variables in Python tutorial.

« Browse All Python Quizzes

variables and assignments quiz (mcqs)

  • C MCQ Topics
  • About & History
  • Printf & Scanf
  • Variables & Datatypes
  • Control St. & Loops
  • Array & String
  • Functions & Pointers
  • Structure & Union
  • Memory Allocation
  • File Handling
  • Preprocessor & Macros
  • Storage Classes
  • Type Conversion
  • Command Line Arguments
  • Error Handling
  • Multithreading
  • Date & Time
  • Mathematical Functions
  • C Programming Reference
  • Learn C Programming
  • C Programming Books
  • C Interview Questions
  • C Programming Quiz
  • C Coding Questions
  • Other Reference
  • Quantitative Aptitude
  • Learn Computer Architecture
  • Javascript Interview Questions

C Programming Multiple Choice Question - Variables And Datatypes

This section focuses on the "Variables And Datatypes" of the C programming. These Multiple Choice Questions (mcq) should be practiced to improve the C programming skills required for various interviews (campus interview, walk-in interview, company interview), placement, entrance exam and other competitive examinations.

A. 31 B. 32 C. 64 D. 63

Explanation: There are total 32 keywords in C.Keywords are those words whose meaning is already defined by Compiler.C Keywords are also called as Reserved words.

A. Variable names cannot start with a digit B. Variable can be of any length C. They can contain alphanumeric characters as well as special characters D. Reserved Word can be used as variable name

Explanation: Variable names cannot start with a digit in C Programming language.

A. TRUE B. friend C. export D. volatile

Explanation: volatile is C keyword.Volatile in C programming language signify that the compiler that the software in hand (the thread for the routine it’s compiling) doesn’t have exclusive control over the variable described as "volatile"

A. Compilations Error B. 10 C. 10 D. 10.1

Explanation: Since the variable x is defined both as integer and as float, it results in an error.

A. Syntax error in declaration of a B. No errors, program will show the output 5 C. Redeclaration of a in same scope throws error D. a is out of scope when printf is called

Explanation: the output of this program is the Syntax error in declaration of variable a.

A. Garbage Value B. 20 C. Compiler Error D. None of these

Explanation: First var is declared, then value is assigned to it. As soon as var is declared as a local variable, it hides the global variable var.

A. 2 bytes B. 4 bytes C. 8 bytes D. Depends on the system/compiler

Explanation: The size of the datatypes depend on the system.The size of "int", in fact every other data type as well is compiler dependent and not language dependent. Based on how a compiler is implemented, it can take either 2 bytes or 4 bytes.

A. TRUE B. FALSE C. May Be D. Can't Say

Explanation: The range of double is -1.7e+308 to 1.7e+308.

A. Constant variables need not be defined as they are declared and can be defined later B. Global constant variables are initialized to zero C. const keyword is used to define constant values D. You cannot reassign a value to a constant variable

Explanation: Since the constant variable has to be declared and defined at the same time, not doing it results in an error..

A. Derived Data type B. Primitive Data type C. Custom Data type D. None of these

Explanation: Data types simply refers to the type and size of data associated with variables and functions.It is of two types :- Fundamental Data Types and Derived Data Types. Array is Derived Data type datatype in C Programming language.

A. Address of last element of Array B. Value of first element C. Base address of array D. Value of elements in array

Explanation: Base address of array is passed.

A. Rounded B. Truncated C. Depends on the standard D. Depends on the compiler

Explanation: When double is converted to float, the value will be Depends on the compiler.

A. ! B. && C. || D. |

Explanation: && - Logical AND ! - Logical NOT || - Logical OR | - Bitwise OR(used in bitwise manipulations)

A. & B. * C. Both A and B D. None of the above

Explanation: & have different meaning in different contexts.

A. 1 and 2 B. 2 and 4 C. 3 and 4 D. All are valid

Explanation: All are valid. First 3 mean the same thing. 4th means unsigned.

A. 2 B. 3 C. 0 D. 1

Explanation: Without any temporary variable ,one can swap two variables easily. For Example :- var a ,b; a=a+b; b=a-b; a=a-b;

A. The basic data type of C B. Qualifier C. Short is the qualifier and int is the basic datatype D. All of the mentioned

Explanation: short is the qualifier and int is the basic datatype.

A. %, *, /, +, - B. %, +, /, *, - C. %, +, -, *, / D. +, -, %, *, /

Explanation: All arithmetic operators in C language follow the left to right associativity. Their precedence from highest to lowest is as given below: () => Brackets % => Modulus * => Multiplication / => Division + => Addition - => Subtraction In an arithmetic operation, the higher precedence operators are evaluated first followed by the lower value operators.

A. int B. char C. float D. long

Explanation: Float data type will throw an error on modulus operation(%).

A. String B. float C. long D. structure

Explanation: structure cannot be used on Relational operators.

A. 128 B. -128 C. Depends on compiler D. None of the above

Explanation: signed char will be a negative number.

A. a B. 0.000000 C. 97.000000 D. Run time error

Explanation: ASCII value of a is assigned to the float variable x .

A. ceil(6.66) B. floor(6.66) C. roundup(6.66) D. roundto(6.66)

Explanation: The ceil function returns the smallest integer that is greater than or equal to x.

A. 2 B. 4 C. 8 D. Linker Error

Explanation: The statement extern int i specifies to the compiler that the memory for 'i' is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name 'i' is available in any other program with memory space allocated for it. Hence a linker error has occurred.

A. 4 2 1 B. 8 4 4 C. 8 4 2 D. compiler dependent

Explanation: None

A. 1 1 2 3 B. 1 1 2 2 C. 0 1 2 2 D. 0 1 2 3

Explanation: n an expression involving || operator, evaluation takes place from left to right and will be stopped if one of its components evaluates to true(a non zero value). So in the given expression m = i++ || j++ || k++. It will be stop at j and assign the current value of j in m. therefore m = 1 , i = 1, j = 2 and k = 2 (since k++ will not encounter. so its value remain 2)

A. 13 B. 14 C. -14 D. Compilation Error

Explanation: Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus = plus.

A. 5 B. 10 C. 0 D. None of the above

Explanation: 1

A. p=1 q=1 B. p=1 q=2 C. p=2 q=2 D. Invalid Syntex

Explanation: The comma operator evaluates both of its operands and produces the value of the second. It also has lower precedence than assignment. Hence r = p, q is equivalent to r = p, while s = (p, q) is equivalent to s = q.

A. fff0 B. fff1 C. fff2 D. fff3

Explanation: -1 will be represented in binary form as: 1111 1111 1111 1111 Now -1<<4 means 1 is Shifted towards left by 4 positions, hence it becomes: 1111 1111 1111 0000 in hexadecimal form - fff0.

A. 11 3 5 11 B. 11 1 5 11 C. 11 3 2 11 D. 11 3 3 11

Explanation: For any comma separated expression the outcome is the right most part.

A. 30 35 B. 30 30 C. 25 30 D. 25 35

Explanation: a = 5 * 5 and b = 5 * 7

A. 0 B. 1 C. -1 D. NULL

Explanation: EOF is macro which has been defined in stdio.h and it is equivalent to -1.

A. 49 B. 48 C. 10 D. 8

Explanation: It will print the ascii value of 0, i.e it will print the ascii value of last character always

A. Compilation error B. 10 C. Garbage value D. 0

Explanation: Void is not a valid data type for declaring variables.

A. 8 4 2 B. 4 4 1 C. 8 4 1 D. 4 4 2

Explanation: C compiler by default will assign any undeclared float data type as double. Thus 8 4 1 is outputted

A. Compilation error B. 1 0 C. 0 0 D. 0 1

Explanation: Clearly, a != b and it execute the else part, where we ask compiler to display the value of a and b.

A. float B. double C. long double D. far double

Explanation: A double is a more accurate way of representing floating point numbers due to more digits of precision and defaulting to a double for constants will yield more accurate and consistent answers.

A. char B. int C. float D. double

Explanation: Both %d and %i can be used as a format identifier for int data type.

A. It is not standardized B. To avoid conflicts since assemblers and loaders use such names C. To avoid conflicts since library routines use such names D. To avoid conflicts with environment variables of an operating system

Explanation: To avoid conflicts since library routines use such names.

Also check :

  • java programming tutorial
  • C++ programming tutorial

* You must be logged in to add comment.

examveda.com

Data Types and Variables -Java Programming MCQ Questions and Answers

Section 1 Section 2

1. What is the maximum value that can be stored in a byte variable in Java?

Answer & solution, 2. which data type is used to store a single character in java, 3. what is the default value of an int variable in java if it's not explicitly initialized, 4. which of the following is not a valid identifier for a java variable, 5. which data type is used to store floating-point numbers with single precision in java, 6. in java, which data type is used to represent true or false values, 7. what is the size of a long variable in java.

D. 16 bytes

8. Which of the following is a valid way to declare a constant in Java?

A. final int PI

B. const float PI

C. static double PI

D. final double PI

9. What is the range of values that can be stored in a short variable in Java?

A. -128 to 127

B. -32,768 to 32,767

C. 0 to 65,535

D. -1,000,000 to 1,000,000

10. Which of the following is a primitive data type in Java?

1 2 3 4 5 6 7 8 9 10

Read More Section(Data Types and Variables)

Each Section contains maximum 100 MCQs question on Data Types and Variables . To get more questions visit other sections.

  • Data Types and Variables - Section 2

Python Programming

Python Variables

Updated on:  August 31, 2021 | 19 Comments

A variable is a reserved memory area (memory address) to store value . For example, we want to store an employee’s salary. In such a case, we can create a variable and store salary using it. Using that variable name, you can read or modify the salary amount.

In other words, a variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python.

A variable can be either mutable or immutable . If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable. We will learn the difference between mutable and immutable types in the later section of this article.

Also, Solve :

  • Python variables and data type Quiz
  • Basic Python exercise for beginners

Table of contents

Creating a variable, changing the value of a variable, integer variable, float variable, complex type, string variable, list type variable, get the data type of variable, delete a variable, variable’s case-sensitive, assigning a value to a constant in python, rules and naming convention for variables and constants, assigning a single value to multiple variables, assigning multiple values to multiple variables, local variable, global variable, object reference, unpack a collection into a variable.

Python programming language is dynamically typed, so there is no need to declare a variable before using it or declare the data type of variable like in other programming languages. The declaration happens automatically when we assign a value to the variable.

Creating a variable and assigning a value

We can assign a value to the variable at that time variable is created. We can use the assignment operator = to assign a value to a variable.

The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value.

In the above example, “John”, 25, 25800.60 are values that are assigned to name , age , and salary respectively.

Many programming languages are statically typed languages where the variable is initially declared with a specific type, and during its lifetime, it must always have that type.

But in Python, variables are dynamically typed  and not subject to the data type restriction. A variable may be assigned to a value of  one type , and then later, we can also re-assigned a value of a different type . Let’s see the example.

Create Number, String, List variables

We can create different types of variables as per our requirements. Let’s see each one by one.

A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values.

The  int is a data type that returns integer type values (signed integers); they are also called  ints or integers . The integer value can be positive or negative without a decimal point.

Note : We used the built-in Python method type() to check the variable type.

Floats are the values with the decimal point dividing the integer and the fractional parts of the number.  Use float data type to store decimal values.

In the above example, the variable salary assigned to value 10800.55, which is a float value.

The complex is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values.

In Python, a string is a set of characters  represented in quotation marks. Python allows us to define a string in either pair of  single  or  double quotation marks. For example, to store a person’s name we can use a string type.

To retrieve a piece of string from a given string, we can use to slice operator [] or [:] . Slicing provides us the subset of a string with an index starting from index 0 to index end-1.

To concatenate the string, we can use  the addition (+) operator.

If we want to represent  a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact.

Read : Complete Guide on Python lists

The list can be accessed in two ways, either positive or negative index.  The list has the following characteristics:

  • In the list insertion order of elements is preserved.
  • Heterogeneous (all types of data types int , float , string ) elements are allowed.
  • Duplicates elements are permitted.
  • The list is mutable(can change).
  • Growable in nature means based on our requirement, we can increase or decrease the list’s size.
  • List elements should be enclosed within square brackets [] .

No matter what is stored in a variable (object), a variable can be any type like int , float , str , list , tuple , dict , etc. There is a built-in function called type() to get the data type of any variable.

The type() function has a simple and straightforward syntax.

Syntax of type() :

If we want to get the name of the datatype only as output, then we can use the __name__ attribute along with the type() function. See the following example where __name__ attribute is used.

Use the del keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector.

Now, let’s delete var1 and try to access it again.

Python is a case-sensitive language. If we define a variable with names a = 100 and A =200 then, Python differentiates between a and A . These variables are treated as two different variables (or objects).

Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is  not applicable . By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it.

 Example

It is just convention, but we can change the value of MAX_VALUE variable.

As we see earlier, in the case of Python, the constant concept is not applicable. But if we still want to implement it, we can do it using the following way.

The declaration and assignment of constant in Python done with the module. Module means Python file ( .py ) which contains variables, functions, and packages.

So let’s create two modules, constant.py  and main.py , respectively.

  • In the constant.py file, we will declare two constant variables,  PI and TOTAL_AREA .
  • import constant module In main.py file.

To create a constant module write the below code in the constant.py file.

Constants are declared with uppercase later variables and separating the words with an underscore.

Create a  main.py  and write the below code in it.

Note : Constant concept is not available in Python. By convention, we define constants in an uppercase letter to differentiate from variables. But it does not prevent reassignment, which means we can change the value of a constant variable.

A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name.

There are some rules to define variables in Python.

In Python, there are some conventions and rules to define variables and constants that should follow.

Rule 1 : The name of the variable and constant should have a combination of letters, digits, and underscore symbols.

  • Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z)
  • Digits(0 to 9)
  • Underscore symbol (_)

Example 

Rule 2 : The variable name and constant name should make sense.

Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful.

It above example variable x does not make more sense, but student_name  is a meaningful variable.

Rule 3: Don’t’ use special symbols in a variable name

For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error

Rule 4:  Variable and constant should not start with digit letters.

You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example.

Here Python will generate a syntax error at 1studnet . instead of this, you can declare a variable like studnet_1 = "Jessa"

Rule 5:  Identifiers are case sensitive.

Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables total , Total , TOTAL .

Rule 6:  To declare constant should use capital letters.

Rule 6: Use an underscore symbol for separating the words in a variable name

If we want to declare variable and constant names having two words, use an underscore symbol for separating the words.

Multiple assignments

In Python, there is no restriction to declare a variable before using it in the program. Python allows us to create a variable as and when required.

We can do multiple assignments in two ways, either by assigning a single value to multiple variables  or assigning  multiple values to multiple variables .

we can assign a single value to multiple variables simultaneously using the assignment operator = .

Now, let’s create an example to assign the single value 10 to all three variables a , b , and c .

In the above example, two integer values 10 and 70 are assigned to variables roll_no and marks , respectively, and string literal, “Jessa,” is assigned to the variable name .

Variable scope

Scope : The scope of a variable refers to the places where we can access a variable.

Depending on the scope, the variable can categorize into two types  local variable and the global variable.

A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error.

In the above example, we created a function with the name test1 . Inside it, we created a local variable price. Similarly, we created another function with the name test2 and tried to access price, but we got an error "price is not defined" because its scope is limited to function test1() . This error occurs because we cannot access the local variable from outside the code block.

A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.

In the above example, we created a global variable price and tried to access it in test1 and test2 . In return, we got the same value because the global variable is accessible in the entire file.

Note : You must declare the global variable outside function.

Object/Variable identity and references

In Python, whenever we create an object, a number is given to it and uniquely identifies it. This number is nothing but a memory address of a variable’s value. Once the object is created, the identity of that object never changes.

No two objects will have the same identifier. The Object is for eligible garbage collection when deleted. Python has a built-in function id() to get the memory address of a variable.

For example, consider a library with many books (memory addresses) and many students (objects). At the beginning(when we start The Python program), all books are available. When a new student comes to the library (a new object created), the librarian gives him a book. Every book has a unique number (identity), and that id number tells us which book is delivered to the student (object)

It returns the same address location because both variables share the same value. But if we assign m to some different value, it points to a different object with a different identity.

See the following example

For m = 500 , Python created an integer object with the value 500 and set m as a reference to it. Similarly, n is assigned to an integer object with the value 400 and sets n as a reference to it. Both variables have different identities.

In Python, when we assign a value to a variable, we create an object and reference it.

For example, a=10 , here, an object with the value  10 is created in memory, and reference a now points to the memory address where the object is stored.

Suppose we created a=10 , b=10 , and  c=10 , the value of the three variables is the same. Instead of creating three objects, Python creates only one object as  10  with references such as  a , b , c .

We can access the memory addresses of these variables using the id() method. a , b refers to the same address  in memory, and c , d , e refers to the same address. See the following example for more details.

Here, an object in memory initialized with the value 10 and reference added to it, the reference count increments by ‘1’.

When Python executes the next statement that is b=10 , since it is the same value 10, a new object will not be created because the same object in memory with value 10 available, so it has created another reference, b . Now, the reference count for value 10 is ‘2’.

Again for  c=20 , a new object is created with reference ‘c’ since it has a unique value (20). Similarly, for d , and e  new objects will not be created because the object ’20’ already available. Now, only the reference count will be incremented.

We can check the reference counts of every object by using the getrefcount function of a  sys module. This function takes the object as an input and returns the number of references.

We can pass variable, name, value, function, class as an input to getrefcount() and in return, it will give a reference count for a given object.

See the following image for more details.

Python object id references

In the above picture, a , b pointing to the same memory address location (i.e., 140722211837248), and c , d , e pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2 and 3 respectively.

  • In Python, we can create a tuple (or list) by packing a group of variables.
  • Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing.

Here a , b , c , d  are packed in the tuple tuple1 .

Tuple unpacking  is the reverse operation of tuple packing . We can unpack tuple and assign tuple values to different variables.

Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError .

Also, See :

  • Class Variables
  • Instance variables

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

variables and assignments quiz (mcqs)

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

COMMENTS

  1. Variables and Assignments Quiz (MCQs) Flashcards

    A teacher is writing a code segment that will use variables to represent a student's name and whether or not the student is currently absent. Which of the following variables are most appropriate for the code segment? A string variable named studentName and a Boolean variable named isAbsent. Consider the following code segment. p <- 10. q <- 20.

  2. Variables and Assignments Quiz (MCQs)

    Quiz yourself with questions and answers for Variables and Assignments Quiz (MCQs), so you can be ready for test day. Explore quizzes and practice tests created by teachers and students or create one from your course material.

  3. 2.1 Variables and assignments Flashcards

    Study with Quizlet and memorize flashcards containing terms like Write a variable assignment statement with assigns totalpets with 3., Write a variable assignment statement that assigns luckyNumber with 7 and suppresses the output to the command window., Write a variable assignment statement that assigns birdFeeders with the current value of variable stockCount, and prints the value of the ...

  4. Variables and Assignments Quiz (MCQs) with Flashcards

    Take our variables and assignments quiz with MCQs and flashcards to test your programming skills and learn concepts like assignment statements and data types. ← Recent Show all ... Test your knowledge on variables, assignment statements, and expressions in programming. Learn about defining and initializing variables, using the assignment ...

  5. Python Variables and Data Types Quiz [15 Quiz Questions]

    Read all the given answers and click over the correct answer. Read Variables in Python and Python Data Types to solve this quiz. 1. What is the output of the following code. 2. Please select the correct expression to reassign a global variable " x " to 20 inside a function fun1() # your code to assign global x = 20. 3.

  6. Python Variables Multiple-Choice Questions (MCQs)

    Python Variables MCQs: This section contains multiple-choice questions and answers on Python Variables. These MCQs are written for beginners as well as advanced, practice these MCQs to enhance and test the knowledge of Python Variables. List of Python Variables MCQs. 1. What are variables? Variables are used to identify the module, class i.e ...

  7. Variables MCQ [Free PDF]

    Get Variables Multiple Choice Questions (MCQ Quiz) with answers and detailed solutions. Download these Free Variables MCQ Quiz Pdf and prepare for your upcoming exams Like Banking, SSC, Railway, UPSC, State PSC. ... Matching subjects with random assignments: It is used for assigning subjects to groups to match individual subjects on extraneous ...

  8. Java Variables Quiz

    Java is one of the most popular programming languages in the world. If you're a beginner, it's crucial to understand the fundamentals of Java, and variables are a great place to start. Test your knowledge with this Java Variables Quiz consisting of 10 multiple-choice questions.

  9. Variables and Assignments

    10. 20. 30. 40. What are the values of first and second as a result of executing the code segment? The value of first is true, and the value of second is true. The value of first is true, and the value of second is false. The value of first is false, and the value of second is true. The value of first is false, and the value of second is false.

  10. Java Variables MCQ

    This multiple choice quiz on Java variables assesses your understanding of variable declaration, initialization, scope, and data type compatibility. Test your knowledge on how variables are defined, assigned values, and utilized in Java programming. This quiz covers fundamental concepts essential for mastering Java variable handling.

  11. 3.1 Variables and assignments (general) Flashcards

    In a program, a variable is a named item, such as x or numPeople, used to hold a value. assignment. An assignment assigns a variable with a value, such as x = 5. That assignment means x is assigned with 5, and x keeps that value during subsequent assignments, until x is assigned again. An assignment's left side must be a variable.

  12. Python Variables MCQ

    Here we present 15 multiple-choice questions to test your knowledge of Python variables. Each MCQ has the correct answer with an explanation. 1. Which of the following is a valid variable name in Python? a) 1_variable. b) variable_name. c) variable-name. d) None of the above. Click to View Answer and Explanation.

  13. Python Operators and Expression Quiz [15 Quiz Questions]

    The quiz contains 15 Questions. Solve 10 correct to pass the test. You will have to read all the given answers and click over the correct answer. The page will reload after Quiz submission. After submission, scroll the page to view the result. 1. What is the output of the expression print(-18 // 4) -4. 4.

  14. Java Variables MCQ

    Java is one of the most popular programming languages in the world. If you're a beginner, it's crucial to understand the fundamentals of Java, and variables are a great place to start. Test your knowledge with this Java Variables Quiz consisting of 10 multiple-choice questions.Each question is followed by the correct answer and an explanation to help reinforce your knowledge.

  15. Python MCQ Questions On Variables & Operators

    Python MCQs - Variables And Operators. This section focuses on the "Variables And Operators" of the Python programming. These Multiple Choice Questions (mcq) should be practiced to improve the Python programming skills required for various interviews (campus interview, walk-in interview, company interview), placement, entrance exam and other competitive examinations.

  16. Python Variables Quiz

    Python Variables Quiz. Test your understanding of Python variables and object references. Take this quiz after reading our Variables in Python tutorial. The quiz contains 9 questions and there is no time limit. You'll get 1 point for each correct answer. At the end of the quiz, you'll receive a total score. The maximum score is 100%. Good luck!

  17. Variables and Assignment Flashcards

    What is an expression? An expression is a combination of literals, operators, variables, and parentheses used to calculate a value. Which one of the following expressions is NOT correct? (-12 + (13 + 7)/2 ) * 4. Which of the following expressions is NOT correct? 34 - 86) / (23 - 3 ) What is the value of the following expression: (2 - 6) / 2 + 9.

  18. C MCQ Questions

    C Programming Multiple Choice Question - Variables And Datatypes. This section focuses on the "Variables And Datatypes" of the C programming. These Multiple Choice Questions (mcq) should be practiced to improve the C programming skills required for various interviews (campus interview, walk-in interview, company interview), placement, entrance exam and other competitive examinations.

  19. Data Types and Variables -Java Programming MCQ Questions and ...

    Option A: -128 to 127 - This range corresponds to a. Option C: 0 to 65,535 - This range corresponds to an unsigned is signed and can have both positive and negative values. Option D: -1,000,000 to 1,000,000 - This range exceeds the capacity of a variable, which can only store values up to 32,767. 10.

  20. Flashcards Variables and Assignments Quiz (MCQs)

    Variables and Assignments Quiz (MCQs) Log in. Sign up. Get a hint. The variable age is to be used to represent a person's age, in years. Which of the following is the most appropriate data type for age ?

  21. 30 Multiple-Choice Questions on Python Variables

    Explanation: Inside the inner_test() function, the nonlocal keyword allows modification of the x variable from the outer test() function. Therefore, the output within the test() function is 25, but outside of it, x remains 20. Congratulations on completing this set of multiple-choice questions on Python variables!

  22. Python Variables

    The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable's value. ... Each Quiz contains 12-15 MCQ; Exercises. Quizzes. Posted In. Python Python Basics. Tweet F share in share P Pin. Python Tutorials. Get Started with Python ...

  23. AP Comp Sci Principles- Unit 4 Variables, Conditionals, and ...

    For example: =, ≠, >, <, ≥, and ≤. Selection. determines which parts of an algorithm are executed based on a condition being true or false. String. an ordered sequence of characters. Study with Quizlet and memorize flashcards containing terms like Expression, Assignment Operator, Variable and more.